chrome.tabs.executeScript - succeeded?
chrome.tabs.executeScript - succeeded?
如何才能知道我的执行是否成功
我知道executeScript提供了回调,但如果脚本由于某种原因被阻止,回调就永远不会发生。
我怎么知道?
有两种方法可以检查chrome.tabs.executeScript
调用是否成功:
- 检查
results
属性是否为数组(失败时未定义) - 检查是否设置了
chrome.runtime.lastError
属性(这是推荐的方式)
chrome.tabs.executeScript(tabId, {
code: '// some code'
}, function(result) {
if (chrome.runtime.lastError) { // or if (!result)
// Get the error message via chrome.runtime.lastError.message
return;
}
});
上一个示例仅显示插入内容脚本时发生错误的情况。对于运行时错误,它不会显示任何错误。如果你想知道脚本中是否发生了错误,请打开选项卡的devtools。如果你需要知道后台页面中是否发生错误,请从内容脚本中返回一个值,以表示脚本没有正确运行
最后一个表达式的值被传递给chrome.tabs.executeScript
的回调(在数组中,因为设置allFrames:true
时会传递多个值)。