从弹出窗口到content.js的sendMessage在chrome扩展中不起作用 [英] sendMessage from popup to content.js not working in chrome extension
问题描述
我正在尝试为Chrome扩展程序创建一个弹出界面.我似乎无法将消息从popup.html/popup.js发送到content.js脚本.到目前为止,这就是我所拥有的.当我点击扩展程序图标时,我得到一个名为clickme的按钮.我单击它,没有任何反应,chrome javascript控制台中没有错误,也没有消息发送到content.js.
I'm trying to make a popup interface for a chrome extension. I can't seem to send a message from the popup.html/popup.js to the content.js script. Here's what I have so far. When I click on the extension icon I get a button that says clickme. I click it and nothing happens, no errors in the chrome javascript console, and no message to content.js.
清单
{
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
"manifest_version": 2,
"name": "extensiontest",
"version": "0.2",
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
],
"browser_action": {
"default_icon": "Beaker.png",
"default_popup":"popup.html"
},
"background": {
"scripts": ["background.js"]
},
"permissions": [
"tabs"
]
}
popup.html
popup.html
<html>
<head></head>
<script src="popup.js"></script>
<body>
<input id="button1" type=button value=clickme>
</body></html>
popup.js
function popup(){
alert(1);
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {"message": "start"});
});
button1=document.getElementById("button1");
button1.addEventListener('click', popup)
}
content.js
content.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "start" ) {
start();
}
}
);
function start(){
alert("started");
}
推荐答案
我修改了您的popup.js
并将DOMContentLoaded
用作Chrome扩展程序,例如:
I modified your popup.js
and used DOMContentLoaded
as Chrome extension suggested like:
popup.js:
function popup() {
chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {"message": "start"});
});
}
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("button1").addEventListener("click", popup);
});
content.js:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "start" ) {
start();
}
}
);
function start(){
alert("started");
}
popup.html:
<!DOCTYPE html>
<html>
<head></head>
<script src="popup.js"></script>
<body>
<input id="button1" type=button value=clickme>
</body></html>
我已经测试了它的工作原理.
I've tested on my end it works.
这篇关于从弹出窗口到content.js的sendMessage在chrome扩展中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!