I'm working on a small Chrome extension that needs to run in the background. However, I understand that that isn't possible when I'm using a popup. After some reading it seems that the best option is to create popup.js
in order run the background.js
, using chrome.extension.getBackgroundPage()
function.
Can someone please show me an example of how it's done?
here's the manifest:
"browser_action": {
"permissions": ["background"],
"default_popup": "popup.html"},
"options_page": "options.html",
"background": {
"scripts": ["background.js"],
"persistent" : true
}
I've included the popup.js reference in popup.html
:
<script src="popup.js"></script>
And created a variable in popup.js
var bkg = chrome.runtime.getBackgroundPage();
so now I need a way to activate the background.js
Do I need to run the relevant function inside background.js
from popup.js
,
or give a general command for the background.js
to run?
A chrome extension is a way of adding functionality to the chrome browser. You can add interface elements, open and close tabs, interact with the address bar, as well as modify the contents of any page the browser is currently on.
The chrome. extension API has utilities that can be used by any extension page. It includes support for exchanging messages between an extension and its content scripts or between extensions, as described in detail in Message Passing.
Yes, you need to call function from background in your popup. Here's a simple example which demonstrates how it works.
background.js
function backgroundFunction () {
return "hello from the background!"
}
popup.js
(function () {
var otherWindows = chrome.extension.getBackgroundPage();
console.log(otherWindows.backgroundFunction());
})();
When you inspect your popup.js you'll see "hello from the background!" in your console. GetBackgroundPage() simply returns window object for your background page, as you probably know all variables are attached to this window object so in this way you will get access to function defined in background scripts.
There is a sample code demonstrating this in chrome documentation see Idle Simple Example and look at file history.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With