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

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

相关推荐
hanbr5 小时前
C++ 初涉
开发语言·c++
Дерек的学习记录5 小时前
C++:入门基础(下)
开发语言·数据结构·c++·学习·算法·visualstudio
恋猫de小郭5 小时前
Flutter 正在计划提供 Packaged AI Assets 的支持,让你的包/插件可以更好被 AI 理解和选择
android·前端·flutter
小小前端--可笑可笑5 小时前
Vue / React 单页应用刷新 /login 无法访问问题分析
运维·前端·javascript·vue.js·nginx·react.js
云小逸5 小时前
【nmap源码解析】Nmap 核心技术深度解析:从源码到实战
开发语言·网络·windows·nmap
小林敲代码77885 小时前
记一次 Vue 项目首屏优化:从 7.1s 到 0.9s,深挖 Gzip 的力量
前端·javascript·vue.js
前端大卫5 小时前
写给年轻程序员的几点小建议
前端
前路不黑暗@5 小时前
Java项目:Java脚手架项目的公共模块的实现(二)
java·开发语言·spring boot·学习·spring cloud·maven·idea
人道领域5 小时前
Spring核心注解全解析
java·开发语言·spring boot
云深麋鹿6 小时前
标准库中的String类
开发语言·c++·容器