1

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

下面是一个便于理解的例子:

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

 document.body.style.backgroundColor = "#AAAAAA";

 document.getElementById('targetFrame').contentWindow.targetFunction();
4

1 回答 1

3

如果是别人的页面。如果没有对方的一些合作,你根本无法做到这一点。想一想,如果像您这样的随机人员可以针对其他开发人员编写的应用程序任意运行代码,这将对 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 的加载事件或让您的同事反向使用 postMessage 来通知您触发你的活动。.

有关更多信息,请查看关于 Web 消息的 HTML5 规范

于 2012-05-20T07:07:04.350 回答