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({});

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

相关推荐
迷渡几秒前
聊一聊 Bun 用 Rust 重写这件事
开发语言·后端·rust
古怪今人9 分钟前
Gradle构建工具 Groovy/Kotlin DSL的现代化自动化构建工具
开发语言·kotlin·自动化
赏金术士10 分钟前
Kotlin 协程与挂起函数(Coroutines & suspend)入门到实战
android·开发语言·kotlin
贫民窟的勇敢爷们23 分钟前
React跨平台能力,打破前端开发的平台边界
前端·react.js·前端框架
y = xⁿ36 分钟前
Java并发八股学习日记
java·开发语言·学习
你很易烊千玺40 分钟前
JS 数组所有变态遍历・完整案例 + 场景 + 对比
javascript·数组
xifangge202542 分钟前
【深度排障】从 OS 底层寻址剖析 javac 不是内部或外部命令 核心报错:变量空间隔离与自动化部署终极范式
java·开发语言·jdk·自动化
肖恩想要年薪百万1 小时前
JSP中常用JSTL标签
java·开发语言·状态模式
lifejump1 小时前
Dede(织梦)CMS渗透测试(all)
前端·网络·安全·web安全
l1t1 小时前
在aarch64机器上安装clang来生成codonjit python模块
开发语言·python