Friday, January 2, 2015

Developing Chrome Extension - How to Build First Chrome Extension

Let's develop a  simple chrome extension to modify some text on visited webpage.
Whenever Google website is visited we will modify all 'Google' text string on page to 'Foogle'.

Following files will be required to achieve this - manifest.json and inject.js

manifest.json

  • Manifest file is required for all extensions.

  • It defines meta data for Chrome.

  • All files & permissions should be declared here.

  • Resource files like images or other template files should be declared as "web_accessible_resources"



  • [sourcecode language="javascript"]

    {
    // required
    "manifest_version": 2
    "name": "Foogle Search",
    "version": "0.1",

    "content_scripts": [
    {
    "matches": ["https://www.google.com/*"],
    "js": ["inject.js"],
    "run_at": "document_end"
    }
    ],

    }

    [/sourcecode]

    "Foogle Search" is the name of chrome extension, and 0.1 is its version.
    content_scripts section tell chrome to insert javascript file inject.js in web pages which matches URL pattern google.com/*
    manifest_version is a mandatory field.


inject.js

  • Content Scripts execute in the context of the visited web page and can access and modify the DOM of the visited page.

  • Content Script do not have access to JavaScript variables or functions of visited web page. Content scripts are not aware of the JavaScript code of the visited page.

  • Since they run in context of webpage they cannot directly communicate with rest of the extension. Message passing is used for communication between content script and rest of the extension.

  • Content scripts can be injected every time a matching URL web page is visited  or can be inserted dynamically in the webpage based on some conditions. Cross Origin Permission should be specified in the later case.

  • Following javascript code searches for all occurrences of text 'Google' in web page and replaces it with 'Foogle'.



[sourcecode language="javascript"]

document.body.innerHTML = document.body.innerHTML.replace(new RegExp("Google", "g"), "Foogle");

[/sourcecode]

Now, to test the extension in brower

1. Open extensions option in Chrome. Type chrome://extensions/ in chrome tab
2. Enable Deverloper Mode checkbox.
3. Click on 'Load Unpackged Extension'
4. Select folder where you have saved extension files.

 

No comments:

Post a Comment