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

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

相关推荐
pixelpilot13 分钟前
微软常用运行库directx修复工具(directx repair)2026版directx下载下载安装教程
java·开发语言·其他·microsoft
cany10006 分钟前
C++进阶 -- std::deque‌ 和 ‌std::list
开发语言·c++
曾几何时`7 分钟前
Go(二)Goroutine及GMP模型
开发语言·后端·golang
AD钙奶-lalala8 分钟前
kotlin反射
android·开发语言·kotlin
老毛肚9 分钟前
jeecgboot vue Pinia 拆分01
前端·javascript·vue.js
2301_7890156211 分钟前
Lnux权限
linux·开发语言·c++·权限
江湖中的阿龙12 分钟前
Go语言零基础入门教程(一)环境搭建与基础入门
开发语言·后端·golang
集成显卡8 小时前
Rust实战七 |基于带 colored 颜色文字控制台的批量文件删除工具
开发语言·后端·rust
夜焱辰9 小时前
浏览器端 Agent 的文件版本管理:不用 Git,基于 OPFS + SQLite 自己造了一个
前端·人工智能
梦想的颜色9 小时前
TypeScript 完全指南(下):从类型体操到生产级配置
前端·javascript·typescript