Google Chrome Extension – Developing Analyze-it, a Context Menu

Developing a Google Chrome browser extension that creates a context menu for the active tab is a simple way to add the functionality you desire to the browser using JavaScript. You can use everything the Internet has to offer inside your context menu extension to help you use your browser better. The context menu extension described in this post is simple to develop, and easy to reuse as a simple template. By reverse engineering the GET request parameters in a url, you should be able to accomplish whatever you are doing with less copy-paste, clicks – whatever. This particular extension will open up the Guess and Fetch tools from scritch.org in a new tab with the active tab url passed in for analysis. This should make it easier to research any page in the browser and discover SEO and CMS information about it.

Google Chrome Extension Context Menu Development

Google Chrome Context Menu development is simple as far as structure is concerned. If your context menu is coded to do something relatively simple the extension size will only amount to a few lines of code in a JavaScript file, the manifest, and the graphics needed (graphics are not required to run the extension).

About the objects we will be developing with

There are only two objects in the Google Chrome Extension API to be concerned with when developing extensions similar to the one covered in this post; the tabs object and the contextMenu object. The Google Chrome Extension contextMenu object is very simple, it consists of only four methods, one event and one data type. The three parts we will be developing with is the create method, the onClicked event and the onClickData type. The Google Chrome Extension tabs object is slightly more complex. However, since we will only be creating a new tab and pointing it to a url, coding its usage is trivial  The only method in the tabs object we will be using is the chrome.tabs.create method which takes one object that contains the url as a parameter, This type of extension is small in size. There’s only a few lines of code to go over and explain. Mostly, the boilerplate and the graphics for the extension is what takes up the most space.

The file structure of a Google Chrome Browser Extension

The file structure for this extension is going to be the bare minimum needed for an extension. The files involved are a JSON manifest file required by every extension, a JavaScript file referenced in the manifest containing the code that does everything, and the graphics referenced in the manifest.json file. Thats it!  Everything in a folder and run it in unpacked mode (makes sure the developer mode checkbox is selected on the extension page). When an extension gets packed, all the files needed are zipped up at the top level (cannot be in a subfolder). Your folder structure should look similar to:

  • MyChromeExtension
    • manifest.json
    • app.js
    • icon16.png
    • icon32.png
    • icon64.png

The Google Chrome Extension Context Menu Manifest File

The manifest.json file defines all of the properties and permissions associated with the extension. Manifest files can get complex in larger extensions. Important parts of manifest.json in this extension are: the name, description, version, permissions array, background script, manifest version and icons properties. These properties are the bare minimum needed to install and run the extension.

You can actually leave out the icons block if you don’t want to bother with graphics. Chrome will assign default graphics to your extension if none are provided. A good rule of thumb is if you are going to upload your extension to the Google Web Store and distribute it – you should brand it somehow with the graphics. The right graphic can set your extension apart in the end user’s memory; especially if they like it. You should only let Chrome brand your extension while you are developing it.

There’s only one permission in the permissions array, contextMenus. .The contextMenus setting is a silent permission that does not display a warning dialog on installation. See http://developer.chrome.com/extensions/permission_warnings.html for more information regarding permissions settings and warnings.

The background object’s scripts array contains the JavaScript source file name for the extension.

manifest.json

{

"name": "Analyze-it",

"description": "Adds Analyze-it context menu items for the current page. Opens up the scritch.org Guess and Fetch Tools with the active tab url passed in for analysis. Discover SEO and CMS information for any page url",

"version": "0.1",

"permissions": ["contextMenus"],

"background": {

"scripts": ["app.js"]

},

"icons" : {

"16" : "favicon.ico",

"32" : "peopleicon32.png",

"48" : "peopleicon48.png",

"128" : "peopleicon128.png"

},

"manifest_version": 2

}

The Google Chrome Extension Context Menu JavaScript

The JavaScript goes as follows: First, a reference is created to a new menu item. This menu item is the parent context item that will show up when you right click on a page. All other menu items created have to reference this parent reference. Then we start creating the two sub-menu items using the same function used to create the parent – chrome.contextMenus.create. When we created the parent menu item all we passed in was the title, which is the menu item text shown in the menu. There are additional properties we pass in when we create the sub-menu items. The contexts array contains the context settings for the menu item. In this case the setting is set to page, which means the menu item will be shown when the page is right clicked. If you leave this out, the context defaults to page anyway. Then comes the parentId property which should be set to the parent reference created on the first line. Finally, the onclick property should be set to the callback function created for the menu click (which will be created on the next line).

There are two data objects passed into the callback function automatically: the OnClickData object and the tabInformation object. We will make use of the tabInformation object in the callback to retrieve the tab URL. So when you define the callback function pass in those two objects. The callback will start off with a tabCreateProperties object that is defined on the first line of the callback. The tabCreateProperties object contains one key – url. The URL passed into the tabCreateProperties object has to be URI encoded  That object will be passed into a chrome.tabs.create function that will open up the tab and evaluate the URL passed in.

app.js

var hp = chrome.contextMenus.create({"title": "Analyze-it"});

chrome.contextMenus.create({"title": "Fetch Page Info", "contexts":["page"], "parentId": hp, "onclick": fetchIt});

function fetchIt(i, t){

var createProperties = {url: "http://fetch.scritch.org/?url="+ encodeURI(t.url)};

chrome.tabs.create(createProperties);

}

chrome.contextMenus.create({"title": "Guess CMS", "contexts":["page"], "parentId": hp, "onclick": guessIt});

function guessIt(i, t){

var createProperties = {url: "http://guess.scritch.org/?url="+ encodeURI(t.url)};

chrome.tabs.create(createProperties);

}

Running an unpacked extension

Normally, you would download and install an extension from the google site. You must go to the browser menu and choose: Tools->Extensions. There, on the extensions page in the upper right corner of the page, is a Developer mode checkbox. You have to make sure that checkbox is checked before Chrome will allow you to load an unpacked extension (in a folder on the file system). This way you can run any code you want any time you feel up to coding something.  To load something just hit the Load unpacked extension button and choose your extension’s working folder. Don’t forget to reload the extension after you make any code changes to test it.

Running a downloaded extension

If you downloaded an extension from somewhere other than Google, Chrome will not let you install it on the fly. You have to go to the browser menu and choose Tools->Extensions to open up the Extensions tab. Then drag the extension from wherever it is on the file-system to the open Extensions page. This should start the install process. CAUTION! INSTALLING EXTENSIONS IN THIS WAY CAN CAUSE DAMAGE!. You really have to trust the source of the extension if you install it this way. Google has a complete infrastructure that, believe it or not, makes installing extensions through them the safest way. Google will hold the developer account accountable if something turns out to be malicious. Downloading and installing an extension from somewhere other than Google takes that small incentive to write clean, non-malicious code away. Take it from me, its far too easy for someone to write an extension for Google Chrome that steals your passwords or banking information – across every account you visit! Just to be safe you should always install any browser extension from the Chrome Web Store.

Context Menu Extension Development on Demand

Context menu extensions are so small you’ll most likely memorize the basics quickly. If you’re a student or writer, being able to develop these on the fly is skill that could come in handy. Cutting down the number of actions needed to accomplish something can make using Chrome easier and more efficient, Having the right extension can make the difference between doing something and getting aggravated or simply doing something. I haven’t found a cheat sheet on the Internet for writing Google Chrome Browser Extensions so I recommend that you keep a sort of boilerplate file with easy to reuse functionality in it that you can turn to. Having that boilerplate code around while you’re browsing or doing your research can help. If you find yourself doing something over and over again repetitively, you should try to make that action into an extension if possible.

Let’s consider the end user who had a habit of selecting some text on one webpage and copying it, opening another page and pasting the text into that second page’s search box and then searching. There’s the chance to lighten the users load by writing an extension to automate that task flow. Ideally, what you would want is a menu item to click instead of copy that does everything. It’s not too hard to do this for any web site. The key to doing this is reverse engineering the search GET request and setting up the tab creation function to use a url that includes your parameters (the selected text) in the request. It will appear that a new tab will open up to the search for the selected text you originally selected.

Reverse Engineering a GET Request

In a GET request, everything after the question mark is an array of url encoded key value pairs denoted by ampersands. What you have to do on the site being searched is do a search. When your results page comes up look at the url. Locate where your search term is located. First, copy the url up to the question mark (include it) and paste it somewhere.  Now copy the key (include the equals sign). The key gets pasted onto the end of the url you pasted earlier – which creates the url used in the tab creation. Sometimes there will be a plethora of extra system data being passed into the search, you can ignore the rest for now.

If the tab opens up to content other than what you planned when your extension is built and runnung you should go back to the GET request and check if you are missing a parameter. Most web applications work if session information in the url is missing.

Create the extension

Basically cut and paste the code in this extension to use as a template. Next you’ll have to change all the values around to suit your needs. Name, description, version should be changed in the manifest. In app.js you’ll have to change the menu titles to something suitable and the context menu context to selection because its the selected text being passed in as a parameter instead of the page url. The callback name and reference should also be changed to something suitable. Now take the string you created earlier (web address – it should end with an equal sign) and replace the url in the tab’s createProperties object with it.

The selected text that is passed to the search query is in the OnClickData object (the other object being passed in automatically to the callback) in the selectionText property. We will use the encodeURIComponent function instead of encodeURI to encode the selected text and prepare it to be concatenated into the GET request that open up the new tab. The i.selectionText property holds the text to be encoded in the JavaScript file. The url in the code below is fictional and included for illustrative purposes only. The code is not a working extension in other words.

All things considered, its pretty easy to write an extension for a web application on the Internet. It doesn’t have to be the search box you connect your browser to, it can be any site with a form that uses GET instead of POST.

The code alterations should look something like the following:

manifest.json

{

"name": "Search Somesite",

"description": "Adds a Search menu item with the Searh Somesite submenu",

"version": "0.1",

"permissions": ["contextMenus"],

"background": {

"scripts": ["app.js"]

},

"icons" : {

"16" : "favicon.ico",

"32" : "peopleicon32.png",

"48" : "peopleicon48.png",

"128" : "peopleicon128.png"

},

"manifest_version": 2

}

app.js

var hp = chrome.contextMenus.create({"title": "Search"});

chrome.contextMenus.create({"title": "Search some site", "contexts":["selection"], "parentId": hp, "onclick": search});

function search(i, t){

var createProperties = {url: "http://somesite.com/search.php?query="+ encodeURIComponent(i.selectionText)};

chrome.tabs.create(createProperties);

}

There are many small sites on the Internet that don’t have browser extensions either because they don’t have the time or don’t have the budget to develop them. If you use one of these sites extensively maybe its time to whip up an extension to make life a bit easier.

Adding functionality to make the browser easier or simpler to use is what many an end user has often wished they could do in the past. Google made it easy to develop browser extensions in JavaScript for their popular web browser Chrome (and the open source version often used on Linux- Chromium) . Google Chrome Browser Extensions also run on Comodo Dragon a Chromium based secure version of Chrome that centers on privacy.

Related:

Chrome Browser:

Google Chrome Extension:

Google Chrome Extension Development:

References From Google Developer:

Advertisements

2 thoughts on “Google Chrome Extension – Developing Analyze-it, a Context Menu

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s