I have an AS3 application that shows users tweets. I'm trying to use the twitter intents links to do popups, such as https://twitter.com/intent/retweet?tweet_id=93035636432437248.
When you have a simple href="link" it will use the embedded http://platform.twitter.com/widgets.js to properly format a nice popup window.
When in flash I can only open in self or blank and neither triggers the JavaScript the same way it does when you click from html href links.
I also tried using ExternalInterface to call a js method to use document.location or window.open and neither used the twitter js.
What is the best way to harness the Twitter JavaScript from a flash button so we get the nice clean popup window?
Looking at the Twitter Web Intents API Documentation, near the bottom of the page you can find a link to the unobfuscated source code which shows how their API automatically handles links.
Put simply they are attaching a Click Event Handler to the DOM which then checks to see if the link being clicked points to their Web Intents URL. As you are opening a window from ActionScript you are bypassing the DOM and therefore the code won't fire.
Now normally you would just expect to use ExternalInterface to call a method exposed by the Web Intents API; however the clever chaps at Twitter have created their entire API in an anonymous closure to avoid polluting the DOM - gotta love javascript ;)
So, personally, I would tackle this by creating my own version of the Twitter Web Intents API and including it on the HTML page which my Flash Application sits; for example:
// Create a global object which we can attach methods to.
var TwitterAPI = {};
// The methods themselves are created in a closure to avoid polluting the global
// namespace with temporary variables.
(function() {
// The base URL of the Twitter API.
TwitterAPI.baseURL = "https://twitter.com/intent/";
// Opens a pop-up window and prompts the user to retweet the Tweet linked to
// the supplied tweet_id.
TwitterAPI.retweet = function(tweet_id) {
var url = TwitterAPI.baseURL + "retweet?tweet_id=" + tweet_id;
openWindow(url);
}
function openWindow(url) {
var windowOptions = "scrollbars=yes,resizable=yes,toolbar=no,location=yes";
var width = 550;
var height = 420;
// Center the popup window.
var left = Math.round((screen.width / 2) - (width / 2));
var top = 0;
if (screen.height > height) {
top = Math.round((screen.height / 2) - (height / 2));
}
window.open(url, 'intent', windowOptions + ",width=" + width +
",height=" + height + ",left=" + left + ",top=" + top);
}
}());
You can then invoke this from your ActionScript project via an ExternalInterface call, as you previously suggested:
ExternalInterface.call("TwitterAPI.retweet", "35782000644194304");
Related
I'm using the Facebook Javascript SDK to post on my page, i've already read something about this here: Facebook feed dialog: allow user to select destination page or group so I've been using this code so far:
$("button#shareOn").on('click',function(event){
event.preventDefault();
var _parentForm=$(this).parents('form:first');
var _pageSelect=_parentForm.find("select[name='pagesList']");
var _pID=_parentForm.find("#pID").attr('value');
var _vURL=_parentForm.find("#_vURL").attr('value');
FB.ui({
app_id:app_id,
method: 'feed',
from: _pageSelect.val(),
name: 'Title',
caption: 'Subtitle - 26/02/2013',
description: 'My text',
link: _vURL,
},function(response){
console.log(response);
});
});
Where _pageSelect.val() is the ID of the page in which I'm trying to post, _vURL is the url ( youtube link ) which I want to share... The problem is that when I click on the button, a window opens up, but's actually blank.
By opening Google Chrome's dev console, sometimes I see a 500 Internal Server error related to that window and sometimes it only comes up totally empty, but I can't figure out what is actually causing it.
I've also tried urlencode the url from PHP or encodeURIComponent from Javascript, but nothing as changed at all.
Sometimes the window comes up only with Title, Subtitle and Description, so I guess the link should be the error, but I knew that Facebook JS SDK used to write Link not properly formatted or something like API error (100).
UPDATE
It seems that Feed dialog has started collaborating, but still not working as expected. This is the updated code:
$("button#shareOn[name='shareVideo']").on('click',function(event){
event.preventDefault();
var _parentForm=$(this).parents('form:first');
var _pageSelect=_parentForm.find("select[name='pagesList']");
var _pID=_parentForm.find("#pID").attr('value');
var _vURL=_parentForm.find("#_vURL").attr('value');
var options={
app_id:app_id,
method:'feed',
from:_pageSelect.val(),
link:_vURL,
caption:'test'
}
console.log(options);
FB.ui( options, function(response){});
});
The window is opening, but sometimes it's blank and sometimes shows a link, which is not the url of the video, but it's just www.youtube.com. I've been trying with the Facebook URL Debugger and it's showing me that the URL which I'm using is actually right. But feed dialog just doesn't work
So, I've got the answer, which isn't really what I was expecting, but at least it works. As the Facebook docs aren't pointing to this, I've found the sharer method, which I call in a Javascript function.
So, this is the code:
$("button#shareOn[name='shareVideo']").on('click',function(event){
event.preventDefault();
var _parentForm=$(this).parents('form:first');
var _pageSelect=_parentForm.find("select[name='pagesList']");
var _pID=_parentForm.find("#pID").attr('value');
var _vURL=_parentForm.find("#_vURL").attr('value');
var leftPosition, topPosition;
var windowFeatures = "status=no,height=" + 400 + ",width=" + 300 + ",resizable=yes,left=" + leftPosition + ",top=" + topPosition + ",screenX=" + leftPosition + ",screenY=" + topPosition + ",toolbar=no,menubar=no,scrollbars=no,location=no,directories=no";
leftPosition = (window.screen.width / 2) - ((300 / 2) + 10);
topPosition = (window.screen.height / 2) - ((400 / 2) + 50);
window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(_vURL),'sharer', windowFeatures);
return false;
});
By the way, I don't like this method, but it seems like the only way to accomplish what i was trying to do. Now I just need to know how to get the result of the sharing function ( if the post was shared or not ).
Hope this will help someone :)
I have a program where i have a page in the local context and within this page i have got an iframe where the content of it is in the web context. Now I would like to send some data from the local context to the web context. How do i do this.
local
var node = document.createElement("iframe");
node.src = 'ms-appx-web:///pages/mapView/mapView.html?latitude=' + coordinates.latitude + '&longitude=' + coordinates.longitude;
node.style.width = '100%';
node.style.height = '100%';
node.onload = function () {
node.contentWindow.postMessage(JSON.stringify(data), "ms-wwa-web://" +
document.location.host);
}
document.querySelector('#insert').appendChild(node);
in the iframe i do:
window.addEventListener('message', receiveMsg, false);
I have got an ajax call where i got some data, but because i have no access to ajax calls in web context i would like to send some data from this here to mapView.html.
The problem is. I would send some values via Get Parameter, but I have too much data for that.
any help?
Try switching this line:
node.contentWindow.postMessage(JSON.stringify(data), "ms-wwa-web://" +
document.location.host);
... to this:
node.contentWindow.postMessage(JSON.stringify(data), "*");
If that works, you should be ok doing that here in a Win 8 app (wouldn't do that in a web app for security reasons), but if you want to lock it down more I think you'd just need to change the second parameter to be one of:
"ms-www-web:///" (note the triple slash)
"ms-www-web:///pages/"
how can i set different zoom levels on different site. can i use window.location to get the url from the chrome address bar and set a zoom level for that specific site how can i modify this code to use window.location or window.location.href
function zoom(zp) {
page = document.getElementsByTagName('html')[0]
if (page != null) {
page.style.zoom = zp + "%";
}
}
chrome.extension.sendRequest(
{"type": "setZoom"},
function(zp) {
zoom(zp);
}
);
Firstly, note that Chrome already handles setting per-domain zoom levels set by C+ + and C+ -, but this is different from the html.style.zoom.
You can certainly do what you're trying to, but you'll need to inject a content script into the page whose CSS you want to manipulate. Then, you can send messages to that injected script from another part of your extension and get the desired result. You can keep track of zoom levels per URL by (for example) storing a {url: zoomLevel} hash table in your extension's localStorage.
Note that there are problems using the html.style.zoom property: for example, it doesn't work on iframes. There's an extensive discussion about this here: http://crbug.com/30583
Now that I discovered here that I can't write JavaScript within one page to enter form data on another external page, I'd like to do this with a browser-based bookmarklet instead.
I'm able to access the data on my original page with this bookmarklet code snippet:
javascript:var%20thecode=document.myForm.myTextArea.value;
If I open the external Web-based form manually in the browser, this code changes what's in the text box:
javascript:void(document.externalForm.externalTextArea.value="HELLO WORLD"));
And this bookmarklet code will open a new browser window with the external form:
javascript:newWindow=window.open("http://www.url.com","newWindow");if(window.focus){void(newWindow.focus());}
However, when I try to put these snippets together in a single bookmarklet to open the external form in a new window and change the data inside, I can't access any of the elements in newWindow. For example, this doesn't work to check the existing value of the text area in the new window
javascript:var%20newWindow=window.open("http://www.url.com","newWindow");if(window.focus){void(newWindow.focus());}window.alert(newWindow.document.externalForm.externalTextArea.value);
Once I use the bookmarklet code to open the new window as newWindow, I don't seem to be able to access the elements within that new window. Any suggestions what I'm missing? Thanks.
That's because the bookmarklet runs within the sandbox (the environment) of the current web page. Since you're not allowed to access (the DOM of) another page which doesn't have the same protocol, domain name and port, you're not able to access the document property of newWindow when protocols, domains and ports don't match. BTW, the same is true for accessing iframes on a page.
As you're talking about an “external form”, I guess you don't stay on the same domain. The other examples retrieve or manipulate data on the current page (at that moment) and won't error out.
Also see Same origin policy.
Update: About the Delicious (et al.) bookmarklet: its code actually reads:
(function () {
f = 'http://delicious.com/save?url=' + encodeURIComponent(window.location.href) + '&title=' + encodeURIComponent(document.title) + '&v=5&';
a = function () {
if (!window.open(f + 'noui=1&jump=doclose', 'deliciousuiv5', 'location=yes,links=no,scrollbars=no,toolbar=no,width=550,height=550'))
location.href = f + 'jump=yes'
};
if (/Firefox/.test(navigator.userAgent)) {
setTimeout(a, 0)
} else {
a()
}
})()
So, yes, the parameters are only transferred using a GET request.
I'm writing a greasemonkey script to keep session open on a webapp I use for work.
Which javascript command would you use to create some feedback with the server and ensure the session doesn't fall without having to bother the user making a complete refresh of the page?
I've solved the issue using:
function keepAlive() {
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', "/restricted_file_url");
httpRequest.send(null);
}
setInterval(keepAlive, 840000); //My session expires at 15 minutes
Using some tips from Jesse's answer, here's the complete code.
You will need to update the #match param with your site's domain
// ==UserScript==
// #name Auto session extender
// #namespace http://obive.net/
// #version 0.2
// #description Automatically extend server-side session
// #author Charlie Hayes
// #match http://obive.net/
// #grant GM_getValue
// #grant GM_setValue
// #noframes
// ==/UserScript==
(function() {
'use strict';
console.log('The session for this site will be extended automatically via userscript.');
var minute = 60*1000;
var refreshTime = 15 * minute;
var iframe = document.createElement("iframe");
iframe.style.width = 0;
iframe.style.height=0;
var loc = window.location;
var src = loc.protocol +'//' + loc.host + loc.pathname;
src += loc.search ? (loc.search + '&') : '?';
src += 'sessionextendercachebuster=';
var reloadIframe = function(){
var time = new Date().getTime();
var lastRefresh = GM_getValue('lastRefresh');
var timeSinceLastRefresh = time - lastRefresh;
if (!lastRefresh || timeSinceLastRefresh > refreshTime - minute) {
console.log('Auto-extending session');
iframe.src = src + time;
GM_setValue('lastRefresh',time);
setTimeout(reloadIframe, refreshTime);
setTimeout(function(){
// Unload the iframe contents since it might be taking a lot of memory
iframe.src='about:blank';
},10000);
}else{
console.log('Another tab/window probably refreshed the session, waiting a bit longer');
setTimeout(reloadIframe, refreshTime - timeSinceLastRefresh - minute);
}
};
setTimeout(reloadIframe, refreshTime);
document.body.appendChild(iframe);
})();
Second choice
If you absolutely insist on using Greasemonkey, any element.click() method on any event that submits an XMLHTTPrequest should do.
First choice
If you are willing to use a solution that does not require you to write a Greasemonkey script:
ReloadEvery 3.0.0, by Jaap Haitsma
This reloads web pages every so many seconds or minutes. The function is accessible via the context menu (the menu you get when you right click on a web page) or via a drop down menu on the reload button.
It's not what you asked for, but unless you simply want to brush up on your javascript skills, this is probably the most straight-forward method for solving your problem.
If you want to write JavaScript to solve this (the other answers are a lot easier and I would recommend going the easier route), here's what I would do:
Call document.createElement("iframe") to create an iframe
Size the iframe to 0x0, style.display = "none", set the ID to something, and set the src property to a page on the site that will extend your session
Use document.body.appendChild to add the iframe to the page
Using setTimeout refresh the iFrame using window.frames['iframeID'].location.reload(true); and also call setTimeout to refresh the page again.
See if the other answers would work because using JavaScript seems like it would be more trouble than it's worth.
I can definitely recommend the solution suggested by dreftymac!
If you don't want to worry about remembering to click the reloadevery option, your grease monkey script is simply
window.location.href = window.location.href
This is presuming you don't want to keep the page constantly refreshing, as suggested by others.
Ordinarily, if you were simply looking to ping the server, you would probably do best to do something like use an image that you know exists on the remote server, and check it's height - thus creating traffic.
However, your problem (I presume) needs to access some limited area of the website, in order to keep the session active... with this being the case (and the fact that you can't directly ping), find a page that is 'restricted' and do an Ajax call, or similar. Don't quote me on this, as I'm by no means a JavaScript expert... just throwing out a potential solution.