Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Chrome Extension - How to Use Commands and Background Scripts

4.00/5 (1 vote)
7 Oct 2014CPOL4 min read 22.2K   348  
This tip shows how to create a chrome extension via a background JavaScript page and commands.

Background Pages and Commands - Chrome Extension

This tip discusses how background scripts and commands (issued from the keyboard) can be used in combination to create a Chrome Extension. This chrome extension displays the Tab Id and Tab URL for the current open/active tab.

Background

Basic knowledge of JavaScript will be an advantage. Please go through the basic structure of manifest.json file for a deeper understanding. Use the documentation given by Google chrome for the same.

Using the Code

NOTE: The details on how to export the extension in chrome is discused in the Article_demo.

We shall discuss the technical details of the extension here. Let us begin with Manifest.json file. Json is a notation to describe data/text in key-value pair form. All chrome extensions need the information regarding what is to be loaded, that is how should the extension look like on chrome page, what image it needs to display, should the user be able to see the description of extension when the user hovers over the extension icon. Extensions need information of background scripts running in the background and whether they are required to be persistent or not.

All this basic information regarding the configuration setting of the extension is given in "Manifest.json". Let us discuss important code snippets here.

JavaScript
"browser_action": {
    "default_title": "This App will display Tab Id and Tab URL when user issues the command.",
    "default_icon": "hello.png" 
  }

Browser Action tells chrome that icon of this extension is to be shown outside the Omnibox/URL box. As shown:

Image 1

"default_icon" is the name of the file to be displayed. Make sure that it is in the same directory level as that of Manifest file. "default_title" is the extension description which gets displayed when the user hovers over the icon.

Image 2

Extension needs to know the name of background script and whether is it persistent or it should be invoked when some event happens. For example: if you want to create an extension which will get the facebook feeds after every 10 minutes, then this is the example of persistent background script while the extension which triggers a background process once an event is fired or command is issued are not persistent.

JavaScript
"background": {
    "persistent": false, // As explained above
    "scripts": ["TabBackGround.js"] // Multiple comma separated names of background scripts can be added 
  },

Now, let us focus on the "commands;" section of which is used to register the set of commands for which the background process will be fired.

JavaScript
"commands":
	{
		"toggle" : 
		{
			"suggested_key": {
				"default": "Alt+A",
				"mac": "Command+Shift+Y" 
			},
			"description" : "Display Id and URL of the current open/active tab."
		}
	},

"commands" section is used to register the commands which shall be identifed by the background script. Though only one such command has been registered in this extension named "toggle", multiple commands can be declared in this section. Suggested key declares the set of keys required to intiate the command. These keys may be separately configured for Windows and Mac platform. It is good to have the description written for the command.

This ends the introduction to manifest file. Now let us discuss about the background script which contains the main functionality of the extension.

JavaScript
chrome.commands.onCommand.addListener(function(command) { /*Your stuff lies here*/});

chrome.commands.onCommand.addListener is used to listen to the commands registered with the manifest file. The significance of the function parameter command is that it is used to identify the command issued by the user.

Example: When the user presses ALT+A(windows) or Command+Shift+Y(mac) platform, listener attached in the background script receives the request to process the command. We can compare if the incoming command is "toggle" only then process it, as shown below.

Image 3

JavaScript
if (command == "toggle") 
{
	alert ("3. Resolved Command");
	alert ("TAB ID = " + currentTabId + "\n URL =  " + currentTabURL);
}	

So far, we have the seen code snippets to capture the command issued by the user. We have already discussed what is to be done once the user presses ALT+A(windows) or Command+Shift+Y(mac) platform. Next, we need the information related to the tabs. The relevant code to do the same is discussed below.

JavaScript
chrome.tabs.query({active:true, currentWindow: true}, function(arrayOfTabs) {

		alert("2. Filtering Results");
		currentTabURL = arrayOfTabs[0].url;
		currentTabId = arrayOfTabs[0].id; 
			
	});

Query function returns the array of tabs which satisfy the parameters mentioned. So the above query asks chrome to return all the tabs which are active and the tabs are in the current window. If we want the information of all tabs irrespective of whether the tabs are in the current window or not, use:

JavaScript
currentWindow:false

Points of Interest

The point to note here is the query call since it is asynchronous. Example: Just remove the:

JavaScript
alert ("3. Resolved Command");

or comment all the alert statements and you shall see that the results are not as expected. Executing chrome.tabs.query will not do anything immediately (and will not return anything, by the way), but instead asks Chrome to query the tabs whenever it can. So do not expect a normal sequential flow of call.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)