Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make cross-domain communication between JavaScript and Flash?

How do I open 'cross-domain security', so the JavaScript on the page can freely communicate with the SWF, even when this is hosted on another domain?

I know for certain that this function communication is blocked by default, but by playing around with a file called "crossdomain.xml" and the actionscript 3 function: system.Security.allowDomain("*"). I'm not having full success though, and I don't have the insight to know which one is opening up for what.

Is there other hidden security layers, that I need to think of in this scenario?

And am I opening up my code for potential hackers somehow by doing this setup?

(and in case you're wondering: Yes, I have to make this work in a scenario, where the html is hosted on one domain, the JavaScript is added externally from another domain and the SWF is embedded by the JavaScript from a third domain - don't ask why, it's too complicated to explain - I too wish I could just host the whole thing in one domain).

like image 556
Christian Hollbaum Avatar asked Jan 16 '09 23:01

Christian Hollbaum


2 Answers

Using Security.allowDomain("www.example.com") in the SWF will allow JS in a page from www.example.com to call functions exposed in the SWF with ExternalInterface.addCallback(). The domain and subdomain must match exactly. Using "*" will allow any domain to communicate with the SWF, but if you have one specific domain, it's better to use that.

Setting allowScriptAccess to always in the HTML embed code will allow the SWF to to call JavaScript functions.

One thing that catches many developers is that JavaScript will not be able to call functions on the SWF until the SWF is done loading. Unfortunately, there is no JS-based event that tells you when the SWF is ready (at least that I've found). What I usually do to work around this problem is call a JS function from the SWF immediately when the SWF finishes loading to notify the page that the SWF is ready.

There's some abstraction here and there, but if you take a look at the source code for YUI Charts, you might be able to figure out how Yahoo! got crossdomain JS/SWF communication working.

like image 142
Josh Tynjala Avatar answered Nov 15 '22 20:11

Josh Tynjala


One thing I'd add to the previous answer: If you try the above code and it doesn't work, check to see if your site's address includes the "www" or not. Mine did not and didn't work if I wrote it as

Security.allowDomain("www.jeremy-knight.com");

I needed to write it as:

Security.allowDomain("jeremy-knight.com");
like image 27
Jeremy Knight Avatar answered Nov 15 '22 19:11

Jeremy Knight