javascript - Chrome 扩展 : Interacting with iframe embedded within popup

标签 javascript google-chrome iframe google-chrome-extension

我正在编写一个 Chrome 扩展程序,它需要与用户没有打开的 url 进行交互。因此,我正在使用嵌入在弹出窗口中的隐藏 iframe,并试图单击 iframe 中的按钮。但是,我收到同源策略错误。我知道当 iframe 在用户打开的选项卡上时,扩展可以通过内容脚本与不同域的 iframe 交互,但我不确定是否可以使用内容脚本与 iframe 交互直接在弹出窗口中。

这是我的代码:

list .json

"content_scripts": [


{
    "js": [ "bin/jquery.min.js", "interaction.js" ],
    "all_frames": true,
    "run_at": "document_start",
    "matches": [ "http://*/*",
                 "https://*/*" ]
  }],

  "permissions": [
    "activeTab",
    "tabs",
    "http://*/",
    "https://*/"
],

interaction.js

$(document).ready(function() {
  $('div#iframes').append("<iframe id='shop' src='https://www.google.com/'></iframe>")
  $('iframe').bind("load", function() {
    $('iframe').contents().find("html").ready(function() {
      loadedStores += 1;
      if (loadedStores == carts.totalStores) {
        $('div#cost').append(carts.grandTotal)
        showMain();
      }
    })
  })
})

错误

Uncaught SecurityError: Blocked a frame with origin "chrome-extension://mapgjiofchdchalgcifmdolgcekfaadp" from accessing a frame with    origin "https://www.google.com/".  The frame requesting access has a protocol of "chrome-extension", the frame being accessed has a protocol of "http". Protocols must match.

错误出现在interaction.js的第三行(有load回调)。有谁知道我应该对内容脚本进行任何更改以允许我与 iframe 进行交互?或者我是否应该采取其他方法?谢谢!

最佳答案

您的框架还将注入(inject)一个内容脚本。

您需要使用 Messaging 与该内容脚本进行通信,并使其执行您需要的操作。

这里有一些进一步的信息:

关于javascript - Chrome 扩展 : Interacting with iframe embedded within popup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31177436/

相关文章:

javascript - 为什么 Angular 的标题过滤器对我不起作用?

javascript - 在jquery中单击iframe文档时如何获取包含iframe id

jquery - 在 facebook iframe 应用程序中使用 jquery - GET 与 POST

javascript - 如何将对象作为数据类型传递给sequelize中的数据模型?

javascript - Datalist - 限制只显示 x 数量的选项

google-chrome - 检测到网络速度慢。加载时将使用后备字体

javascript - 在多框架页面上只加载一次 jQuery

javascript - 计时器触发Azure Function开始但未结束?

javascript - 验证复选框限制javascript

node.js - 使用 puppeteer 在 headless chrome 中运行 Flash 游戏