对于 chrome Chrome 92+
,您可以使用args
chrome.tabs.query({active: true, currentWindow: true}).then(([tab])=>{
const para = "Hello world!!!"
chrome.scripting.executeScript({
target: {tabId: tab.id},
function: (args) => {
alert(args)
},
args: [para]
})
})
或者您可以使用chrome.storage
{
"manifest_version": 3,
"permissions": [
"storage",
"activeTab",
"scripting"
]
}
chrome.storage.sync.set({msg: "hello world"})
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}`)
})
}
})
})
args 中传递函数的更新可以吗?
你不能
也不Storage
是Args
,它们都不能接受函数参数。
例子:
const myObj = {
msg: "Hi",
myNum: 1,
myFunc: ()=>{return "hi"},
myFunc2: function() {return ""}
}
chrome.storage.sync.set({
msg: "my storage msg",
myObj,
})
chrome.tabs.query({active: true, currentWindow: true}).then(([tab])=>{
chrome.scripting.executeScript({
target: {tabId: tab.id},
function: (para1, para2MyObj) => {
console.log(para1) // Hello
console.log(JSON.stringify(para2MyObj)) // {"msg":"Hi","myNum":1} // myFunc, myFunc2 are missing. You can't get the variable if its type is function.
chrome.storage.sync.get(['msg', "myObj"], ({msg, myObj})=> {
console.log(`${msg}`) // "my storage msg"
console.log(JSON.stringify(myObj)) // {"msg":"Hi","myNum":1}
alert(`Command: ${msg}`)
})
},
args: ["Hello", myObj]
})
})