我需要复制chrome.runtime.lastError功能。如何在自定义函数中未捕获chrome.runtime.lastError时触发警告?
if(self.chrome == null) {
self.chrome = { runtime: { } }
}
chrome.test = function(option, callback) {
if(option) {
callback("done")
} else {
chrome.runtime.lastError = { message: "Needs something." }
callback()
chrome.runtime.lastError = undefined
} }
chrome.test(false, function(result) {
console.log(result)
})

答案 0 :(得分:0)
我能够使用Proxies并覆盖chrome.runtime来实现此功能。
if(self.chrome == null) {
self.chrome = { runtime: { } }
}
chrome.test = function(option, callback) {
if(option) {
callback("done")
} else {
let error = "Needs something."
let unchecked = true
chrome.oldruntime = chrome.runtime
chrome.runtime = new Proxy(chrome.runtime, {
get(target, key) {
if(key == "lastError") {
unchecked = false
return({ message: error })
} else {
return(target[key])
} } })
callback()
chrome.runtime = chrome.oldruntime
if(unchecked) {
console.error("Unchecked runtime.lastError while running chrome.test: " + error)
} } }
chrome.test(false, function(result) {
console.log(result)
})