我在弹出页面和内容页面之间创建了长寿命连接。它很成功。但是,当用户单击按钮时,我希望将消息发送给内容。
contentscript.js
console.log("content script loaded!");
var port = chrome.runtime.connect({name: "content-script"});
port.onMessage.addListener(function(message){
if(message.key=="color"){
document.body.style.backgroundColor='lightgrey';
}
else if(message.key=="color2"){
document.body.style.backgroundColor='blue';
}
});popup.js
document.addEventListener('DOMContentLoaded', function() {
var checkPageButton = document.getElementById('btnStart');
checkPageButton.addEventListener('click', function() {
GetImages("");
}, false);
}, false);
function GetImages(pageURL){
if(activePort!=null){
activePort.postMessage({key:"color2"});
}
}
var activePort=null;
chrome.runtime.onConnect.addListener(function (port) {
console.assert(port.name == "content-script");
activePort=port;
port.onMessage.addListener(function(message) {
if(message.key=="download"){
port.postMessage({key:"download", text: "OK"});
}
else if(message.key="load"){
port.postMessage({key:"color"});
console.log(message.text);
}
})
});在GetImages()函数中,我试图
port.postMessage({key:"color2"});当然它找不到“港口”。因此,我创建了activePort变量,并尝试用它发布消息。但没能正常工作。
发布于 2020-09-13 19:45:57
我更改了下面的代码,它工作正常。现在,我在popup.js中打开了端口,我可以通过单击按钮发送消息。
newpopup.js
function GetImages(pageURL){
port.postMessage({text:"ok"});
}
var port;
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
port = chrome.tabs.connect(tabs[0].id,{name: "knockknock"});
});newcontentscript.js
chrome.runtime.onConnect.addListener(function(port) {
console.assert(port.name == "knockknock");
port.onMessage.addListener(function(msg) {
console.log(msg);
});
});https://stackoverflow.com/questions/63870838
复制相似问题