gpt4 book ai didi

google-chrome-extension - 从弹出窗口到 content.js 的 sendMessage 在 chrome 扩展中不起作用

转载 作者:行者123 更新时间:2023-12-04 09:30:45 24 4
gpt4 key购买 nike

我正在尝试为 chrome 扩展制作一个弹出界面。我似乎无法从 popup.html/popup.js 向 content.js 脚本发送消息。这是我到目前为止所拥有的。当我点击扩展图标时,我会看到一个按钮,上面写着 clickme。我点击它,什么也没发生,chrome javascript 控制台中没有错误,也没有向 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"
]
}

弹出窗口.html
<html>
<head></head>
<script src="popup.js"></script>
<body>
<input id="button1" type=button value=clickme>
</body></html>

弹出窗口.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)
}

内容.js
   chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "start" ) {
start();
}
}
);

function start(){
alert("started");
}

最佳答案

我修改了你的 popup.js并使用 DOMContentLoaded正如 Chrome 扩展程序所建议的那样:

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>

我已经测试过它的工作原理。

关于google-chrome-extension - 从弹出窗口到 content.js 的 sendMessage 在 chrome 扩展中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29926598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com