简体   繁体   中英

Can javascript access iframe elements from the parent page?

我在页面上有iframe,iframe和父页面在不同的域中,父页面上的javascript代码可以访问这个iframe中的元素吗?

It should not be able to if the pages are from different domains, the browsers security sandbox should prevent this type of access. It might work when the two pages are from different sub domains of the same domain, but that can and will differ between browsers (and possibly even versions of the same browser).

Accessing the child iframe might work, but the other way around will most certainly not work.

最简单的方法是通过窗口上的框架对象,如下所示:

window.frames[0].document.getElementById('ElementId').style.backgroundColor="#000";

You can use CORS to achieve this, specifically changing the 'document.domain' value to match in both parent & child. But, please undestand the security implications of this, and that you require access to the source code of both parent & child documents.

This is especially important if you own multiple sub domains. I use this technique all the time, so I know it works, even with SSL.

如果两个域完全分开则不可能

可以使用--disable-web-security参数来完成Chrome ...;)

Use jQuery.postMessage plugin http://benalman.com/code/projects/jquery-postmessage/docs/files/jquery-ba-postmessage-js.html

Browsers Tested Internet Explorer 6-8, Firefox 3, Safari 3-4, Chrome, Opera 9.

是的,通过document.frames数组,您可以访问iframe。

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