我正在编写一个 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/