ExternalInterface addCallback repeatedly fails - javascript

I'm trying to get JS in a Wordpress webpage and an Actionscript 2 Flash movie to talk to one another. The attempt is failing miserably. On every attempt to call the function that I've set a callback for, I get "..... is not a function" in the browser error console (I'm using Firefox 20).
Here's how things are set up:
The page is a bit unusual, being a Wordpress page with inline javascript. The main javascript is a jQuery.ready() block of code that loads the flash object (this is done so that GET parameters in the URL can be passed into the flash). Once it's loaded, there's a link with this:
Region A
Meanwhile, the flash object has this in it to make it possible:
import flash.external.ExternalInterface;
System.security.allowDomain("thisdomain.com"); // the domain on which the flash is hosted
ExternalInterface.addCallback("setRegion", null, switchZone); //switchZone is the function's internal name
The flash's container has allowScriptAccess set to "always", and I can confirm that the jQuery statement is hitting the right target. However, when the flash object is debugged, the addCallback returns false— a sign that it's failed. Anyone have any ideas what could be going on?

I met this kind of problem before. To explain this, you may just image your flash file to be a image. Usually, the image in you page will show after the whole page is loaded. For your flash file, in $.ready event, the flash DOM is inserted into your page, but the content of it is loading and the environment of it is not ready yet.
To handle this, you need to register a callback function in your page like this:
window.ping = function () {
$('#fmap')[0].setRegion('regiona');
}
Then in your flash environment, call the ping() registered.
The order of function call is the key point here.

OK, figured it out. First off, the function declaration needed to be above the ExternalInterface.addCallback bit. In addition, once that was done it started throwing a different error, so I had to make a new function... thanks for your help.

Related

Check if html file would open JavaScript alert dialog

I'm wondering if it is possible to, in Java, detect whether or not an HTML file would open an alert dialog if opened in the browser. Preferably headlessly. For example, a file with the below contents were parsed, it would return true.
<html><script>alert("hey")</script></html>
and the below would return true also
<html><iframe src="javascript:alert(1)" onload="alert(2)"></iframe></html>
but the below would return false because it would not open an alert dialog if it were opened in the browser (because none of the code is syntactically correct, and the part that is isn't in a tag).
<html><script>alert;,(123w)</script>alert(1)</html>
I have thought of a way to approach this problem, but it is flawed. Basically, you see if the stringalert(1) is in the file, etc.
The problem with this is that it wouldn't work in cases where that code isn't inside of script tags or tags that make it execute. An example of where it wouldn't work is: The following would return true, even though it wouldn't actually open a popup <html>alert(1)</html>.
This isn't Android by the way. Appreciate your help!
You will need to not only verify if the Alert function is there but check if the JavaScript function would even run. An example of this is if there is a script with an Alert function inside a function that never runs. The Alert function would be there but it would never run. This would give a false positive. So the in the best case you should run the JavaScript in some way to validate the code and to see if the function would ever run.
As Louis pointed out in the comments Option 2 is better in this case as you will need to account for both the DOM and JavaScript's behaviour as both can change if the Alert function runs and how it runs.
Option 1 : Run the JavaScript with Script Engine
You would need some way of separating the HTML from the JavaScript but once you have that you can do this method.
You can run the JavaScript in Java using ScriptEngine. https://docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/api.html
If you read the API there is a way to create variables and communicate between your Java Program and the JavaScript you are Running.
To capture the context of the Alert you can create a custom JavaScript function that overwrites the Alert function. Inside this custom function you can send the arguments of the function back to your Java Program.
Option 2 : Headless Browser
You can also try to use a headless browser like JBrowserDriver and as you can see you have an Alert interface with getText as a function. For async issue the headless browser has a default amount of time for waiting for the script to complete. If this default amount is not enough you can use the setScriptTimeout to handle it.
http://machinepublishers.github.io/jBrowserDriver/

How can I define a property on the tab's main window object?

I'm trying to define the property jQuery on the window object from a content script with code in the setter. That way, when the actual jQuery object is defined, I can use it right away. I seem to be unable to get it right, though.
The target website is Outlook.com. That's the webmail version of Outlook.
I tried to put the code in the content script directly, but even if I put "all_frames": true in the content_scripts section of the manifest (so the code gets injected into every frame), it isn't working.
function afterInit(){
var _jQuery;
console.log('This gets logged');
Object.defineProperty(window, 'jQuery', {
get: function() { return _jQuery; },
set: function(newValue) {
_jQuery = $ = newValue;
console.log('This is never logged!');
$(document.body).append($('<span>I want to use jQuery here</span>'));
}
});
}
afterInit();
I verified that window.jQuery is properly defined afterwards by the actual jQuery function/object, but my setter code is never executed.
I also tried it with message passing: I send a message with the code as a string to a background script, and use executeScript to execute it on the correct tab, but this also doesn't work.
chrome.runtime.sendMessage(
{action:'jQueryPreInit', value: '('+afterInit.toString()+')();'});
And in my background script:
chrome.runtime.onMessage.addListener(function(message, sender, callback) {
switch (message.action){
case "jQueryPreInit": chrome.tabs.executeScript(sender.tab.id, {code: message.value});
}
});
If I put something else than the Object.defineProperty code in the executeScript code, that works fine. I only have problems defining the property.
(quotes are from a comment)
I want to use the jQuery provided by the page itself. I could try inserting the same jQuery file as Outlook does and hope it gets loaded from cache, but I'd rather just keep my extension as clean as possible, and use what is already available.
Your attempt at optimizing the extension is not workable / not recommended.
First off, you will not be able to use the page's code anyway because of the isolation between content script and webpage code. You cannot obtain a reference to page's own jQuery/$.
But let's for a moment suppose that you could. And then the site updates jQuery to another version, renames the jQuery object or stops using it entirely, which is outside your control. Result: your extension is broken. This is, partially, the rationale behind the isolation in the first place.
As a result of the context isolation, you are guaranteed there are no conflicts between your copy of jQuery and whatever runs on the site. So you don't need to worry about that: use your copy, and use the standard $ to access it.
Bundling a <100 KB file with your extension as a one-time download that makes sure code is available 100% of the time and with at worst disk-access latency is not making it less "clean", quite the opposite. It's a common practice and is enshrined in the docs.
Looking at your actual code, it executes in the content script context (regardless whether it's through manifest or executeScript), not in the page context. As such, no matter what the page does, $ will not be defined there.
I verified that window.jQuery is properly defined afterwards by the actual jQuery function/object [...]
I assume that you tried to execute window.jQuery in the console; by default, that executes it in the page context, not in your content script context (therefore, not reflecting the state of the content script context and not invoking your getter/setter). If you want to test your content script, you need to change top in the context drop-down above the console to your extension's context.
All that said, however,
When all is said and done, I want to use jQuery's ajaxSuccess function to execute code every time an e-mail is opened in the read pane.
Here we've got a problem. Since the content script code and webpage code are isolated, your code will never know about AJAX executing in the page's copy (not through ajaxSuccess, anyway).
Possible courses of action:
Rely on other methods to detect the event you want. Perhaps monitoring the DOM.
Inject some code into the page itself; the only way to do so is by injecting a <script> tag into the page from the content script. There, you can access the page's copy of jQuery, attach your listener and message your content script when something happens.
Rely on the background page to detect activity you need with webRequest API. This will likely intercept the AJAX calls, but will not give you the reply contents.
Final note: this may not be as simple as AJAX calls; perhaps the page maintains a WebSocket connection to get realtime push updates. Tapping into this is trickier.
Thanks to Xan, I found there are only two ways to do this.
The first is by adding a <script> element to the DOM containing the appropriate code. This is a pretty extensive StackOverflow answer on how to do that: https://stackoverflow.com/a/9517879/125938.
The second is using Javascript pseudo-URLs and the window.location object. By assigning window.location a bookmarklet-style URL containing Javascript, you also bypass certain security measures. In the content script, put:
location = 'javascript:(' + (function(){
var _jQuery;
Object.defineProperty(window, 'jQuery', {
get: function() { return _jQuery; },
set: function(newValue) {
_jQuery = $ = newValue;
console.log('totally logged!');
$('<span>jQuery stuff here</span>');
}
});
}).toString().replace(/\n/g, ' ')+')();';
The reason I/you were originally failing to define it, was because both methods of code injection we were using, caused our code to be sandboxed into isolated worlds: https://developer.chrome.com/extensions/content_scripts#execution-environment. Meaning, they share the page's DOM and could communicate through it, but they can't access each other's window object directly.

How can I debug this JavaScript error?

I have been asked to fix an issue with a website and I am encountering an issue with a JavaScript error.
On the home page, [removed website link], I am receiving the error Uncaught TypeError: undefined is not a function. However, the function being called on that line (line 30) should exist, as the jQuery plugin is being loaded.
The call-stack just shows a series of anonymous functions pointing towards the jQuery file. I am having trouble determining why this is producing an undefined function error.
I have tried using the Chrome debugger to step through the code where the error occurs but it just seems to highlight the jQuery source file for every step.
My question is this:
How do I go about tracking down the source of the issue when the trail is just a series of anonymous functions in the jQuery source file?
Is there something I am missing here or that I am not considering?
Thank you.
Edit:
As is it not clear, the method being called, jQuery.ContentSlider is in fact being included within the page within the file testimonials.js.
This is not just a "What's wrong with my code" question, but also an inquiry into how I handle situations such as this in the context of JavaScript & jQuery specifically.
A call stack of anonymous functions is confusing to me, and I have already attempted to take the obvious steps, such as verifying the plugin is included and that this inclusion takes place before attempting to utilize that plugin.
Sorry for the confusion.
Edit - Solution Found
It appears that although jQuery and the plugin were included prior to use, another copy of the same jQuery file was being injected by a Joomla! module. Since this was the exact same Google hosted jQuery file, it did NOT appear twice in the Resources tab in the Chrome Developer Tools. It appears that Chrome will parse jQuery twice, but doesn't show it as being included twice. So, the version with the plugin attached was being overwritten.
Thank you to those who answered. Thanks to A. Wolff for bringing that piece of information about the Resource tab to my attention.
You're loading the slider after you instantiate it.
Reverse the order of these two blocks:
<script type="text/javascript">
$(function() {
jQuery('#two').ContentSlider({
width : '440px',
height : '240px',
speed : 400,
easing : 'easeOutQuad',
textResize : true
});
});
</script>
<script src="/templates/sp/javascript/jquery.sudoSlider.min.js"></script>
Edit: To the heart of your well-formed question about debugging, generally, Undefined is not a function, especially when dealing with frameworks, is a symptom of trying to access a method before it exists, which is why your attempted function call returns undefined rather than a function.
It's almost always the result of loading a framework after trying to call it, or in an asynchronous context, of not waiting for the framework to load or do something important.
EDIT 2: The above answer is not correct, as A.Wolff points out: it's not that you must reverse the order of the two blocks, but that:
1) The second framework is probably not the one you want, or
2) You have called jQuery('#two').ContentSlider when you meant to call .sudoSlider, (or whatever is appropriate for that framework).

Firefox Extension: Access the DOM Before It's Loaded

I'm trying to create a Firefox extension that fires my Javascript code before any of the current page's Javascript is fired. My Javascript code will basically control whether or not the page's Javascript code can be executed or denied.
I first started out by trying to follow this answer, but I couldn't really figure out how to get it to work and realized I was relying on onDOMContentLoaded, which loads after the Javascript has already executed.
I then turned my attention toward XPCOM, but once again didn't really understand what the Firefox tutorials were telling me.
I've recently been trying to make an extension through Firebug, but I seem to hit the same problem... only having access to the Javascript after it's been parsed/executed. Here's the resulting code that I wrote. I think if I could access the file's objects in the onExamineResponse event, my problem could be solved, but I don't know how to do that... I'm talking about this code:
BeepbopListener.prototype = {
onRequest: function(context, file) {
...
},
onExamineResponse: function(context, file) {
FBTrace.sysout("onexamineresponse " + file); // this returns something like
// '[xpconnect wrapped (nsISupports, nsIHttpChannel, nsIRequest, nsIUploadChannel, nsITraceableChannel, nsIHttpChannelInternal)]'
// but I don't know how to access those elements...
var pattern = /\.js$/;
if (pattern.test(file.href) && FBTrace.DBG_BEEPBOP) {
FBTrace.sysout("ONEXAMINE DOESN'T EVEN GET IN THIS IF SO YOU WON'T SEE THIS");
}
},
...
};
So my question is... is there a tutorial out there that shows me how I can get access to all Javascript code on a page before it's executed? Also, if anyone has any helpful insight, I'd love to hear it. Oh, and if y'all need more code from me, just let me know, and I'll post it.
You can access a new document before any JavaScript code runs by listening to the content-document-global-created observer notification. However, the document will be empty at this point and JavaScript code will run as soon as the parser adds a <script> tag - you cannot really prevent it. Here are the options to control script execution that I am aware of.
1) Disable all JavaScript for a window using nsIDocShell.allowJavascript:
wnd.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShell)
.allowJavascript = false;
This is an all or nothing approach. Note that JavaScript stays disabled even when a new document loads into the same frame.
2) Implement the nsIContentPolicy interface in an XPCOM component and register it in the content-policy category (via nsICategoryManager). Your shouldLoad() function will be able to block scripts selectively - but it will only called for external scripts (meaning <script src="...">), not for inline scripts on the page.
3) Use JavaScript debugger service to intercept script execution. You could use jsdIDebuggerService.interruptHook to step through JavaScript execution and abort the script whenever you like. But that would slow down JavaScript execution very significantly of course. At the very least you should use jsdIDebuggerService.addFilter() to restrict it to a particular document, otherwise you will slow down the entire browser (including browser UI).
I'm trying to create a Firefox extension that fires my Javascript code before any of the current page's Javascript is fired. My Javascript code will basically control whether or not the page's Javascript code can be executed or denied.
Start by completely preventing the document from getting parsed altogether then on the side, fetch the same document, do any processing on this document and then inject the resulting document in the page. Here is how I currently do just that https://stackoverflow.com/a/36097573/6085033

Calling a flash external interface AS3 function on page load

I have a function defined in AS3 that's gonna be called from client side via JavaScript. The AS3 functions simply print some value on SWF screen when it's called.
It works fine when I set an onclick event handler to a button and call the AS3 function. However I want to call this AS3 function as soon as the page loads. I am using jQuery in the project and I placed the call to the AS3 function inside $(document).ready(), but that gives me the following error in FF2 firebug:
getFlashMovie("my_movie_name").my_as3_function is not a function
Then, I tried calling the by setting an onLoad event handler on the , but that also does not work - produces the same error.
So, my question is, how do I call an AS3 function automatically once page loads? In my project, I need to pass some client side initialization information to the flash once page loads.
You'll need to have your flash call a function in the page to notify it that the Flash is loaded and initialized, then use that as your entrypoint.
In the flash:
ExternalInterface.call('flashReady');
In the page:
<script>
function flashReady() {
..
}
</script>
If you use swfObject to embed your SWF (probably a good idea anyway) then you can use its addDomLoadEvent() function which allows you to do something once the SWF is fully loaded
swfobject.addDomLoadEvent(function() {
$("#swfobject").get(0).inited('you are loaded!');
});
i am not trying to be a wiseguy here but do you test your work on a server?
external interface, addcallback dose not work on local filesystem, and eventually you may have to add:
flash.system.Security.allowDomain('http://localhost');
if you are running on local.
:P
The problem is that the Flash object is not initialized yet when the page finishes loading. It would probably be much safer to perform this initialization from within AS3. If you want to pass values from the HTML page, use flashVars.
I ran into this problem myself a couple of weeks ago. The solution is pretty simple :)
First, you need to put in your DOM a div
<div id="timewriter"><div>
You'll also be using the jQuery Timers plugin to time your loading. After this preparation the things will go very easy.
The following piece of code will go in your $(document).ready();
var movie = getFlashMovie('my_movie_name');
if(movie.PercentLoaded() != 100)
{
$("#timewriter").everyTime(100, function ()
{
if(movie.PercentLoaded() == 100)
{
$("#timewriter").stopTime();
//the movie is loaded, call here your functions; usually this happens if you don't use cache
}
});
}
else
{
//the movie is loaded, call here your functions; usually you get here if you use cache
}
Later edit: be careful that HTML page load doesn't mean the swf was loaded, that happens right after the web page load complete event. Also my solution is based on jQuery javascript library.
Answers by both tweakt and Bogdan are viable. Use tweakt's method if you have access to the Actionscript. Use Bogdan's if you don't. I was looking for an alternative besides polling (when you don't have access to the Actionscript) but I have been unsuccessful in finding one thus far. Events are mentioned here: http://www.adobe.com/support/flash/publishexport/scriptingwithflash/scriptingwithflash_03.html But noone seems to know how to use them.
For the sake of completion, you would also have to use import flash.external.*; to make everything work.
It seems like the collection of answers offered answers this closest to it's entirety.
As David Hanak said, the flash object cannot be accessed yet because it is initializing, though i disagree that we must rely on flashvars, though I love them.
Tweakt is right, but upon calling the function in the javascript, have that call the javascript function that calls back to your swf; This way we know flash is ready as it sent the first call.

Categories