简体   繁体   English

如何在iframe中调用javascript函数?

[英]How can I call a javascript function from within iframe?

I've had a read about and I'm aware of the fact the same-origin policy would prevent the DOM of an iframe accessing the parent window's DOM and vice versa if on different domains. 我已经读过一本书,并且我知道一个事实,即同源策略将阻止iframe的DOM访问父窗口的DOM,反之亦然(如果在不同的域上)。

However, I do, in this case, have at least some control of the parent DOM too (it is still on a different domain). 但是,在这种情况下,我也至少对父DOM有所控制(它仍在另一个域中)。 I'm developing a site to sit in the iframe but will also be asking users to add some javascript to the head of their page. 我正在开发一个位于iframe中的网站,但也会要求用户在页面顶部添加一些JavaScript。

Given that, is there anyway I can expose a javascript function in the parent with that included javascript? 鉴于此,无论如何,我可以使用包含的javascript在父对象中公开javascript函数吗?

I'm delighted to say, HTML5 appears to tackle this problem head on with window.postMessage : 我很高兴地说,HTML5似乎可以通过window.postMessage解决此问题:

https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage

According to the link Naeem posted in the comments, there may be some compatibility issues with certain browsers, but that can be overcome. 根据Naeem在评论中发布的链接,某些浏览器可能存在一些兼容性问题,但可以解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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