首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >带有用户操作的Chrome扩展postMessage

带有用户操作的Chrome扩展postMessage
EN

Stack Overflow用户
提问于 2020-09-13 12:36:13
回答 1查看 131关注 0票数 0

我在弹出页面和内容页面之间创建了长寿命连接。它很成功。但是,当用户单击按钮时,我希望将消息发送给内容。

contentscript.js

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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()函数中,我试图

代码语言:javascript
运行
复制
port.postMessage({key:"color2"});

当然它找不到“港口”。因此,我创建了activePort变量,并尝试用它发布消息。但没能正常工作。

EN

回答 1

Stack Overflow用户

发布于 2020-09-13 19:45:57

我更改了下面的代码,它工作正常。现在,我在popup.js中打开了端口,我可以通过单击按钮发送消息。

newpopup.js

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
chrome.runtime.onConnect.addListener(function(port) {
    console.assert(port.name == "knockknock");
    port.onMessage.addListener(function(msg) {
      console.log(msg);
    });
  });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63870838

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档