简体   繁体   English

访问和修改iframe内容,postMessage vs jQuery.contents()

[英]Accessing and modifying iframe contents, postMessage vs jQuery.contents()

It's possible with 有可能

$('#iframe_id').contents().find('.stuff_to_modify).addClass('whatever');

But it's also possible using window.postMessage events, by sending a do_something message to a script from the iframe, which does the modifications when the message is received (adds that class). 但是也可以使用window.postMessage事件,通过从iframe向脚本发送do_something消息,iframe在收到消息时进行修改(添加该类)。

I was wondering which is the way I should go, and what are the differences between these two methods (drawbacks, advantages). 我想知道我应该采用哪种方式,以及这两种方法之间的区别(缺点,优点)。

The jQuery method seems nicer because I don't need to include any script in my iframe anymore jQuery方法看起来更好,因为我不再需要在iframe中包含任何脚本了

The major difference between window.postMessage and jQuery sample you gave is that, postMessage enables cross-origin communication. window.postMessage和jQuery示例之间的主要区别在于,postMessage支持跨源通信。

Meaning, if a Parent page which hosts the iframe is from domain A, while the content of the iframe is from domain B, then postMessage allows you to communicate while the jQuery approach will result in the security error. 这意味着,如果托管iframe的父页面来自域A,而iframe的内容来自域B,则postMessage允许您进行通信,而jQuery方法将导致安全性错误。

The link you provided is a java script wrapper to window.postMessage implementation of the browser and falls back to window location hash polling for browsers that do not support it. 您提供的链接是浏览器的window.postMessage实现的java脚本包装器,并且回退到不支持它的浏览器的窗口位置哈希轮询。 Other benefits are listed in your link itself. 您的链接本身列出了其他好处。

So, if the two pages are from same origin, ie served from same domain, then you can go the jQuery approach itself. 因此,如果两个页面来自同一个源,即从同一个域提供,那么您可以使用jQuery方法本身。 If it is from two different origins, you may have to use the JS wrapper. 如果它来自两个不同的来源,您可能必须使用JS包装器。

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

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