【问题标题】:Execute JavaScript code in an iframe after the iframe is loaded?加载 iframe 后在 iframe 中执行 JavaScript 代码?
【发布时间】:2012-05-20 07:00:03
【问题描述】:

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

为了便于理解,这里举个例子:

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

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

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

【问题讨论】:

    标签: javascript iframe execute loaded


    【解决方案1】:

    如果是别人的页面。如果没有对方的一些合作,你根本无法做到这一点。想一想,如果像您这样的随机人员可以针对其他开发人员编写的应用程序任意运行代码,这将对 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's load event 或让您的同事 use postMessage in reverse, to notify you to fire your event. 来完成。

    欲了解更多信息,请查看HTML5 Specification on Web Messaging

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多