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

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

相关推荐
PythonFun17 分钟前
Python批量下载PPT模块并实现自动解压
开发语言·python·powerpoint
Death20021 分钟前
Qt 6 相比 Qt 5 的主要提升与更新
开发语言·c++·qt·交互·数据可视化
机器视觉知识推荐、就业指导24 分钟前
使用Qt实现实时数据动态绘制的折线图示例
开发语言·qt
快乐就好ya1 小时前
Java多线程
java·开发语言
CS_GaoMing2 小时前
Centos7 JDK 多版本管理与 Maven 构建问题和注意!
java·开发语言·maven·centos7·java多版本
2401_858120533 小时前
Spring Boot框架下的大学生就业招聘平台
java·开发语言
万叶学编程3 小时前
Day02-JavaScript-Vue
前端·javascript·vue.js
转调3 小时前
每日一练:地下城游戏
开发语言·c++·算法·leetcode
Java探秘者3 小时前
Maven下载、安装与环境配置详解:从零开始搭建高效Java开发环境
java·开发语言·数据库·spring boot·spring cloud·maven·idea