chrome.extension.getBackgroundPage()
I get null
and accrouding documentation,
Background pages are replaced by service workers in MV3.
- Replace
background.page
or background.scripts
with background.service_worker
in manifest.json. Note that the service_worker field takes a string, not an array of strings.
manifest.json
{
"manifest_version": 3,
"name": "",
"version": "",
"background": {
"service_worker": "background.js"
}
}
anyway, I don't know how to use getBackgroundPage
, but I found another solution as below,
Solution
use the chrome.scripting.executeScript
So you can inject any script or file. You can directly click inspect (F12) and can debug the function.
for example
chrome.commands.onCommand.addListener((cmdName) => {
switch (cmdName) {
case "show-alert":
chrome.storage.sync.set({msg: cmdName}) // You can not get the context on the function, so using the Storage API to help you. // https://developer.chrome.com/docs/extensions/reference/storage/
chrome.tabs.query({active: true, currentWindow: true}).then(([tab])=>{
chrome.scripting.executeScript({
target: {tabId: tab.id},
function: () => {
chrome.storage.sync.get(['msg'], ({msg})=> {
console.log(`${msg}`)
alert(`Command: ${msg}`)
})
}
})
})
break
default:
alert(`Unknown Command: ${cmdName}`)
}
})
I create an open-source for you reference.