Editor’s note: We found an interesting series of articlesLearn 30 New Technologies in 30 Days, is being translated, an update a day, year-end gift package. Here’s day 29.


Today’sLearn 30 New Technologies in 30 DaysI decided to learn how to write a Chrome extension. After doing somesearchLater, I found a Yeoman generator that could be used to write Chrome extensions. The extension we’re going to write in this post is a plugin that can block social networking sites like Facebook, Twitter, LinkedIn, etc. during work hours. This article will not cover the basics of Yeoman, you can read it24 daysLearn more about Yeoman.

Chrome extension use case

We’ll write a simple plugin that prevents us from accessing social networking sites like Facebook and Twitter during office hours (9am to 6pm). If a user visits Facebook or Twitter, he will see the following page:



I did not block Google + 🙂

Install the Yeoman

Execute the following command to install Yeoman. This command assumes you have Node and Npm installed:

$ npm install -g yeoman

The above command installs yeoman globally. The -g option specifies what global installation means. If you don’t have Grunt and Bower installed on your machine, this command will also automatically install them for you.

GitHub

The code for today’s demo app is available on GitHub: day29-chrome-extension.

Create a Chrome extension

Now, with the basics covered, let’s get started with the development of the Chrome extension.

Create a directory for your extension in a convenient place on your file system, and then move the working directory to the extension directory.

$ mkdir no-socializing
$ cd no-socializing

Then runyo chrome-extensionCommand, which will ask you the following questions.



Let’s go through these questions one by one:

1. It first asks how we want to name the extension. The default name is the folder name.

2. It then asks the purpose of the extension

3. It then asks us if we want to use the UI Action. We use the Browser UI Action. Browser Action allows you to place a clickable icon next to Chrome’s Omnibox. Clicking on this icon opens an HTML file.

4. It then asks if we need to add more UI functionality. We add the Option Page and the Omnibox feature.

5. Finally, it asks what permissions we want to give this extension. Please read theThe documentLearn more details.

You can install the unpackaged extension on Chrome as follows. Check theDeveloper ModeAnd then clickLoad unpackaged extensionsAnd then inno-socializingDirectory to give itappDirectory.

After installation, you should see the following:

Update Background. Js

The behavior of this Chrome extension is controlled by background.js under the folder app/scripts. Copy the code below and replace the background.js source code.

'use strict';

chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
        var currentTime = new Date();
        if(isOfficeTime(currentTime) && isWeekday(currentTime)){
            return {redirectUrl: chrome.extension.getURL('index.html')};    
        }
        return details.url;
    },
    {
        urls: [
            "*://*.facebook.com/*",
            "*://*.twitter.com/*",
            "*://*.gmail.com/*",
        ],
        types: ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "other"]
    },
    ["blocking"]
);

function isOfficeTime(currentTime){
    var hour = currentTime.getHours();
    return hour > 9 && hour < 18;
}

function isWeekday(currentTime){
    var dayOfWeek = currentTime.getDay();
    return dayOfWeek >= 1 && dayOfWeek <= 5;
}

The above code does the following: it listens for the OnBeForeRequest event, which triggers the incoming request. The addListener function takes three arguments: 1. A callback function, which is executed when the event is triggered. 2. RequestFilter object, which is a filter that filters WebRequest events. We’ll list a list of URL patterns to be filtered out. 3. A blocking string containing a blocking string will be processed at the same time.

We also defined some functions to query the current time and the current date on which day of the week it is. It only blocks social networking sites between 9am and 6pm on weekdays.

The above code uses the WebRequest API. We need to give this extension access to the chrome. WebRequest API. This uses the WebRequest permission. Because this extension uses the chrome. WebRequest API in the blocking module, we have to give WebRequestblocking permission as well. Open the manifest. Json file in the app directory and update the permissions module:

"permissions": [
    "webRequest",
    "tabs",
    "http://*/*",
    "https://*/*",
    "webRequestBlocking"
  ]

The last thing we need to do is add an index.html. This is what the user renders when they visit Facebook, Twitter, etc.

<! DOCTYPE html> <html lang="en"> <head> <title>No Socializing</title> <link rel="stylesheet" href="/styles/main.css"> </head> <body> <h1>NO, Socializing</h1> <img src="/images/no-social-media.jpg" height="450" width="450"> <h2>It's Office Time Dude</h2> </body>  </html>

You can download the images from the GitHub repository

Now, reload the extension and open ithttp://facebook.comorhttp://twitter.com. If the current time is between 9am and 6pm on a weekday, you will see the following page:

That’s it for today. Keep feedback.


Day 29: Yeoman Chrome Generator–Write Your First Google Chrome Extension