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

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

相关推荐
@zulnger37 分钟前
读写Excel
开发语言·python·excel
带土11 小时前
9. C++ 套接字(Socket)
开发语言·c++
wearegogog1238 小时前
基于 MATLAB 的卡尔曼滤波器实现,用于消除噪声并估算信号
前端·算法·matlab
molaifeng8 小时前
Go 语言如何实现高性能网络 I/O:Netpoller 模型揭秘
开发语言·网络·golang
Drawing stars8 小时前
JAVA后端 前端 大模型应用 学习路线
java·前端·学习
崇山峻岭之间8 小时前
Matlab学习记录33
开发语言·学习·matlab
品克缤8 小时前
Element UI MessageBox 增加第三个按钮(DOM Hack 方案)
前端·javascript·vue.js
Evand J8 小时前
【2026课题推荐】DOA定位——MUSIC算法进行多传感器协同目标定位。附MATLAB例程运行结果
开发语言·算法·matlab
小二·8 小时前
Python Web 开发进阶实战:性能压测与调优 —— Locust + Prometheus + Grafana 构建高并发可观测系统
前端·python·prometheus
小沐°8 小时前
vue-设置不同环境的打包和运行
前端·javascript·vue.js