【发布时间】:2019-07-24 07:21:59
【问题描述】:
在contentScript.js 中没有调用该函数。
background.js
var insertUI = true
// var hasExecutedOnce = false
chrome.browserAction.onClicked.addListener(function(tab) {
console.log(`clicked browserAction`)
// if (!hasExecutedOnce)
chrome.tabs.executeScript(tab.id, {
file: 'contentScript.js',
})
chrome.runtime.sendMessage({
from: 'background',
subject: insertUI ? 'insertUI' : 'removeUI',
})
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.subject === 'doneRemovingUI') insertUI = false
else if (request.subject === 'doneInsertingUI') insertUI = true
})
insertUI = !insertUI
// hasExecutedOnce = true
})
console.log(`bg`)
manifest.json
{
"manifest_version": 2,
"name": "Sample",
"version": "1.0.0",
"description": "Sample Extension",
"icons": {
"16": "icon16.png",
"19": "icon19.png",
"24": "icon24.png",
"32": "icon32.png",
"38": "icon38.png",
"48": "icon48.png",
"64": "icon64.png",
"128": "icon128.png"
},
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_icon": {
"19": "icon19.png",
"38": "icon38.png"
}
},
"permissions": ["activeTab", "<all_urls>"]
}
contentScript.js
var body = document.getElementsByTagName('body')[0]
function insertUI() {
console.log(`insertUI`)
var div = document.createElement('div')
div.setAttribute('id', 'sample-extension-12345')
div.innerHTML = `<h1>Sample Extension</h1>`
body.appendChild(div)
}
function removeUI() {
console.log(`removeUI`)
var divId = document.getElementById('sample-extension-12345')
body.removeChild(divId)
}
function main() {
console.log(`main called`)
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
console.log({ msg, sender, sendResponse })
if (msg.subject === 'insertUI') {
insertUI()
sendResponse({
from: 'content',
subject: 'doneInsertingUI',
})
} else if (msg.subject === 'removeUI') {
removeUI()
sendResponse({
from: 'content',
subject: 'doneRemovingUI',
})
}
})
}
console.log(`contentScript`)
main()
所以一切正常。 insertUI() & removeUI() 在 contentScript.js 中单独工作,但 chrome.runtime.onMessage.addListener 永远不会被调用。
其中的console.log() 未被调用。休息一切正常。插入 DOM 和删除 DOM 是分开工作的。他们只需要在切换browser_action 时工作。
【问题讨论】:
-
要将消息从后台脚本发送到内容脚本,您必须使用
chrome.tabs.sendMessage,而不是chrome.runtime.sendMessage。此外,您必须在内容脚本运行后发送消息,即在chrome.tabs.executeScript的回调函数中。最后是分号。 -
所以我按照您的要求更改了所有内容,并且可以正常工作。但是,现在我遇到了从 DOM 中多次插入和删除的问题,因为
executeScript每次单击browser_action时都会添加脚本。我该如何解决这个问题?这是完整的要点gist.github.com/deadcoder0904/ac26007a86e3a57846125446bf6c5227 -
@IvánNokonoko 我也添加了解决方案作为答案,尽管从技术上讲它有自己的问题。也请检查下面的答案,因为我添加了不起作用的屏幕截图。它还不断在 DOM 中添加节点并删除它们。如果你知道如何解决这个问题,那会很有帮助:)
-
好的,终于找到了一个完美的解决方案。将其发布为答案:)
标签: javascript google-chrome-extension firefox-addon browser-extension