我希望能够在其他人的页面中执行代码。
为了便于理解,这里举个例子:
假设我想在加载后更改某些 iframe 页面的颜色:
document.body.style.backgroundColor = "#AAAAAA";
document.getElementById('targetFrame').contentWindow.targetFunction();
最佳答案
如果是别人的页面。没有对方的一些合作,你根本无法做到这一点。想一想如果像您这样的随机人员可以针对其他开发人员编写的应用程序任意运行代码,这会对 Web 安全产生什么影响?虽然我确定您的品格良好,但有足够多的人道德败坏,认为这会成为数据安全的一个大问题。
话虽如此,此安全规则也有异常(exception);然而。
例如,如果其他 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's load event 来完成。或者让你的同事 use postMessage in reverse, to notify you to fire your event. .
有关更多信息,请查看 HTML5 Specification on Web Messaging .
关于javascript - 加载 iframe 后在 iframe 中执行 JavaScript 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10671436/