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

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

相关推荐
无心水3 分钟前
22、Java开发避坑指南:日期时间、Spring核心与接口设计的最佳实践
java·开发语言·后端·python·spring·java.time·java时间处理
188号安全攻城狮3 分钟前
【前端安全】Trusted Types 全维度技术指南:CSP 原生 DOM XSS 防御终极方案
前端·安全·网络安全·xss
Hello.Reader7 分钟前
双卡 A100 + Ollama 最终落地手册一键部署脚本、配置文件、预热脚本与 Python 客户端完整打包
开发语言·网络·python
cch891816 分钟前
汇编VS C++:底层控制与高效开发之争
java·开发语言
墨渊君26 分钟前
从 0 到 1:用 Node 打通 OpenClaw WebSocket 通信全流程
前端·openai·agent
lifewange26 分钟前
代码托管平台
开发语言
yangyanping2010827 分钟前
Go语言学习之配置管理库Viper
开发语言·学习·golang
橘子编程29 分钟前
UniApp跨端开发终极指南
开发语言·vue.js·uni-app
冬至喵喵35 分钟前
构建 CLI 的 Python 框架:Typer技术介绍
开发语言·chrome·python
Novlan137 分钟前
一个油猴脚本,解决掘金编辑器「转存失败」的烦恼
前端