views:

286

answers:

1

I'm trying to access and edit the contents of an iframe. The iframe points to a page on a subdomain on my own domain. This is the javascript code I'm using, although it doesn't really matter.

$('iframe').load(function(){
  $('div.code textarea.html').val($(this).contents()[0].html());
});

When I run it it says I don't have permission to access example.domain.com from www.domain.com. So does it matter if the domain I try to access from has the www? Because my host does not allow me to not use www.

+1  A: 

Same-Origin-Policy requires the exact same hostname by default.

To tell it not to, set:

document.domain= 'domain.com';

from script in both the parent (www.) document and the iframe (example.) document.

Note that setting an onload of a statically-written iframe (or image) from script is unreliable, as it is conceivable that the iframe might get completely loaded in between the time the parser reads the iframe tag and when it reads the script tag that sets the onload.

To avoid this, either include the event handler as an inline ‘<iframe onload="doSomething()"’ attribute (one of the few places where inline event handling has some purpose), or, if acceptable for accessibility, create the iframe element itself from script, setting the onload before writing the src and adding it to the page.

bobince
Does doing this make it possible for the subdomain to access the domain's cookies?
this is a dead end
Through reading ‘window.parent.document.cookie’, yes. Sending and receiving of cookies wrt the ‘domain’ cookie parameter is unaffected by document.domain, however.
bobince