David Biga
David Biga

Reputation: 2801

Google Chrome Extension - background script

After messing around with Chrome Extension I noticed that when you are on the chrome://extensions page a background script initiated in the manifest file will run where as if you are just browsing the internet or on another other page besides the extension page the background script will not run.

Here is what I mean:

In my Manifest file:

"background": {
    "scripts": ["jquery-latest.js","background.js"]
  },

Now in the background.js file:

$(document).ready(function(){
    alert("working");
});

I use a simple alert function to see if this will work and found out that alert("working"); only gets displayed when I am on the chrome://extension directory. If I go to google.com or something of that sort, no cigar.

My question lies in, why does this happen? How do I change it so it does alert no matter what.

Upvotes: 26

Views: 81434

Answers (4)

Sean
Sean

Reputation: 827

The background script is a script running in the background to handle majority of chrome events that content scripts cannot. Content scripts are purely the content of the each page. Both cannot speak to each other, however, you can give the scripts listeners (e.g. chrome.browserAction.addListener(myFunction) plays the function when the button in the top right of your screen for the extension is clicked) order to find out whether a button has been pressed or even send a message from the background script into the page's console.

https://youtu.be/ew9ut7ixIlI This video was a great introduction for me about background scripts, however, the part where he begins to talk about the listeners and such is 6:30.

Upvotes: 1

Rajan Verma - Aarvy
Rajan Verma - Aarvy

Reputation: 2117

The effect is produced because whenever you load chrome://extensions it forces the extensions to reload, the same behavior can be reproduced using CTRL+R. So every time, the background page got a fresh reload, which doesn't happen in case of other pages.

Upvotes: 2

Ninoop p george
Ninoop p george

Reputation: 678

It is because you are using the background page .. use the event page instead by slightly modifying the manifest.json.. Try adding this:

"background": {
    "scripts": ["jquery-latest.js","background.js"],
    "persistent": false
  },

for more details on event pages check this : https://developer.chrome.com/extensions/event_pages

Upvotes: 4

Rob W
Rob W

Reputation: 348962

The background script should be viewed as "running in the background of the Chrome browser".
Your desired effect (running a script for every page) is actually a task for content scripts.

To learn more, read https://developer.chrome.com/extensions/overview.html#arch.

Upvotes: 37

Related Questions