【问题标题】:Can i build a API that would let me interact with content inside a iframe?我可以构建一个 API 让我与 iframe 中的内容进行交互吗?
【发布时间】:2020-09-17 08:09:25
【问题描述】:

我正在做一个项目,我想在 iframe 中填充网页,但由于 CORS,我无法从我的应用程序中与 iframe 中的内容进行交互,但是人们会在我的应用程序中显示他们的网页可以在他们的网页上安装代码或其他东西,我尝试过 postMessage,但如果有人愿意,它似乎很容易被利用。

我想知道我是否可以开发某种 API,该 API 可以放置在用户网页上,并且只有在有人从我的应用程序访问它时才会被激活,并允许用户通过自定义事件与 iframe 内的网页进行交互?

我们使用 react js 作为前端。

这样的事情可能吗?如果是的话怎么办?谷歌分析跟踪代码是如何工作的,我相信它也使用 postMessage。

感谢您的帮助。如果你能帮助我,很高兴赞助一杯咖啡。

【问题讨论】:

    标签: reactjs iframe cross-origin-read-blocking iframe-app


    【解决方案1】:

    我有一个非常相似的问题,网页是我的,而 iframe 内容有一个脚本标签是我的。以下是您可以通过两种方式进行通信的方法:iframe 与父级以及父级与 iframe。

    此代码充当一种侦听器,用于侦听来自其他窗口的消息。如果您想要双向通信,您需要在两个页面上使用它,您的客户以及您自己的页面(嵌入页面和嵌入页面):

    window.onmessage = function(e) {
      // this get's triggered when other window sends a message 
      if (e.data == "<some_identifier>") {
        // with e.data you can send an identifier 
        // and then you put the code that should be executed in here (on your page)
      } else if (e.data == "<some_other_identifier>") {
        // other action to do
      }
    };
    

    然后您使用 postMessage 函数从嵌入式 iframe 网站发送这些消息,以便发布到父窗口(嵌入窗口)

    window.top.postMessage("<some_identifier>", "*");
    

    反之,你像这样嵌入页面,名称必须是唯一的

    <iframe src="<your-embedded-url>" name="<some-id>"/>
    

    然后你可以用这个发送一个帖子:

    let target = window.frames.<some-id>;
    target.postMessage("<some_identifier>", "*");
    

    postMessage 中的星号将决定消息是针对您定位的每个窗口还是仅针对特定窗口(例如,您可以发送仅用于您的网站的消息,然后其他嵌入站点将无法接收事件。More infos on restricting the target here

    如果您有任何问题,请询问:)

    【讨论】:

    • 感谢您的回答。我想为多个网页执行此操作?这样做有可能吗?想想我们的产品,比如带有多个网站的谷歌分析。你能帮助我的团队成员完成这项工作吗??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多