我正在尝试编写 Google Chrome 扩展程序。
documentation甚至 sample code假设后台页面可以使用 chrome.tabs.executeScript
方法在事件选项卡上运行 JavaScript,但是当 chrome.tabs
总是 undefined
时我中断了调试器。
此行为在我的代码和 Google 示例代码中均有体现。
真正的问题:如何从 Chrome 扩展程序的后台页面在事件选项卡上运行 JavaScript?
背景.js:
chrome.browserAction.onClicked.addListener(function(tab) {
debugger;
// chrome.tabs is undefined here
chrome.tabs.executeScript({
code: "console.log('hi')"
});
});
list .js:
{
"manifest_version": 2,
"name": "Hello World",
"description": "Says 'hello' to the world.",
"version": "0.1",
"permissions": ["tabs", "activeTab"],
"browser_action": {
"default_title": "hi"
},
"background": {
"scripts": ["background.js"]
}
}
我尝试过的事情:
- 将 list 文件中
background
上的persistent
标志设置为false
、true
、”假”
和“真”
- 包括
“tabs”
权限
当我尝试访问 chrome.tabs
时,运行时抛出此错误:
tabs.binding 的 Lazy require 没有设置绑定(bind)字段
最佳答案
wOxxOm
的评论正确地诊断了这一点:
This is a bug [in Chrome] when you use
debugger;
statement.
然而,我发现它比这更深入。仅断点就足以解决这个问题。感谢this SO answer指出断点也可能导致此问题。
您必须彻底“清除”调试器。重新加载扩展时必须关闭调试器窗口。仅关闭调试器窗口而不重新加载不足以解决问题。
关于javascript - 为什么chrome.tabs在后台页面未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45650670/