chrome-extension-webpack-boilerplate icon indicating copy to clipboard operation
chrome-extension-webpack-boilerplate copied to clipboard

How to access background script public function

Open redochka opened this issue 5 years ago • 3 comments

In my popup.js i used to do: bg = chrome.extension.getBackgroundPage() to get access to the background page. Then I could do bg.xxx() ...

However, with this setup, i am getting:

Uncaught (in promise) TypeError: bg.xxx is not a function

Any clue?

redochka avatar May 19 '19 04:05 redochka

In my popup.js i used to do: bg = chrome.extension.getBackgroundPage() to get access to the background page. Then I could do bg.xxx() ...

Try chrome.runtime.getBackgroundPage instead of chrome.extension.getBackgroundPage

Also you can use messages to/from background page:

popup.js

chrome.runtime.sendMessage({purpose: "ping"}, function(response) {
  console.log(response.resolution);
});

background.js

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
  console.log(request.purpose);
    if (request.purpose === "ping")
      sendResponse({resolution: "pong"});
  });

SzpakLabs avatar May 22 '19 06:05 SzpakLabs

This happens because the background page in this setup is a module, so you can't access the methods from this module with this direct approach because the module encapsulates everything instead of defining everything in the global scope (which allowed you do this access).

Access directly to the methods from other contexts is a slightly bad practice, so the suggested method by @SzpakLabs is the recommended way to do this.

samuelsimoes avatar Nov 23 '19 15:11 samuelsimoes

This is also somewhat bad practice, but if you really need to make your function global to the window object and access it with getBackgroundPage, you can do so by directly setting window.xxx = xxx;

bashbaugh avatar May 31 '20 23:05 bashbaugh