Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to access background script public function #64

Open
redochka opened this issue May 19, 2019 · 3 comments
Open

How to access background script public function #64

redochka opened this issue May 19, 2019 · 3 comments

Comments

@redochka
Copy link

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?

@SzpakLabs
Copy link

SzpakLabs commented May 22, 2019

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"});
  });

@samuelsimoes
Copy link
Owner

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.

@bashbaugh
Copy link

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;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants