Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is chrome.tabs undefined in the background page?

I'm trying to write a Google Chrome extension.

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.

This behavior is manifest in both my code and the Google sample code.

The Real Question: How do I run JavaScript on the active tab from a background page in a Chrome extension?


background.js:

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

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"
  • Including the "tabs" permission

The runtime throws this error when I try access chrome.tabs:

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

like image 758
Mashmagar Avatar asked Aug 12 '17 13:08

Mashmagar


People also ask

What is Chrome tabs query?

query() Gets all tabs that have the specified properties, or all tabs if no properties are specified. This is an asynchronous function that returns a Promise .

What is Chrome background script extension?

The background script should be viewed as "running in the background of the Chrome browser". Your desired effect (running a script for every page) is actually a task for content scripts. To learn more, read https://developer.chrome.com/extensions/overview.html#arch. Follow this answer to receive notifications.

Does Chrome suspend inactive tabs?

Starting with Google Chrome 79, a new Tab Freeze feature has been added that will automatically pause (freeze) tabs when they have been inactive in the background for 5 minutes by default until you return to the tab.


1 Answers

wOxxOm's comment diagnosed this correctly:

This is a bug [in Chrome] when you use 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.

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.

like image 186
Mashmagar Avatar answered Oct 11 '22 23:10

Mashmagar