Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension Registering Events in Background.js

My extension needs to provide some service to it's users and part of it's job is to listen to tab creation events. I have all my JavaScript in popup.js and have the self invoking:

chrome.tabs.onCreated.addListener(function(tab) { 

The thing is the extension only listens to tab creation events if the user clicks on the extension symbol (if he opens the extension hence activating popup.js), and if the poupup screen is closed all event listening stops. (I verified it by writing to console, and it makes sense if you stop to think about it).

My question is: I want to listen to events throughout the extension's life (in other words ever since the user opens chrome) and not only when the user pops up the extension.

I know there's a thing called a background page, should I try to move my entire code over there? I this normal practice for background pages? It's just that the event listeners are dependent on more functions and more objects and it seems that almost all my code will go there. popup.js will be left with almost nothing. Another thing is I'm not sure if it's possible to register events in the background page before the domcontentloaded event was fired (and this event only fires when the user pops up the extension).

Any help would be appreciated!

like image 519
Joel Blum Avatar asked Nov 03 '22 18:11

Joel Blum


1 Answers

A background page is the best way to handle that, it sits in the background whilst the browser's running. See http://code.google.com/chrome/extensions/background_pages.html for a more detailed explanation. It's worth noting it doesn't have to be an HTML page, you can just have a script file.

Anything you need to run independently of the browser action should be in the background script; the popup essentially doesn't exist until you click the button. You can pass data between background scripts and the popup though if you need to, take a look at http://code.google.com/chrome/extensions/messaging.html.

One other thing to note is that the background page doesn't have access to the DOM. Neither will your popup.js for that matter so it may not be an issue.

Hope this helps!

like image 131
Paul Avatar answered Nov 08 '22 16:11

Paul