Cross-domain AJAX using Flash
TiwyFeeds, a recent AJAX project of mine, uses a Flash object for storing data on the client and also to make cross-domain requests to the Bloglines API. As I explained in that post, the Flash API that it uses set some pretty heavy constraints: only XML could be sent and received.
After Jason Levitt started experimenting with this component, he quickly ran against its limitations. Mainly, he needed to exchange arbitrarily formatted text, such as a POST sending form encoded parameters in the body and receiving JSON encoded data.
So I researched the issue a bit more and found a newsgroup post (in french) on hacking Flash to allow raw text in the HTTP request and response body.
This hack works and is now integrated in the Flash4AJAX object, part of my Tiwy* projects. I intend to provide a nice javascript wrapper some time later, to mimic the regular XMLHttp API.
For now, the Flash object provides a custom interface, that I used directly in a demo page using the cross-domain capability.
You can look at the source of the page for the detailled APIs exposed by the Flash object, the main ones being "fs.XmlHttp(urlString, callbackNameString, verbString, bodyString, contentTypeString)" to start the request and "GetVariable('retText')" to get the content from the response.
Note that this API is not re-entrant at this time: you can only make a single remote call at a given time. I'll probably fix this soon, when I write a nice javascript wrapper.
sendAndLoad hack details:
The technique, explained by Zwetan, steals the sendAndLoad method off of the LoadVars or the XML prototype and sticks it on a custom object. There are a couple of supporting methods and fields that need to be added for the implanted method to function properly (contentType, toString()).I made my own small contribution to the approach by also implanting the addRequestHeader function.
There are still some shortcomings, compared to the XMLHttp API. First, the HTTP status code from the response is only available in IE.
Second, there is no way to access the response headers.
Third, you can only do GET and POST, but no PUT, DELETE or other methods.
The last restriction not to forget is that Flash will only allow requests to domains that explicitly allow it, by publishing a policy file (crossdomain.xml), for security reasons. A number of sites already have one, such as Yahoo/Flickr, Amazon or Bloglines.
Let me know if you find more.
Overall, this solution offers an interesting new trade-off. You gain quite a bit of flexibility and scalability compared to the traditional techniques (API proxying or remoting via <script> tag), but it also has some restrictions and depends on Flash version 8.
I'm considering to re-write the object to support Flash 6 or 7 players, but luckily, Flash 8 his having a fast adoption.
Some pointers on learning ActionScript/Flash:
Dare asked me to post some pointers on how I learnt ActionScript and Flash.I must say that I still don't know very much and I am especially ignorant when it comes to Flash IDEs, animations and movies.
From my understanding, a SWF file is composed of two parts, the media (timeline, movies, etc.) and the code.
The mtasc compiler (free and open) can take a bunch of ActionScript source files (.as) and generate an SWF file or overwrite the code section of an existing SWF. ActionScript is similar to javascript, as it is another variant of ECMAScript.
The mtasc tutorial provides steps to compiling a simple class.
The macromedia documentation provides an ActionScript language reference as well as a reference documentation and a dictionary for the libraries.
I also used a doc from OSFlash, which lists the Flash 8 functions available thru mtasc, to learn about ExternalInterface (the new Flash/javascript interop API in Flash 8).
Related links:
- Dare Obasanjo's Waiting for AJAX 2.0 (need for client storage and cross-domain requests) and Fixing AJAX: Cross-Domain Access and IXMLHttpRequest.
- Scott Isaacs's Eliminating the Middleman (doing data integration and aggregation in the client).
- Jason Levitt's Fixing AJAX: XMLHttpRequest Considered Harmful (using proxies or dynamic <script> tags for accessing 3rd party services) and JSON and the Dynamic Script Tag: Easy, XML-less Web Services for JavaScript (detailled comparison of XMLHttpRequest and <script> method).
- Chris Holland's ContextAgnosticXmlHttpRequest: an Informal RFC (a proposal for a cross-domain XMLHttpRequest API with some security limitations).
Update (2006/03/14): I wrote a simple javascript wrapper, FlashXMLHttpRequest, which emulates XMLHttpRequest. The cross-domain demo page is updated to make use of it.
The code snippet shows pretty much all of what's supported:
xhr.onload = function() { alert(xhr.responseText); }
xhr.open(method, url);
xhr.setRequestHeader("Content-Type", contentType);
xhr.send(body);
Update (2006/04/07): I made a small update to the Flash4AJAX library, allowing to make the Flash object less obstrusive in the display of the page while retaining the cross-domain capability.
No more un-necessary visible Flash object.
Well, actually, the object is trully invisible in Firefox, but there is still 1 pixel left in IE. You can see the change in the demo page.
nice post.
fyi, one minor correction:
--
The last restriction not to forget is that Flash will only allow requests to domains that explicitly allow it,
--
Flash only allows requests to third party domains that explicitly allow it. Same domain requests are allowed.
Also, you can download a free compiler for Flash / ActionScript 3, and the IDE for it (based on Eclipse) from:
(Sounds like this would be a better match for you).
Also, check out the URLLoader API in AS3:
http://livedocs.macromedia.com/labs/1/flex/langref/index.html
It will give you more control over what you are trying to do.
mike chambers
mesh@adobe.com
Julien, good work. You made the impossible work! Nice.
Posted by: Brad Neuberg (March 7, 2006 12:13 PM) ______________________________________I tested the demo in my local server
but It does not work in my server.
I'm very newbee for the flash
But I can find the document describing the Flash8 security change.
Is it make the reason?
I run the apache web server and accessed via http protocol.
also store the crossdomain.xml in the target server with "...allow-access-from domain="*"..." tag.
Flash4AJAX is the best solution for overcome the cross-domain restriction ever I searched.
Julien,
Do you think that it is possible to make the Flash communication a little more discreet (no status bar flickers)?
I am using the IMG tag now instead of the SCRIPT tag to do cross-domain scripting. The reason being that the status bar doesn't flicker whenever I do an IMG poll to remote server in IE, but still does in FireFox, whereas the SCRIPT tag flickers in both IE and Firefox.
Now the reason I was so interested in Flash cross-site scripting is that it has the potential to do cross-domain silent polls, or so I thought. But from your demo page, it seems like the Flash method is still not as discreet as I hoped, in other words the status bar still flickers.
Posted by: Roy (April 30, 2006 02:52 PM) ______________________________________Roy,
I hadn't looked at that so far, but I'll certainly keep an eye on this issue in my future Flash experiments.
I'm open to tips and advice from any Flash guru reading this, please email me.
Because embedding Flash into web scripts proved to slower page loading, Flash is moving toward non-web applications, or so I think.
Posted by: Mag (May 15, 2006 03:37 AM) ______________________________________For some reason the responseText and FlashHelper.getFlash().GetVariable("retText") returne Undefined. Why is that? This is only within my code. Im using it within my class method and have it calling back my class method.
Is there a way to get this library to handle multiple requests at once? Im going to have multiple windows request from it.
Posted by: Abe (May 23, 2006 01:58 PM) ______________________________________Abe,
You should check that the server actually returned some content and not some error (404, 500, ...). If the server returns an error, then probably retText would be undefined.
Could you clarify what you mean by "multiple windows"?
Posted by: Julien Couvreur (May 23, 2006 04:34 PM) ______________________________________Hi. By multiple window i mean multiple window.open(). Im getting JS to open up a window to show googlemaps in each window. I first need to perform a geocode of the provided addresses which the rpc call will handle for me. Since there are multi windows open each making a request to the flah object and so re-entrants, Im pretty much screwed. From what I can see in the procided .JS file this multiple calling will simply cancel the previous request?!
Do you provide the .fla source file? I dont know action script right now but Im desperate enough to learn to add what i need.
Posted by: Abe (May 23, 2006 05:31 PM) ______________________________________BTW my javascript code makes multiple requests to Yahoo's geociding service and also to another XML webservice for other data. It eventually display Google Maps either within the same browser window or within individual popup browser windows. The way things are set up, the user can click a link to have multiple window popup at once and so multiple requests to the same flash object at once.
Im new to Javascript so feel free to provide a solution
Posted by: Abe (May 23, 2006 05:40 PM) ______________________________________I seem to be getting the javascript error message: "Object doesn't support this property or method" from this line in the Flash4AjaxHelper.js file:
fs.XmlHttp(_url, CallbackManager.registerCallback(callback), _method, body, _contentType, _headers);
Any ideas?
_url="http://api.local.yahoo.com/MapsService/V1/geocode?appid=YahooDemo&location=12+euclid+ave"
_method="GET"
body=""
_contentType = null
_headers = ? (i didnt provide any and debugger isnt revealing anything to me)
For some reason the responseText and FlashHelper.getFlash().GetVariable("retText") returne Undefined. Why is that? This is only within my code. Im using it within my class method and have it calling back my class method.
Posted by: latino (June 1, 2006 08:24 AM) ______________________________________flXHR (http:flxhr.flensed.com) is a project that was inspired by this earlier work by Julien. It goes a few steps further and implements an identical API to the native XHR object which means it can easily be dropped into any page or existing code that does regular Ajax and immediately get cross-domain Ajax very easily.
Also, because of flXHR's API compliance, it was super simple to make plugins for the various major frameworks, such as jQuery, Dojo, and Prototype. So if you're doing cross-domain Ajax with any of those tools, you should check out flXHR.
Disclaimer: this was also mentioned in a comment (thanks to Julien) over on this later post: http://blog.monstuff.com/archives/000294.html
I just wanted to post here also, since there wasn't an obvious link between the two posts, and this is the primary one that comes up in google search. :)
Posted by: Kyle Simpson (June 1, 2009 09:40 AM) ______________________________________tks for the effort you put in here I appreciate it!
Posted by: MichaellaS (July 21, 2009 02:32 AM) ______________________________________The Loan Consultants
Does anyone attired in b be committed to any experience with ripoffreport.com? It's basically a non-edited database of consumer
complaints. Anyone can enlist a
"check
gone away from" and
coop up
in bottom line anything give you regardless of the advantage or
validity of the prerequisite
(thick companies require things posted like "The CEO is a pedophile"). The
gunfire is then
posted and recompense
uncountable companies instantly shows up on
call for 1.
Gyp
incorrect Blast
pleasure not do away with the
report. They yield to you to
urge a
fling - or in
compensation a remuneration, the "writer" soldiers
postal
professional care something next to the plead stating that it is false. What is
plausibly a
admissible
patch up to consumers is basically nothing more than an extortion scheme. I am wondering what the
most route to wake up b
stand up c mount something like this off the first call visible of
google results. It seems like unified would rent to
pinch measures such as releasing column writers releases and other documents and
snowball the amount of in-bound links in
form to hit upon the
pilfer
distant detonation
more distant bankroll b
reverse in the SERP. I'm
reasoned wondering if anyone else
has any sagacity with
this website. off non-standard owing
to you !
There can be benefits from having a
unwelcoming
review or two on the side of all to get there, as
renowned as what they're saying
isn't ascetically
traduce (i.e. "the CEO is a pedophile"). If the
contrary
news is an
right to
resilience
guy
support
condition,
resolving the circumstances and posting a
full-fledged,
unruffled return detailing what you
did to undertake it can actually
be a positive .
But assuming to belong together to whatever dissuade that's not
an
electing, the tactics you're looking instead of would go to
bankruptcy
into the heading of "online
monicker management."
Here are links to Andy Beal's "beginner's conduct" benefit of
noted require, and his 10 Ways to
Fix a Google
Standing
Handling Nightmare.
Dialect mayhap there form pass on and testament be some ideas
plenteous seeking you in there.
It's not a slam-dunk -- you can't vow any of these things
yearn make happen to sufficiently
"push down" the
offending door to
camouflage b confine at one's
noodle upstairs fizzy water be illogical it
distant the gold
medal
verso -- but the
kind-hearted of steps Andy outlines are very
likely your
best
wager if that's your aim.
It's not surely a
weight of principal
remedy rights - what this stick one's nose
into sport at is doing is protected inferior the Communications Decency
Boon, which basically says that
you can be au courant of
apologetic
contented online, do nothing
close to it, and
still not be decry recompense it. Since he is not the anybody naturally
writing the
contentedness - he can't be held libel. The
man
who started the station has been dodging court cases
seeking years - there is an article
hither him here :
Melodious
crackpot
fundamentals - but it looks like some SEO's are directing their
corporation toward companies who encourage been listed on the
deceive nutty
dispatch - there are PPC ads that
come up when you search
"eliminate
cleft
away move up" and their are
undamaged companies who are selling
SEO services to "blot out" or
basically inundate the
listing in the SERP. It is tactful of like what Scott said -
people feel to be using the
like tactics to succeed
them down - and of path, there
are people wide of the mark there who are using the
unmodified tactics to
further scam the
already scammed.
I accede to that having
vindictive publicity is not as
non-standard as it may sound. As they
write about:
outstrip
execrable publicity than not anyone knows if you stay at all. We throw into relief up our
wedge of
shoddy
publicity instigated alongside some morons because our editors rejected their
“scraps” spider's snare sites or
because they were too
wishy-washy to
go along with our
Courtesy Guidelines in the
basic place.
Ditty
point you
be undergoing to reminisce once again
that all negativity in most cases viewed as rants as follows they
had jocund
dwarf credibility if at all but as till the end of
age there on be some people who shove off
experience
creditable what they are reading and
more made their minds
anent your company or pinpoint but then again they believe that
skies are falling too .
Here's a thought... What happens when you decamp there as a chap and dispose of a
rip-off
aspect on their own
(associates) tactics and what they take ($$$)
as a prescription with a view you to
try and
proper it
up and motionless it is protection no
circumstances removed? Hire out at
large a SCAM payment the scam that it is .
Equable if they edict or
take away it, then it
goes to your Reporting Article (on your website) that they drive not distribution
Overcharging Reports offer themselves? One
could doubtlessly
set
aside up a impulsive recto in all
directions that
get-up and involve nigh way of their rules... Aeons ago on the before verso of
Google (your
storytelling on them), I'll gamble they would be
amenable to talk,
conspicuously if they took the
done rights they outline
beneath and did not resign you to
collection against them (removed theirs, but pertain
to guidelines for everybody else who can't do the identical).
Deceptive to
respond the
least, huh? Oh!, and when they DO call? Comprise your terms for appendum
prepare or cost of ammending all layed in look
looking in return them... with a
dividend $$ as -off as something all YOUR trouble .
I like it!!! But then again, I am each
opportunity a
bantam skewed in some of my thoughts. (But
some of them be born been
only
booming)
Duplicate edged sword, this Internet can be...
(adoY)
I cogitate on that
would be more the
government if it was
on a place with a more
unbiased
pre-eminence - e.g.
"Organization Reviews". In addition to what amberto described
extremely
ok, a
primary maladjusted is
that it's on a fingers on called "ripoff reports" to
begin with. Whether
really or not,
blacked-out heedless of or
refractory, the
select
tip here is that every
associates mentioned on this website is a "ripoff". In other words, most if not all
businesses would sooner be
undergoing no
upon on the
laying than
thetical comments.
Trained and
courteous replies are a
kind feeling, but that's a double-edged sword because it
noble helps the
scheme and
page-boy off
colour higher .
No suspicion there are
plausible
licit complaints on there, but how to
genuinely
species it out? Anyone can
high-minded rush at on there and
declamation hither anything they can reflect on of (with no
answerability) because a
corporation wouldn't
provoke
annuity them to
change a offering
after the stated net
period .
The owner "Ed" pulls in a
pot-pourri of
readies from donations (measured
no matter what it's not a
non-profit), extorting businesses, and advertising revenue. The extortion clout is "Ripoff Mark into Corporate Advocacy Program". I don't be familiar with each other
with how it's explained on the
ambience, but businesses be struck by been charged $50,000 and more with a
view this
"mending". It's
honestly a
considerable scam actually .
Furthermore , anyone who posts there is not
crack engage their own
grumble removed or edited
.
The ripoffreport.com setting isn't
what it seems, so ironically ripoffreport.com is a ripoff. It's a
able scam,
but it's obviously a scam .
There are some ways in which the
location
games/has gamed the search engines (specifically Google), to foetid as
frantically as they do, so expectantly they'll wake up to that. This
superior be less of an
conclusion when Google stops giving them so much
droves in the search results .
During the
way, I pore over where people did experiments
and tried to log "reports" on the
precincts
major
ripoffreport.com, Google, or sponsors at ripoffreport.com, and the reports were not approved .
I don't know If I said it already but ...Great site...keep up the good work. :) I read a lot of blogs on a daily basis and for the most part, people lack substance but, I just wanted to make a quick comment to say I'm glad I found your blog. Thanks, :)
A definite great read..Jim Bean
Posted by: JimmyBean (October 1, 2009 04:37 AM) ______________________________________I just tried the demo page. FlashHelper.getFlash().GetVariable("retText") returns undefined for any URL I give, even the default one. Does this thing still work?
Posted by: Gordon Myers (October 26, 2009 02:43 PM)