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

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

相关推荐
anyup2 分钟前
uView Pro 正式支持 MCP 协议!让 AI 秒懂你的组件库
前端·uni-app·ai编程
触底反弹4 分钟前
🔥 50 行代码,我手写了一个 MCP Server 给 Claude 用!
javascript·人工智能·程序员
江华森5 分钟前
04-python-面向对象
开发语言·python
AI行业学习8 分钟前
Notepad++ 官方纯净下载+完整安装教程(Windows)【2026.7.5】
开发语言·windows·python·前端框架·html·notepad++
Coffeeee9 分钟前
从 Android 15 到 Android 17,谷歌猝不及防的音频改动
android·前端·google
大流星12 分钟前
LangChainJs之Prompt提示词(二)
javascript·langchain
雪隐16 分钟前
用Flutter做背单词APP-00前言
前端·人工智能·后端
何时梦醒17 分钟前
前端存储全攻略 & JavaScript this 绑定完全指南
前端·javascript·面试
前端百草阁21 分钟前
JavaScript 设计模式(23 种)
开发语言·前端·javascript·设计模式
EntyIU25 分钟前
Java NIO 实战
java·开发语言·nio