views:

116

answers:

2

I am trying to access the DOM of an iframe that loads an external URL. Of course that I get a "Permission denied for" error due to cross domain security. How can I make this work? I saw something done with json (but I can not get a json string from my external source) and something done with HTML5 postmessage.

you can see it live at : http://jsfiddle.net/QPBvJ/

The code is:

    $(document).ready(function(){
     $('#get').live('click', function() {

        var currentIFrame = $('#frameDemo');
        currentIFrame.contents().find("a").css("background-color","#BADA55");

        alert ("done")
    });
    });

<iframe src="http://api.jquery.com/" width="80%" height="600" id='frameDemo'></iframe>
<button id="get">Get</button>

What would the the easiest way to make this work. Thank you

A: 

That is because of what is known as Same origin policy. Have a look at JSONP actually.

JSONP or "JSON with padding" is a complement to the base JSON data format, a usage pattern that allows a page to request and more meaningfully use JSON from a server other than the primary server. JSONP is an alternative to a more recent method called Cross-Origin Resource Sharing.

Under the same origin policy, a web page served from server1.example.com cannot normally connect to or communicate with a server other than server1.example.com. An exception is HTML tags. Taking advantage of the open policy for tags, some pages use them to retrieve JSON from other origins.

Sarfraz
question was not `why` that is the case, but how to do it anyways.
jAndy
Yes, I was aware of the Same Origin Policy. There are some HTML5 workarounds I am trying to find.
Mircea
+2  A: 

There is no way to make this work. Unless, the foreign domain you try to access supports a procedure like C.O.R.S, JSONP or postMessage.

There are a few exceptions (like always):

If you're dealing with a WebApp for instance, you can tell your users that they have to grant access to cross-domain-calls.

In Gecko/Firefox for instance, you can call

netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead')

which enables the browser to access foreign domains via ajax/iframes. In this scenario, an user has to set

signed.applets.codebase_principal_support

to true under about:config to make this work.

In the Internet Explorers of this world, there is a setting called something like allow cross-domain access deeply hidden in the security tab, which must be set to enable.

Chrome allows cross-domain calls with a commandline argument:

chrome.exe --disable-web-security
jAndy
Ok, thanx for the info. I am working on this, it should work.
Mircea