简体   繁体   English

为什么chrome.tabs在后台页面中未定义?

[英]Why is chrome.tabs undefined in the background page?

I'm trying to write a Google Chrome extension. 我正在尝试编写Google Chrome扩展程序。

The documentation and even sample code say that a background page can run JavaScript on the active tab using the chrome.tabs.executeScript method, but chrome.tabs is always undefined when I break in the debugger. 文档甚至示例代码都说后台页面可以使用chrome.tabs.executeScript方法在活动选项卡上运行JavaScript,但是当我在调试器中打破时, chrome.tabs总是undefined的。

This behavior is manifest in both my code and the Google sample code. 这种行为在我的代码和Google示例代码中都很明显。

The Real Question: How do I run JavaScript on the active tab from a background page in a Chrome extension? 真实问题:如何在Chrome扩展程序中的后台页面上的活动标签页上运行JavaScript?


background.js: background.js:

chrome.browserAction.onClicked.addListener(function(tab) {
  debugger;
  // chrome.tabs is undefined here
  chrome.tabs.executeScript({
    code: "console.log('hi')"
  });
});

manifest.js: manifest.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"]
  }
}

Things I've tried: 我试过的事情:

  • Setting the persistent flag on background in the manifest file to false , true , "false" , and "true" 将清单文件中background上的persistent标志设置为falsetrue"false""true"
  • Including the "tabs" permission 包括"tabs"权限

The runtime throws this error when I try access chrome.tabs : 我尝试访问chrome.tabs时运行时抛出此错误:

Lazy require of tabs.binding did not set the binding field

wOxxOm 's comment diagnosed this correctly: wOxxOm的评论正确诊断出来:

This is a bug [in Chrome] when you use debugger; 当您使用debugger;时,这是[在Chrome中]的错误debugger; statement. 声明。

However, I've found it goes deeper than that. 但是,我发现它比这更深入。 A breakpoint alone was sufficient to give me this issue. 只有一个断点足以让我解决这个问题。 Thanks to this SO answer for pointing out that breakpoints can also cause this problem. 感谢这个SO答案指出断点也可能导致这个问题。

You have to be thorough to "clear out" the debugger. 您必须彻底“清除”调试器。 The debugger window must be closed when the extension is reloaded. 重新加载扩展时,必须关闭调试器窗口。 Simply closing the debugger window without reloading was not enough to make the problem go away. 简单地关闭调试器窗口而不重新加载不足以使问题消失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM