Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I access contents of an iframe from a subdomain if I use www. on the main domain?

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.

like image 377
fent Avatar asked Sep 01 '09 21:09

fent


1 Answers

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.

like image 70
bobince Avatar answered Oct 01 '22 08:10

bobince