加载 iframe 后在 iframe 中执行 JavaScript 代码

Execute JavaScript code in an iframe after the iframe is loaded?

本文关键字:iframe JavaScript 代码 执行 后在 加载      更新时间:2023-09-26

我希望能够在别人的页面中执行代码。

下面是一个易于理解的示例:

假设我想在加载某些 iframe 页面后更改它的颜色:

 document.body.style.backgroundColor = "#AAAAAA";
 document.getElementById('targetFrame').contentWindow.targetFunction();

如果是别人的页面。如果没有对方的合作,你根本无法做到这一点。想想如果像你这样的随机人可以任意运行代码来对抗其他开发人员编写的应用程序,这会对 Web 安全产生什么影响?虽然我确信你品行良好,但有足够多的人道德低下,这对数据安全来说将是一个巨大的问题。

话虽如此,此安全规则也有例外;但是。

例如,如果其他 Web 开发人员授予您在其页面上执行代码的权限,则可以使用 HTML5 window.postMessage API 将消息从一个上下文传递到另一个上下文,然后在收到该消息时运行命令。

澄清一下,这要求其他开发人员在他/她的网站中注册一个侦听器,以收听从您的网站发送的事件。

同事网站上的代码:

// register to listen for postMessage events
window.addEventListener("message", changeBackground, false);  
// this is the callback handler to process the event
function changeBackground(event)  
{  
  // you're colleage is responsible for making sure only YOU can
   // make calls to his/her site!
  if (event.origin !== "http://example.org:8080")  
    return;  
  // event.data could contain "#AAAAAA" for instance
  document.body.style.backgroundColor = event.data;
  // do other stuff
  }
}  

您的代码:

// pass the string "#AAAAAA" to the iframe page, where the changeBackground
 // function will change the color
document.getElementById("theIframe").contentWindow.postMessage("#AAAAAA", targetOrigin);

为了在 iframe 完成加载时执行此代码,您当然需要能够检测到这一点,这可以使用 iframe 的 load 事件或通过让您的同事反向使用 postMessage 来完成,以通知您触发事件。

有关更多信息,请查看 HTML5 Web 消息传递规范。