[英]Communication of background with content script
我试图与内容脚本交流背景,但我的方法行不通。 我想知道为什么它不起作用以及如何解决此问题(其他解决方案不起作用。idk为什么)。
Manifest.json:
{
"manifest_version": 2,
"name": "X",
"version": "2.0",
"browser_action": {
"default_title": "title"
},
"permissions": [
"activeTab",
"tabs"
],
"content_scripts": [
{
"matches": ["https://*/*"],
"js": ["content_scripts/jquery.min.js", "content_scripts/script.js"],
"run_at": "document_idle"
}
],
"background": {
"scripts": ["background/background.js"]
},
"icons": {
"16": "icon.png",
"32": "icon.png",
"48": "icon.png",
"64": "icon.png",
"128": "icon.png"
}
}
Background.js:
chrome.tabs.query({active: true}, function (tabs) {
tabs.forEach((cur, i)=>{
chrome.tabs.sendMessage(tabs[i].id, {"delBody": true})
})
})
ContentScript:
chrome.runtime.onMessage.addListener(function(obj, sender) {
if(obj.delBody)
document.body.remove()
})
非常感谢您。 问题出在
当您的扩展程序加载到浏览器启动/更新中时,当您的内容脚本尚未注入时,后台脚本将运行
所以我这样解决:
内容:
chrome.runtime.sendMessage({"getInfo": true})
chrome.runtime.onMessage.addListener(function(obj, sender) {
if(obj.delBody)
document.body.remove()
})
背景:
chrome.runtime.onMessage.addListener(function(obj, sender) {
if(request.getInfo) {
chrome.tabs.query({active: true}, function (tabs) {
tabs.forEach((cur, i)=>{
chrome.tabs.sendMessage(tabs[i].id, {"delBody": true})
})
})
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.