页面操作
page_action可以在我的 Github 上找到一种工作方式→ https://github.com/deadcoder0904/insert-remove-ui-chrome-extension/tree/page_action
背景.js
var hasExecutedOnce = false
function addUI(tabId) {
chrome.tabs.sendMessage(tabId, {
from: 'background',
subject: 'isUIAdded?',
})
}
chrome.runtime.onInstalled.addListener(function() {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([
{
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { hostEquals: 'www.google.co.in' },
}),
],
actions: [new chrome.declarativeContent.ShowPageAction()],
},
])
})
})
chrome.pageAction.onClicked.addListener(function(tab) {
if (!hasExecutedOnce) {
chrome.tabs.executeScript(
tab.id,
{
file: 'contentScript.js',
},
function() {
addUI(tab.id)
},
)
hasExecutedOnce = true
}
addUI(tab.id)
})
内容脚本.js
var body = document.getElementsByTagName('body')[0]
function insertUI() {
var div = document.createElement('div')
div.setAttribute('id', 'sample-extension-12345')
div.innerHTML = `<h1>Sample Extension</h1>`
body.appendChild(div)
}
function removeUI() {
document.getElementById('sample-extension-12345').remove()
}
function main() {
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.subject === 'isUIAdded?') {
const id = document.getElementById('sample-extension-12345')
if (id === null) insertUI()
else removeUI()
}
})
}
main()
浏览器操作
它还browser_action在 master 分支上有一个解决方案→ https://github.com/deadcoder0904/insert-remove-ui-chrome-extension/
背景.js
var hasExecutedOnce = false
function addUI(tabId) {
chrome.tabs.sendMessage(tabId, {
from: 'background',
subject: 'isUIAdded?',
})
}
qq_花开花谢_0
相关分类