chrome-extension-webpack-boilerplate
chrome-extension-webpack-boilerplate copied to clipboard
How to access background script public function
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?
In my popup.js i used to do:
bg = chrome.extension.getBackgroundPage()
to get access to the background page. Then I could dobg.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"});
});
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.
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;