Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

chrome.extension.getBackgroundPage() function example

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?

like image 582
Niko Avatar asked Jan 15 '14 19:01

Niko


People also ask

What is the function of Chrome extension?

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.

Is a Chrome extension an API?

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.


1 Answers

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

like image 104
Pawel Miech Avatar answered Sep 26 '22 07:09

Pawel Miech