Tuesday, 2 September 2008

Forcing reloading of URL Protocols (getting round Same Origin policy)

Let's say you have a link that looks like this <a href="myurlscheme:login/AppUserId/820">myurlscheme:login/AppUserId/820</a>

This link will only operate when clicked on by a user (that is it's semantics, it's a "a href", a hypertext link to another document).

But, let's say I don't want to do that. Instead I want to trigger the application bound to that protocol automagically. So, the first step (the only thing I can try) is the use XMLHttpRequest. This handy JS function allows me to "get" or "post" data from a server. The problem here is that for the sake of security this can only operate from the domain from which the page containing the JS was loaded e.g. http://www.myurlscheme.com can run JS to get requests from myurlscheme.com but not google.com or https://www.myurlscheme.com (protocol is significant in these tests). This page (mozilla) provides an excellent and clear overview of the "Same Origin" policy.

So, what's the solution?

In my HTML page (actually music.aspx which is HTML with embedded ASP code - basically PHP ;-) I create an "iframe" tag and make it invisible...

<iframe id="protocolHandler" src="" style="display:none"></iframe>

Now, when I want to programatically invoke the "myurlscheme" protocol I can use the following

document.getElementById("protocolHandler").src = "myurlscheme:login/AppUserId/820";

And... almost unbelievably, setting the iframe src property forces a reload of that frame (which is invisible anyway). Now, a URL Protocol does not return any data to the browser (on any platform I've tested) despite people insisting on the opposite I can find no way to get data back from a URL Protocol. However, this hack works for what I need so... err.. peachy.



No comments: