我尝试将消息从从我的扩展加载的 iframe 发送到我的扩展(背景脚本或内容脚本)。
创建的 Iframe 通过内容脚本从扩展加载。
我正在寻找一种交流方式,但我所有的尝试都失败了......
list .json
{
"author": "***********",
"background": {
"page": "back/background.html",
"persistent": true
},
"browser_action": {
"default_title": "***",
"default_popup": "./popup/popup.html"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["./content/allurls.js"],
"all_frames":true
},
{
"matches": ["<all_urls>"],
"js": ["./banner/confirm_banner.js"]
}
],
"web_accessible_resources": [
"frame.html"
],
"description": "oui",
"manifest_version": 2,
"name": "***",
"permissions": ["tabs"],
"version": "1.0"
}
Confirm_banner.js(加载 iframe)
var extensionOrigin = 'chrome-extension://' + chrome.runtime.id;
window.onload = load_iframe();
function load_iframe()
{
if (!location.ancestorOrigins.contains(extensionOrigin))
{
var iframe = document.createElement('iframe');
iframe.src = chrome.runtime.getURL('../frame.html');
iframe.style.cssText = 'position:fixed;top:0;left:0;display:block;' +
'width:100%;height:40px;';
document.body.appendChild(iframe);
}
}
Frame.js(与 frame.html 链接的脚本)
$(document).ready(function()
{
$('#jamais').click(function()
{
send_message("BANNER", "jamais");
alert("send");
});
});
function send_message(type, data)
{
var msg = {
type: type,
data: data
};
window.postMessage(msg, "*");
}
allurls.js 中的处理程序(内容脚本)
window.addEventListener('message', function(event) {
if (event.data.type && (event.data.type === 'BANNER'))
{
alert("ouimonsieur");
}
});
因此,来自 iframe.js 的消息发送良好(由警报证明),但内容脚本没有收到任何消息,甚至在:
if (event.data.type && (event.data.type === 'BANNER'))
有人可以看到有什么问题或我可以使用哪些其他消息传递协议(protocol)(我也尝试过使用 top.window.postmessage)?
最佳答案
Ty wOxxOm 的答案,我很接近:
只需替换 window
通过 parent
在 frame.js
一切都很完美。
因为即使内容脚本在 iframe 中运行,Frame.js
不是内容脚本,它是 iframe 脚本并在扩展的上下文中运行。
关于javascript - 创建的 iframe 和扩展、谷歌浏览器扩展之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46118425/