javascript - 如何将消息从 background.js 传递到内容脚本并操作 DOM?
问题描述
我在后台脚本中有一个选项卡更改侦听器,它将检查 URL 并相应地向内容脚本发送消息以进行 DOM 操作。这段代码有什么问题?
我试过 chrome.runtime。以及 chrome.tabs。API。此外,console.log() 在 content.js 中不起作用。
背景.js
chrome.tabs.onActivated.addListener(function(activeInfo) {
chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
let arr = tabs[0].url.split('/');
let url = arr[0] + "//" + arr[2];
if(url=="https://youtube.com"){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(
tabs[0].id, {action: "open_dialog_box"}, function(response) {console.log(response)}
);
});
}
});
});
内容.js
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
console.log(request);
if (request.msg === "youtube_action") {
//console.log(request.data.subject)
alert("kdjfnodf");
}
return true;
});
清单.json
{
"manifest_version" : 3,
"name" : "Play",
"description" : "Play",
"version": "2",
"browser_action" : {
"default_title" : "Play-Pause",
"default_popup" : "popup.html"
},
"permissions" : [
"activeTab",
"tabs",
"background"
],
"content_scripts": [{
"matches": ["http://*/*"],
"js": [
"content.js"
]
}],
"background" : {
"scripts": ["background.js"],
"persistent": false
}
}
解决方案
推荐阅读
- android - Android Instrumented 测试断言是否启动了活动
- selenium - 使用 Selenium 通过 WebDriverwait 提高点击速度
- java - 如何在应用内浏览器(Chrome 自定义选项卡)中直接打开外部链接而不提示选择浏览器
- python - json() 方法和 json.loads() 有什么区别
- r - 如何将默认列从 1 到 n 排序?
- python - 使用笔记本在 Tkinter GUI 中创建选项卡
- flutter - UI Flutter 关于列和行
- c++ - 使用 Array 实现堆栈(改进代码的方法)
- javascript - 如何等待承诺解决而不是使用 Promise.all?
- mysql - mysql ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)