Chrome 扩展 background 与content_script 之间通信

content_script 向 background 发消息要用:chrome.runtime.sendMessage

复制代码
        chrome.runtime.sendMessage({event: "xhr", data:option }, function (res) { 
            //option.onload(res);
            //console.log(res);
            if (res.event == "xhr" && !res.err){
                option.onload(res);
            }
        });

background 接收消息:chrome.runtime.onMessage.addListener

javascript 复制代码
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
 if (message.event == "copy") {
       //alert("copy detected");
       //return true;
 }

    sendResponse({});
    return true; 
});

background 向 content_script 发消息要用:chrome.tabs.sendMessage

javascript 复制代码
            chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
              if (tabs && tabs.length > 0) {
                const activeTab = tabs[0];
                console.log('当前活动标签页的是:', activeTab);
                try {
                    chrome.tabs.sendMessage(activeTab.id, {'evt':'mediaUrl','data':mediaUrl }, function (res) { 
                        console.log(res);
                    });
                } catch (error) {
                    console.error(error.message);
                }
              }
            });

content_script 接收消息用:chrome.runtime.onMessage.addListener

和background中是一样的,注意其中的 sendResponse({});

这一句很关键,接收到了就要给一个回应;

相关推荐
小小小小宇12 分钟前
React 的 DOM diff笔记
前端
糯米导航17 分钟前
Java毕业设计:办公自动化系统的设计与实现
java·开发语言·课程设计
小小小小宇18 分钟前
react和vue DOM diff 简单对比
前端
糯米导航20 分钟前
Java毕业设计:WML信息查询与后端信息发布系统开发
java·开发语言·课程设计
我在北京coding21 分钟前
6套bootstrap后台管理界面源码
前端·bootstrap·html
Carlos_sam24 分钟前
Opnelayers:封装Popup
前端·javascript
MessiGo1 小时前
Javascript 编程基础(5)面向对象 | 5.1、构造函数实例化对象
开发语言·javascript·原型模式
大霞上仙1 小时前
nonlocal 与global关键字
开发语言·python
galaxy_strive1 小时前
绘制饼图详细过程
开发语言·c++·qt