简体   繁体   中英

accessing variable in parent page from iframe

I have a page with an iframe that contains a html page. I want to access a Javascript variable in the parent page from within the iframe. The name of the variable in the main page is observer .

I have tried this

parent.observer = 'aadasds';

but I am getting the following error:

Permission denied for to get property Window.observer from

.

Exchanging values between iframes (and parent) is only allowed if both sites come from the same domain. If they do, your example should just work. If they don't, browsers inhibit the communication.

However there are a number of hacks to circumvent this: eg the Yahoo.CrossFrame library described in Julien le Comte's blog using a third iframe to enable one way communication, or the "resize an iframe around the iframe"-idea described in Adam Fortuna's blog enabling two way communication.

Edit (as people still seem to read this old answer):
In modern Browsers you can use postMessage to exchange Data between iframes. There are many javascript libraries that try to emulate that functionality in older browsers, too. Eg by mis-using the location.hash, like the jquery-postmessage-plugin does.

It sounds as though your iframes are using different domains. All major browsers block access to parent iframes if they are not using the same domain. IE if you have the domain www.test.com and you embedded a page from www.google.com and try to access/modify anything from google's website, you will be denied access.

The other answer to this question explains the implemented API post message . This can also be used to send/receive data from different frames from different domains. However, the things you can do with that are limited compared to if you had two frames using the same domain.

That being said, here is the answer if your iframes are using the same domain.

window.parent.observer;

Hope this helps someone :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM