谷歌浏览器插件开发-popup如何向contentscript交互「发送消息」

popup发起通信

chrome.tabs.query( //获得tab(标签页)
{ active: true, lastFocusedWindow: true }, //这个配置是获取当前的标签页,但是需要注意的是返回的依然是数组(一个元素)
function (tabs) {
    that.contentscript_post = chrome.tabs.connect(//建立通道
	tabs[0].id,
	{ name: "xxx" }//通道名称
    );
});

要发送消息使用

//参数是发送的数据,我设为一个json对象
this.contentscript_post.postMessage({
	type: "run_distinguish",  //消息名称
        data: {
		run: n
	}
});

contentscript接收消息

chrome.runtime.onConnect.addListener(function (port) {
    console.assert(port.name == "facevideo"); //通道名称
    port.onMessage.addListener(function (msg) { //msg就是上面的postMessage的参数(发送的数据)
        let type = msg.type;
        let data = msg.data;

        if (type == "run_distinguish") {
            //do someting
        }
        console.log("监听到消息", msg);
    });
});


--文章来源本人个人站点,同为原创作者,转载需注明此出处:谷歌浏览器插件开发-popup如何向contentscript交互[发送消息] | 瑷程序

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章