Feeds:
Posts
Comments

Posts Tagged ‘chrome’

I wrote a Chrome extension recently called Chrome Nanny  – For more details see Instructions For Chrome Nanny – A Leech Block like extension for Chrome  . This post is primarily about sharing some the tips I learnt during the process of developing the extension.

Application Logs

One of the most important way to debug the extension is using logs. Sprinkle console.log liberally in your code during development. If you want to view these logs, then go to extensions page (Wrench -> Extensions) , select your extension and click on the appropriate page. Most of the time the primary logic will be in your background html page. Hence you need to select this page in the extensions page to get the developer tools. The last tab there is the console tab which will show your logs. Of course, if the console.log is in some other html page (say options page) , then you want to click on appropriate html file in the extensions page. Each active page of the extension starts its own developer tools window and hence the logs dumped in one is not visible in the other.

Usually, this is the behavior you want. But some times, you may want to redirect all the logs to BackGround html’s console. I don’t recommend it although it is pretty convenient. To achieve this write a wrapper function in your BackGround js which takes a string as input and writes it to console. A sample function might look like this.

writeToConsole : function(stuff)
{
    console.log(stuff);
}

In the code for other html files , you can invoke it . In my case , my BackGround js had an object called BackGroundManager. Hence, I invoke the function as

chrome.extension.getBackgroundPage().BackGroundManager.writeToConsole(someText);

Note that to get access to the BackGround, you need to use getBackgroundPage function. I get BackGroundManager object within it and invoke its writeToConsole function. Of course , it can be much simpler in your code. Once you do this , you can watch all the logs in a single place.

If you are lazy to type the whole expression then write another helper function which can return the background page. This might look like

function bg()
{
    return chrome.extension.getBackgroundPage();
}

You can invoke your object using bg().BackGroundManager using chaining.

A Catch in Tab Update

Chrome has a function to make a tab go to a different URL – chrome.tabs.update . This function has two arguments : A tab id and an updateProperties object. updateProperties has a property called URL which accepts a valid URL.

A sample invocation looks like this :

    chrome.tabs.update(tabId,{‘url’:urlToGo});

The behavior of this API is this : If the URL does not have a protocol, then it assumes that you are trying to load some file from your extension folder. This is useful , for example, when you want to show your help file in a tab. A common mistake (which I did) is giving the url  as http://www.test.com . Here the url does not have a protocol and hence it tries to open a file called http://www.test.com in my extension folder. The lesson is that , you should always remember to have a protocol in the URL to show unless you want to show a file from your extension.

What this means is :

Does not work :   

chrome.tabs.update(tabId,{‘url’:’www.mit.edu’});

Works :  

chrome.tabs.update(tabId,{‘url’:’http://www.mit.edu’});

Profiling Extension’s CPU And Memory Usage

When I was developing the extension , I did not want it to hog lot of memory. Chrome is best know for its blazing speed and I would not want to spoil that experience. Chrome has lot of tools to analyze the extension memory.

Method 1 :
Use this method, if you want an overall extension memory consumption and you do not really care to drill down deep. The easiest way is to press Shift+Esc keys. You can also click on the icon near the Wrench icon , select Developer option and select Task Manager. This will show how much memory each tab and extensions are using. This will give you an approximate value of the memory consumed by your extension.

Method 2 :
If you want to dig deep and figure out which parts of the extension contribute to the memory, then you are in luck. Chrome has some great tools. Go to the extensions page and select the background html page. This will open the Developer tools for the extension. You can select the "Profiles" tab. By default this will not contain any information.

Click on the black dot on the status bar and continue using the extension as usual. After some time, click the same icon and stop the profiling. For best results , I would suggest you do some set of actions which exercise most of the functionality of your extension. Now you can see the CPU profile of the extension so far. It will show all the functions which take a long time to run. You can use this information to fine tune your function.

If you are more worried about memory, then the Heap profile can help. Click on the icon which looks like an Eye to start heap profiling. This will give you a break down of all the objects which take up memory. I find this information to be too much for me to process and I usually ignore it.

Disable Selecting Of Text

For Chrome Nanny, I needed a way to prevent user from copying and pasting text. The scenario is this : When user wants to perform some operation that is forbidden, then I ask the user to enter some random 64 character code as a way to discourage them. Now I wanted to prevent them from using copy and paste to circumvent the challenge. I searched a lot and at last found a working solution – The best part was that it was entirely based on CSS and did not use Javascript at all. I got the idea from this stackoverflow page  . The idea is to have a css class like this :

.no-select
{
   -moz-user-select: none;
   -khtml-user-select: none;
   -webkit-user-select: none;
   user-select: none;
}

Now add this class to your textbox. This will prevent them from selecting text !

Callback functions

Lot of things happen asynchronously in Chrome. Almost all of Chrome APIs accept a callback function. Also a typical extension registers event listeners for the events it is interested in . The downside is that many of them can fired simultaneously and if you are not careful, you internal data structures can become inconsistent.

A more common problem is to know that callback functions need not be called immediately. A bad code is this :

chrome.tabs.getSelected(windowId,function(tab){
    tabId = tab.id
});

if(tabId == blah)
    doSomeThing();

This assumes that Chrome will set tabId inside the callback function before coming to the if. The correct way is to bring the logic inside the callback function (or atleast not make the incorrect assumption). A common way to fix it is

chrome.tabs.getSelected(windowId,function(tab)
{
    tabId = tab.id
    if(tabId == blah)
        doSomeThing();
});

I will talk about more stuff in the next part !

 

Add to DeliciousAdd to DiggAdd to FaceBookAdd to Google BookmarkAdd to RedditAdd to StumbleUponAdd to TechnoratiAdd to Twitter

If you liked this post , please subscribe to the RSS feed.

Advertisements

Read Full Post »

I wrote a Chrome extension recently called Chrome Nanny – For more details see Chrome Nanny – A Leech Block like Extension for Chrome  . I learned lot of interesting things in the process and I will try to write some posts on it.

Originally, I thought of writing a tutorial on writing Google Chrome Extensions – but dropped the idea as Google’s tutorial is fairly comprehensive. So instead , I will try to write about stuff which is not in Google’s tutorials. In this post, I will talk about the various Chrome events that are thrown during usage of Chrome. Tracking these events properly is very important for Chrome Nanny which is both a website blocker ( a la Leech Block) and a time tracker. I suspect these transitions are not that important for most extensions. But still knowing these will help you write extensions better.

Chrome has lot of APIs and event handlers. I will focus on some of events and ignore others . More specifically, I will ignore events like attached/detached etc as their event transitions are fairly straightforward. I will focus on tab/window creation,switching and closing events and their interplay. (ie  the events chrome.tabs.onCreated , chrome.tabs.onRemoved , chrome.tabs.onSelectionChanged , chrome.tabs.onUpdated , chrome.windows.onCreated ,    chrome.windows.onFocusChanged, chrome.windows.onRemoved ). You can read about the event handlers and the arguments they take in the resources given in the References section.

Again for sake of convenience, I have assumed that the default URL opened/entered is google.com. The info I have given below is a bit concise but I hope it is quite understandable.

Tab Creation and Updation Events

1. Open a new tab in an exisiting Window
    create tab event {url : chrome://newtab}
    tab selected event for current tab.
    update tab event { url : null, status = loading, tab url = chrome://newtab}
    update tab event { url : null, status = complete, tab url = chrome://newtab}

2. Open a new tab in an existing Window, but Chrome has some extension that redirects to some other URL
    create tab event {url : chrome://newtab}
    tab selected event for current tab.
    update tab event { url : null, status = loading, tab url = chrome://newtab}
    update tab event { url : null, status = complete, tab url = chrome://newtab}
    update tab event { url : google.com, status = loading, tab url = google.com}
    update tab event { url : null, status = complete, tab url = google.com}

3. When you enter an URL in the current tab
The behavior is same if the tab is new or existing.
    update tab event { url : google.com, status = loading, tab url = google.com}
    update tab event { url : null, status = complete, tab url = google.com}

4. Click on a url and make it open in a new tab  – but focus does not shift to new tab
This happens when you right click and say "Open in new tab" or press (ctrl+enter).
    create tab event {url :googe.com}
    update tab event { url : null, status = loading, tab url = google.com}
    update tab event { url : null, status = complete, tab url = google.com}

5. Click on a url and make it open in a new tab – and focus shifts to new tab
This happens when you press (ctrl+shift+enter).
    create tab event {url : googe.com}
    tab selected for current tab.
    update tab event { url : null, status = loading, tab url = google.com}
    update tab event { url : null, status = complete, tab url = google.com}

6. Refresh the Current Tab
Assuming the tab has google.com and you refresh the page.
    update tab event { url : null, status = loading, tab url = google.com}
    update tab event { url : null, status = complete, tab url = google.com}

Window Creation And Updation Events

1. Open a new window
This happens when you press ctrl+n or select "New Window" in Chrome.
    window created event
    Tab creation scenario (1) or (2)
    window focus changed event for current window

2. Open a link in new window
This happens when you right click on a link and say "Open In New Window".
    Window created
    Tab creation scenario (4)
    window focus changed event for current window

3. Open a link in incognito mode or Open a new Incognito window
    No events thrown. (For Chrome version 5.0 and less.  From Chrome 5.0, if you allow access to an extension in incognito mode, then the events are thrown as in the regular scenarios.

Tab And Window Switching Events

For discussion assume we have two windows w1 and w2. w1 has two tabs a1 and b1. w2 has two tabs a2,b2.

1. Shift to different tab in same window
For eg, we are in a1 and we move to b1. This happens when you select the new tab via mouse, or using keyboard like ctrl+tab or select an exact tab using ctrl+tab number.
    for the new tab (a2 here) , tab selected event is thrown

2. Shift to currently focused tab in different window
Assume that tab a1 is selected in w1 and a2 is selected in w2. If you are now in a1 and then select a2 in w2. This one is a bit tricky to execute. It happens when you are able to see both windows (may be because w1 was not maximised) and you selected a2).
    w2 gets a window focus changed event

3. Shift to tab that is not currently focused in different window
Assume that tab a1 is selected in w1 and a2 is selected in w2. If you are now in a1 and then select a2 in w2. This one is also tricky to execute. It happens when you are able to see both windows (may be because w1 was not maximised) and you selected b2.
    w2 gets a window focus changed event
    b2 gets a tab selected event.
4. Switch to another Window
This happens when you do a alt+tab or when you select the window from the bottom panel. Assume w2 is the new window.
    w2 gets a window focus changed event

Tab and Window Closing Events

Assume that we two windows w1 and w2. w1 has tabs a1,b1,c1 . w2 has tabs a2,b2,c2 . Assume current window is w1 and current tab is c1.

1. Close Current Tab
    tab removed event for c1.
    tab selected event for b1.

2. Close Some other tab in same window without going to that tab
Suppose you are in c1 and you close a1 using the close button without going to tab a1. (Else it becomes scenario 1 ) .
    tab removed event for a1

3. Close last tab in window
Assume w1 has only one tab a1. And you close a1.
    Tab removed event for a1.
    Window focus changed event for w2.
    Window removed event for w1.

4. Close Window : Case 1
Assume w1 has a1,b1,c1. The tab with focus is a1.
    Tab removed event for c1.
    Tab removed event for b1.
    Tab removed event for a1.
    Window focus changed event for w2.
    Window removed event for w1.

5. Close Window : Case 2
Assume w1 has a1,b1,c1 in that order. The tab with focus is c1 (last tab).
    Tab removed event for c1.
    Tab selected event for b1.
    Tab removed event for b1.
    Tab selected event for a1.
    Tab removed event for a1.
    Window focus changed event for w2.
    Window removed event for w1.

6. Close Window : Case 3
Assume w1 has a1,b1,c1 in that order. The tab with focus is b1 (second tab).
    Tab removed event for c1.
    Tab removed event for b1.
    Tab selected event for a1.
    Tab removed event for a1.
    Window focus changed event for w2.
    Window removed event for w1.

 

Source Code

If you want to test these event transitions or want a sample extension to play around , you can download a simple extension here.

References

1) Google’s Chrome Extension Getting Started Guide
    Gives a step by step explanation of how to get started and also a comprehensive set of APIs/
2) Chrome API Guide
    Has a fairly comprehensive set of APIs and its documentation.

 

Add to DeliciousAdd to DiggAdd to FaceBookAdd to Google BookmarkAdd to RedditAdd to StumbleUponAdd to TechnoratiAdd to Twitter

If you liked this post , please subscribe to the RSS feed.

Read Full Post »

I use Google Chrome as my default browser. So when I started getting errors saying "Your profile could not be opened correctly" , it was quite annoying. I tried lot of fixes on my own and nothing seemed to work. I checked the forums and most of the solutions were to basically create a new profile which was not acceptable to me.

I had quite a bit of idle time today and hence decided to find the root cause. One of the main reasons for my anxiety was the nagging doubt that this might be due to my recent Chrome Extension – Chrome Nanny (for more details see Chrome Nanny – A Leech Block like Extension for Chrome ). It turned out that my extension was innocent but in the process , I found the root cause !

The cause of this issue seems straightforward – Some file or database is corrupted. I tried opening all SQLite databases and they all worked correctly. Most of the other files (esp which had JSON data) too seemed fine to me. The remaining was some data files and I had no way to find how to verify their integrity.

I was able to finally solve the issue. I had few solutions which should work. I had listed all of them – so use the one which works for you.

Method 1 : Check if there is any zombie processes

This is probably the most common scenario. If you get an error “Your profile could not be opened” , close all Chrome windows. Now check using ps if there is any chrome process still alive. A simple ps –aux | grep –i chrome or ps –aux | grep –i chromium should do.  If there is any processes still alive kill them (use kill, pkill or killall). Make sure all chrome processes are dead and start Chrome again. If the error does not come again, great ! Else follow the other steps.

If you are in Windows, then use the task explorer to kill all chrome processes.

Method 2 : Removing Web Data file

Try this method first as this was the issue in my system. Google Chrome has a file called "Web Data" which stores lot of info in it – including your passwords (wink wink). In my case this file was corrupted. I deleted this file and all worked well.

If you are in Linux , you can find the "Web Data" file at ~/.config/google-chrome/Default (if you are using Chrome) or at ~/.config/chromium/Default (if you are using Chromium). If you are in Windows (atleast in Windows 7), the file is at C:\Users\<username>\AppData\Local\Google\Chrome\User Data\Default\ . Delete the file and restart Chrome. Hopefully everything should work well. Of course, you will lose all your stored passwords and the search engines.

Method 3 : Check if any of the SQLite databases is locked

Chrome uses SQLite to store lot of information. Some times, the database might be locked and Chrome might not be able to access it. In this case, follow Kyron’s script in this Chrome forum.

Basically what he does is this : he dumps the SQLite database data into an SQL file, deletes the database , recreates it using the SQL file. This script should work if you are in Linux. (I think it should work for Mac too). His script is written for Chromium. If you are using Google Chrome, change the folder ~/.config/chromium/Default/ to ~/.config/google-chrome/Default/ .

Method 4 : Creating a new profile with most of the data from old profile

This method is very similar to the previous methods where instead of removing "Web Data", it tries to create a new profile with most of the useful data from old profile copied in to it. The steps are :

    a) Rename the Default folder at ~/.config/google-chrome/Default or ~/.config/chromium/Default to say backup. For Windows, the folder is at C:\Users\<username>\AppData\Local\Google\Chrome\User Data\Default\
    b) create a new folder with name "Default"
    c) copy the files/folders given below from original Default folder (currently named as backup) to the new Default folder one by one . After each step, try opening Chrome to see if the error comes. If an error comes, then the latest object you copied caused the issue.

    Preferences file
    Bookmarks file
    Extensions folder (contains all your extension’s source code)
    Local Storage folder : copy only files beginning with "chrome-extension_"  (other files are most likely not needed )
    History* (all your history )   

 

Again note that you will get a profile that is very close to the previous profile but it will not have the old stored passwords or the custom search engines you had.

Hope this post helped to solve a nagging issue !

[Update 12 May 2010] : Added more scenarios.

 

Add to DeliciousAdd to DiggAdd to FaceBookAdd to Google BookmarkAdd to RedditAdd to StumbleUponAdd to TechnoratiAdd to Twitter

If you liked this post , please subscribe to the RSS feed.

Read Full Post »

1. India’s EVMs are Vulnerable to Fraud
Interesting demo of how India’s EVM are vulnerable to fraud. Some of the points they make are quite valid. Although, I doubt if any politician has enough brains to even ask a techie to do this. I thought for some time about potential fixes for this issue but I don’t think there is any reliable way to completely avoid fraud. Going back to paper based voting or EVM with paper ballot is not an option especially for a country has as large as India. Link from Schneier.

2. How Wired.com Tracked the iPhone Finder
Nice article. Given the wide spread use of social networks , there are no more places to hide.

3. Video: Major Facebook security hole lets you view your friends’ live chats
A real scoop by Facebook. I saw the post too late to verify it. Glitches like these are quite scary and undermine the trust.

4. Pedal to the Chrome metal: Our fastest beta to date for Windows, Mac and Linux
I have been using Chrome 5 Beta for quite some time and its awesome ! It has some very neat features for extension developers like remembering unpacked extensions,audit tab etc. The post also has a video of various unconventional experiments showing how fast Chrome is. It proves that Google for atleast to some extent is still a different kind of a company.

5. Chrome Nanny – A Leech Block like Extension for Chrome
Shameless plug 🙂 I developed a Chrome extension which does some of the tasks of Leech Block for Firefox. Do try it out ! I also want to take the opportunity to express my gratitude to Suresh, Lokesh, Ashok (who also suggested the name !), Kripa, Divya and Arvi who helped me to test the extension and gave useful suggestions. You guys just rock !

 

Add to DeliciousAdd to DiggAdd to FaceBookAdd to Google BookmarkAdd to RedditAdd to StumbleUponAdd to TechnoratiAdd to Twitter

 

If you liked this post , please subscribe to the RSS feed.

Read Full Post »

[Update Oct 12 2018] : Thank you  for using Chrome Nanny. It is not available in the app store. It uses an old version of the Chrome extension API/manifest. Unfortunately, I do not have time to update it. Please consider other alternative extensions. Thanks!

[Update Nov 15 2011] : Chrome Nanny is now Nanny for Google Chrome. It also has a new home. The link to Google Chrome extension gallery ishttps://chrome.google.com/webstore/detail/cljcgchbnolheggdgaeclffeagnnmhno . Please spread the word !

Leech Block is one of my favorite Firefox extensions. When I made the switch to Google Chrome, the lack of Leech Block like Chrome extension was annoying. In one of my old blog post Two Chrome Extensions I wish Chrome had !! , I had mentioned that the two extensions I miss were Leech Block and one which can track my browsing habits.

I waited for quite some time for some one to make a Chrome extension and then decided to write it myself. Google has a good API documentation and tutorial – so coding was not that hard. In the process, I learned lot of interesting stuff – and my admiration for Chrome has only increased.

What Is Chrome Nanny

Chrome Nanny is a Leech Block like extension for Chrome. It allows you to say don’t allow me to go to a particular site during the time you specify. You can also limit the maximum time that you spend on a site. This means, that you can say you do not want to be allowed to go to facebook.com from 9-5. Even better, you can say don’t allow me to spend more than 1 hour during the time facebook is not blocked (12 AM -9AM, 5 PM – 12 AM). This is probably , the most common way Chrome Nanny will be used. Also you will also not be allowed to edit or delete a blocked URL during the time it is blocked.

If you want to check out the extension, please try it out at Chrome Nanny‘s Google extension gallery. If you want to read the instructions and its features, check out Instructions at Chrome Nanny – A Leech Block like extension for Chrome.

If you try to access a site during the time when it is blocked or after your daily quota is over, you will not be allowed to visit it. By default, Chrome Nanny will close the tab. If you like, you can also redirect the tab to  go to some motivational site. For eg, I make my Chrome Nanny redirect to ocw.mit.edu. Whenever I see that ocean of knowledge, I get a guilty feeling and start to work again 😉

I also added a feature to track the time I spend on some sites I commonly visit – digg, nytimes, hacker news etc. These are the sites, which I do not want to block , but I want to know how much time I spend on them. In Chrome Nanny, these sites are called White Listed Sites. You can add a site and the system will silently start tracking the time you spent on those sites.

Tags are another of my favorite feature. You can create tags to group URLs. For eg facebook and myspace may be in social networks, google reader and technorati in blogs etc. A tag contain multiple URLs and a URL can have multiple tags. Tags are most useful when you chart the time spent on each broad activity (like blogs, news, work etc ).

Chrome Nanny also has a basic charting system. It can provide three charts : Blocked Urls, White Listed Urls and Tags. Each of these can be drawn as a bar or pie chart.

Chrome does not have any easy way to determine if the Chrome tab/window is minimized. This means that it is hard to know that the user is not at the desk. For that, I have an maximum inactive time in General Options. For eg , if it is set to 5 minutes , and there is no activity in Chrome for 5 minutes, then Chrome Nanny stops tracking. In fact , it even gives back the 5 minutes !

If you want to know how much time left in your quota , you can always click on the Chrome Nanny’s icon to see the URLs blocked and allowed now. If an URL is allowed , then it also shows how much time left today too !

Comparison with Stay Focusd and Rescue Time

I noticed that there are two extensions that have functionality similar to Chrome Nanny. One is Stay Focusd and other is Rescue Time. Both are fine extensions. You may want to select the most appropriate extension based on your needs.

Stay Focusd has a single block time for a whole day and all the blocked URLs share this limit. In Chrome Nanny , each blocked URL has individual block time and max limits. In Leech Block parlance, all the Stay Focusd URLs form a single block set while in Chrome Nanny each URL is its own block set.

Chrome Nanny can do the job of Rescue Time partly too ! If you add the urls you want to track in White Listed URLs, then Chrome Nanny will count how much time you spent on each of them. Rescue Time on the other hand tries to track and analyze any url that you visit.

Acknowledgements

I had used jqplot  for charting. It is an excellent charting system and was very flexible. The icon for Chrome Nanny is obtained from the icon set of Smashing Magazine .

Also a special shout out to Suresh, Lokesh, Ashok (who also suggested the name !), Kripa, Divya and Arvi who helped me to test the extension and gave useful suggestions. Thanks a lot guys !

Do check out Chrome Nanny and tell me your opinion !

Add to DeliciousAdd to DiggAdd to FaceBookAdd to Google BookmarkAdd to RedditAdd to StumbleUponAdd to TechnoratiAdd to Twitter

If you liked this post , please subscribe to the RSS feed.

Read Full Post »

[Update Oct 12 2018] : Thank you  for using Chrome Nanny. It is not available in the app store. It uses an old version of the Chrome extension API/manifest. Unfortunately, I do not have time to update it. Please consider other alternative extensions. Thanks!

[Update Nov 15 2011] : Chrome Nanny is now Nanny for Google Chrome. It also has a new home. The link to Google Chrome extension gallery ishttps://chrome.google.com/webstore/detail/cljcgchbnolheggdgaeclffeagnnmhno . Please spread the word !

Prelude :

I have written a Chrome extension which kinda does some very basic stuff that Leech Block does for Firefox. I also have added some more features (like tags, charts) to Chrome Nanny that makes it more usable IMHO. If you are interested in checking it out, check the Chrome Nanny’s entry in Google Chrome extension gallery.

When I published the extension , the site asked for a web page with instructions for the extension . Even though , I had included instructions in options page of the extension, it makes sense to have  the instructions in a website too . Hence this post !

[Update]

1. The features that are planned to implemented are listed at the page Chrome Nanny Road Map .

2. This post will be updated as and when new versions of Chrome Nanny are released.

I have put the most commonly asked questions in the FAQ.  Please take a look at the FAQ and the comments to see if your issue is addressed. If not please feel free to comment on the post or Chrome Nanny’s extension page.

FAQ

I have added some FAQs based on the comments in the blog post. I will keep them updated as the comments evolve.

1. How do I block a URL (eg : http://www.facebook.com)  for a specific period of time ?

Lets say you want to block facebook between 9AM-5PM. Go to Chrome Nanny’s Options page and select Blocked List tab. Enter facebook.com in the URL. Convert time to be blocked to hhmm format in military time. It becomes 0900-1700. If there are multiple times, then append them with commas. Eg 0900-1200,1300-1700.  Select the days on which facebook has to be blocked. Click “Save URL”.

2. How do I limit accessing facebook to 1 hour a day ?

Suppose you want to access facebook all day but want to limit it to 1 hour at the most in a day. Go to Chrome Nanny’s Options page and select Blocked List tab. Enter facebook.com in the URL.  Enter 0000-0000 in the Blocked Time. Enter 60 in the “Max Time In a Day”. Click “Save URL”.

3. How do I block a url for specific interval but also want to limit the time spent on it in a day ?

This is achieved by a combination of 1 and 2. Lets say you want to block facebook between 9AM-5PM. In the remaining time you want to limit your browsing to 1 hour. To do that, enter facebook.com in the blocked URL , block time as 0900-1700, max time in a day as 60.

4. How do I block all .org sites except wikipedia ?

This can be done using regexp. In the block url , enter .*.org as the url. Enter the appropriate block times and save the blockset. Now go to “White List” tab and enter “wikipedia.org” as white listed url. Chrome Nanny will block all .org sites except wikipedia.

5. Is http, https, www needed ?

No. They are really not needed and Chrome Nanny internally strips them when doing the matching. So facebook.com will block facebook and there is no need to enter the full URL as http://www.facebook.com .

6. Chrome Nanny Crashed my Chrome

Open Chrome Nanny’s options page. In the “General Options” tab,  check the value of “Mode of Blocking”. If it is remove (default) then Chrome Nanny will close the tab if you try to access a blocked URL or if your daily quota is up. If there is a single tab in the window, it might look Chrome has crashed. It has not.

7. Chrome Nanny closed my tab

Chrome Nanny’s default mode of blocking is to remove the offending tab. If you want to redirect to some motivational web page, you can certainly do so. Open Chrome Nanny’s options page. In the “General Options” tab,  select “Redirect” as the value for “Mode of Blocking”. Enter the redirect url. Note that you cannot redirect to a URL that is blocked.

8. Chrome Nanny did not block my page

There are multiple possible reasons for this scenario.

Case 1: Check if the settings are correct. Is Chrome Nanny disabled ? Are you in Incognito mode ? Obvious, but it does not hurt to say again. Should this URL should be blocked now ? You can click on Chrome Nanny’s popup icon to get more details on which URLs are blocked now.

Case 2 : Is the blocked URL a substring of the tab’s current URL ? For eg having facebook.com will block http://www.facebook.com/home.php , http://www.facebook.com/settings.php and so on. For some websites, the URL with which we access may not be the final URL.  Eg reader.google.com may not work. Enter blocked url as google.com/reader. Enter mail.google.com instead of gmail.com and login.live.com instead of hotmail.com and so on.

Case 3 : Check if blocked list and white list URLs clash.

White listed URLs take precedence and if a URL matches white list and block list then it is allowed. A sample scenario is to block Google reader but allow all other google pages. To do this entering google.com/reader in blocked list is enough. If you add google.com in white list , then Google Reader is also allowed as it matches the white listed URL “google.com” .

Case 4 : Check if any of your blocked or white listed URLs using regular expressions (eg using “*” in the URL). If so, validate it in “Validate Regular Expressions” tab. Note that an error in any of the regexp URLs can cause Chrome Nanny to not block other URLs.

Case 5 : Click on Chrome Nanny’s popup icon (the one that looks like a clock). Check if the URL is blocked now. If it is , then Chrome Nanny will block the URL sooner or later. Chrome Nanny uses callback functions of Chrome’s events to perform the blocking. If they are not called , Chrome Nanny might not block the tab immediately .

Don’t worry : Chrome Nanny has other checks too ! It checks all the tabs every minute and blocks tabs if necessary. Also if you switch to another tab or refresh the tab , the tab is checked again. So if Chrome Nanny does not block it immediately then give it some time. If the tab is not blocked even after one minute (Although, Chrome Nanny’s popup says otherwise) then please check the troubleshooting section to see how to contact the developer about the error.

9. Chrome Nanny blocked my page before the deadline is up !
Chrome Nanny has a feature which allows you to specify total time you can spend on all blocked URLs in a day. Suppose you set it to 60 minutes. Then if the total time you have spent on all blocked URLs exceed 60 minutes, then all blocked URLs will be blocked immediately, even though individual URLs may have some more time left. ie This feature overrides the individual URL settings. To disable this feature , set Maximum Allowed minutes in a day for Blocked URLs to 0 in General Options tab.

10. Can I block a subdomain or a specific url ?

Sure. For eg, if you want to block Google Reader alone (but not other google pages) enter google.com/reader in the blocked list. This will allow all Google pages but will block Google Reader.

11. Can I block certain patterns of URLs ?
A sample scenario is this : I want to block all Google searches for games but other queries are ok. Yes, you can do it by having a blocked URL as “google.com/search.*games” .

12. Some examples for regular expressions

Please note that you need to use “.*” whenever you want to use “*” in the regular expression. (Eg .*.wordpress.com instead of *.wordpress.com )

a) google.*
Matches google.com , google.co.in, google.com/reader , picasaweb.google.com
Does not match any URL that does not have the word google in it.

b) http://www.google.*/reader
Note : Chrome Nanny internally strips http,https and www. So this regexp is equivalent to google.*/reader
Matches http://www.google.com/reader/view
Does not match google.com, google.co.in, picasaweb.google.com, reader.google.com

c) *.wordpress.com
Does not match anything. Worse yet, it can prevent validtion of other blocked URLs. If you verify this URL , you get an error “Invalid regular expression: /*.wordpress.com/: Nothing to repeat”. This is because , the “*” operation needs some character to repeat and when you dont give any, it errors out.

d) .*.wordpress.com
Correct way to block all wordpress.com blogs. Here the “.*” matches any characters that come before the domain and hence it will block all of them. If you want to allow say, “saravananthirumuruganathan.wordpress.com” but block other wordpress blogs, then create a “.*wordpress.com” blocked URL and make “saravananthirumuruganathan.wordpress.com” as a whitelisted URL.

e) test

This will match any URL that contains the word test. For eg test.com, blahtest.com, foo.com/test , bar.com/g.php?val=test etc.

13. I do not want the Challenge that occurs when I try to edit/delete a blockset when it is blocked !
The 64 character (default) challenge that Chrome Nanny raises when you try to edit/delete a blockset when it is currently blocked is one of the few hurdles in your way before you start whiling away your time ! I do understand there are many “legal” scenarios like experimenting with Chrome Nanny when challenge is an annoyance. So use the following feature only when needed. Go to General Options and then Length Of Challenge Text . Reduce the length 0. To prevent abuse, Chrome Nanny will ask for challenge once. If the length is changed to 0, then further changes do result in a challenge. Once you are done with the playing around, please do increase the challenge text length.

14. I do not want the blocked URLs to be displayed in the popup !
By default, Chrome Nanny will show the URLs currently blocked, how much time left in other blocked URLs and other details. If you do not want it to be displayed in the icon popup, go to Options , click ‘General Options’ tab, and select ‘No’ for the field ‘Show blocked URLs in popup ?’ . After this, when you click on the Chrome Nanny icon, it will display a bland message instead of the blocked URL details.

15. I think I have found a new bug ! Or How do I troubleshoot Chrome Nanny ?

I have tested Chrome Nanny extensively but bugs do creep up. Please check if you can reproduce the error consistently. If so, please point out the bug and the steps to reproduce in any of the following ways : comment at Chrome Nanny’s extension page OR comment in Chrome Nanny’s instructions blog post OR email the developer at saravanan DOT thirumuruganathan AT gmail DOT com .

It would be great if you can email the settings of Chrome Nanny also. Easiest way is to email the file chrome-extension_gpdgmmdbbbchchonpfanphofpplhmcmn_0.localstorage at ~/.config/google-chrome/Default/Local Storage (If using Linux and Chrome) or ~/.config/google-chrome/Default/Local Storage (using Linux and Chromium) or at C:\Users\\AppData\Local\Google\Chrome\User Data\Default\Local Storage (In Windows) .

Optionally you can also give me the logs when the bug occurs. To get Chrome Nanny’s logs , click on the Wrench icon – Select Extensions. Go to Chrome Nanny and click on “background.html” . This will open Chrome’s developer tools. Now try reproducing the bug and copy the log it generates. This will be very helpful for additional debugging.

16. I have a patch for feature X . How do I send it to you ?

It is wonderful that you took time to write a patch. Please send an email to saravananDOTthirumuruganathanATgmailDOTcom with the patch details and the file. I will test it and apply it to the extension. The latest code of Chrome Nanny will can be downloaded from the repository here . If you need additional help on the code please take a look at my post “How to Read the Source Code of Chrome and Firefox Extensions” .

Instructions

First of all, Thanks for using Chrome Nanny !

Chrome Nanny is a Chrome extension which can keep your browsing habits in check. Do you spend more time on facebook than on work ? Do you spend time more time in Google Reader or Digg and later wish you had not spent as much time ? Do you want to know how much you spent on Flick ? If so , Chrome Nanny is for you. Using Chrome Nanny, you can limit yourself from going to some sites on pre determined times or limit the time you spend on some sites. If you do not want to block a site, but want to know how much time you spend there, Chrome Nanny can do that for you too ! If you have used Leech Block for Firefox , you can recognize that Chrome Nanny does something similar but with a twist.

Note : If you are in Google Chrome version 5 or more , then enable this extension to run in Incognito mode too! Chrome Nanny will not like it if you visit blocked sites in Incognito mode. Will she ?

General Options

Mode Of Blocking decides what to do if you are visiting a website during blocked hours or after exhausting all the time you allocated yourself for the site. The default option is to remove the tab which may not be ideal for you. If you want the tab to be redirected to some motivational sites then you can select the redirect option and give a redirect url. You can specify a web page or a local html page (using file:// prefix) . Note that if you have only one tab, mode of block is”remove” and the url is blocked now, the entire window will be closed.

Stop Timer after Chrome is inactive for x minutes – Chrome does not notify when you minimize a Window/Tab. Chrome Nanny does not want you to lose the minutes you were not at the desk. You can enter some number in this field. For eg, if you are not active for 5 minutes, then Chrome Nanny will stop tracking the minutes till you come back.

Maximum Allowed minutes in a day for Blocked URLs – Use this field if you want to set a single limit to the time you spend on Blocked URLs. This value will override the individual Blocked URL limits. As an example , lets say you added facebook.com to Blocked URL list and set Max Time In a day as 60 minutes. If you now set, Maximum Allowed minutes in a day for Blocked URLs as 30 minutes, then facebook.com will not be accessible after 30 minutes . The same holds when you have multiple Blocked URLs. If the sum of time spent on all the URLs exceed this field, then all Blocked URLs will be blocked.

Length Of Challenge Text  – This determines the length of the Challenge text that Chrome Nanny will ask if you  try to edit/delete a blockset when it is  currently blocked. Reducing this field will also decrease the length of the challenge text. This field was added because in “some” scenarios (eg when playing with Chrome Nanny) , Challenges are an annoyance. Please use this field with discretion. To make changing this field a little hard to use, when you reduce the length of the Challenge, Chrome Nanny will perform a Challenge. So if you try to reduce a 64 character challenge  to 32 character, you will be challenged with a 64 character random string before being allowed to change it. Making the length as 0, removes all challenges.

Tags

Tags are a way to aggregate individual URL statistics. For eg you may spend lot of time on nytimes.com and Google news. If you want to aggregate the results into a “news” tag, then you can use the Tags tab for it. An url can belong to multiple tags.

Blocked URLs

Do you think, you spend too much time on Facebook ? This is the tab where you can use to limit your visits.

Block Set Name : Chrome Nanny allows you to group multiple URLs into a block set. Enter a name that you think summarizes the list of URLs. Eg News, Social Networks, Blogs etc.

URLs : Add the websites in this block set here. You need not add a full site url. So facebook.com will be enough. No need to add the whole “http://www.facebook.com”. Note that the url must be the “final” URL of the page that you want to be blocked. This means that gmail.com is better written as mail.google.com , reader.google.com is better written as google.com/reader and so on. You can add as many URLs you want in the text area. Separate them by newline (Enter key). ie a.com enter b.com blocks both a.com and b.com.

Add Tag : If you add any tags in the Tags tab, then you will see those tags here. You can add any number of tags for the url here. Just select the tag and keep clicking “Add Tag”. A URL can have multiple tags.

Block Time : This is the most important information. This decides when the url should be blocked. So if you want it to be blocked from 9 AM to 5 PM, then you encode it as 0900-1700. This is nothing but expressing start and end time as hhmm-hhmm in the 24 hour format. You can add multiple time blocks by separating them by comma. So to block between 9AM-5PM and 7PM-9PM, you write 0900-1700,1900-2100. Note that during the time a URL is blocked, you will not be able to edit or delete the URL.

Max Time : This an optional field. If you want to limit the time you spend on a site during your allowed time, then this field is useful. For eg, taking the example above, if you want to block between 9AM-5PM but you want to limit your browsing to 1 hour in the allowed time (12 AM-8:59 AM , 5:01 PM-11:59 PM) then you enter 0900-1700 in Block Time and 60 in the Max Time In A Day.
Apply On Days : Chrome Nanny understands that you may want to relax on weekends. So if you want your strict rules to apply only on weekdays, uncheck the weekends here.

This field also allows you to specify the block time in a granular level. For eg, you can set yourself to be allowed to browse the site for a maximum of 10 minutes each hour. To do that, set max time as 10 and in the drop down select for every “1 hour’”.

Note that you can edit or delete all the URLs any time when it is not blocked.

Lock Down

Lock down tab allows you to go into a focus mode by blocking some web pages for next “n” minutes. To do that, select the list of blocksets and then set the time to lock down. Note that once a lock down is active, you cannot edit or delete the blockset. Additionally, there is no way to cancel a lockdown too.

The lockdown information is visible in popup and also in the ‘Lockdown Information’ block.

White Listed URLs

If you do not want to block a URL but want to find how much time you spend each day, then use the White Listed URLs tab. Any URL added here is not blocked, but will be tracked and can be charted.
URL : Enter the URL of the site you want to be tracked. Again, you can enter just the domain name to track any page in the site.
Add Tag : As with Blocked URLs , you can add tags to White Listed URLs too !

Statistics

If you want to visualize how you spent your days with respect to the URLs you entered in Chrome Nanny, then this is the tab for you. You can enter the date range and Chrome Nanny will give you four charts. One each for Blocked URLs, Block Sets, White Listed URLs and tags. You can select between Bar Chart and Pie Chart !.

Validate Regular Expression

If you are going to use a regular expression in the URL, then you can use this tab to validate it. A bad regexp can cause syntax error in the code and *might* cause Chrome Nanny not to block other URLs.

Validating a Regular Expression : Enter your regexp in “Regular Expression for URL” and click “Test Regular Expression”. Check the field “RegExp Error”. If there is any error in regexp, it will be displayed here.
Verify if an URL is blocked : Enter the regexp in “Regular Expression for URL” . Enter URL to be tested in “Test URL”. Click “Test Regular Expression”. Check the fields “RegExp Error” and “Match”.

Add to DeliciousAdd to DiggAdd to FaceBookAdd to Google BookmarkAdd to RedditAdd to StumbleUponAdd to TechnoratiAdd to Twitter

If you liked this post , please subscribe to the RSS feed.

Read Full Post »

I am writing a Chrome extension (more on that next week !) and so far the experience has been excellent. Google has a decent set of API and has a good tutorial to get you started on developing extensions. But other than that I did not find many good resources in net for developing Chrome extensions. So I used the old way of reading the code of other good Chrome extensions to learn the ropes. Since the extension I write emulates a Firefox extension, I had to read some code of Firefox extensions too !

So in this post, I will talk about how to go about reading the code of Chrome/Firefox extensions and experimenting with them. I intend to write a more detailed post of developing/debugging Chrome extensions once I finish my extension.

A Word Of Caution

1) It is quite easy to mess with the extension’s application logic or its internal data structures. So be a little cautious when you are playing with the extension internals.
2) Also when you read the code, you might be tempted to reuse some of them. Just cross check with the extension’s license. Most of them have fairly liberal licenses. But it does not hurt to verify.

I will talk about Chrome extensions first and later will discuss the Firefox extensions.

Getting the Chrome Extension Id

One of the first things to know before playing with the extension is the extension id. There are two ways to know the id of an extension.

If the extension is installed in your computer, then you can get the id from the Extensions menu. Click on the wrench icon and select Extensions. In the Extensions page, each extension will be listed with some details like its name, description, version and most importantly an id. The id is a strange looking string with around 32 characters. For eg hoildcfdkjkefngkheffkiepkdcfdiok .

If you have not installed the extension, you can get the extension id by going to the extension’s page in the official Chrome extensions page . The extension id corresponds to the xxxx in the sample url – https://chrome.google.com/extensions/detail/xxxx.

Reading the Chrome Extension Source Code

I have two OSes in my system (Ubuntu and Windows 7). So I will explain the process for these two OS. But I am sure the process for other OS will be very similar.

In my Ubuntu system, for an extension with id say xxxx, the source code is located at ~/.config/google-chrome/Default/Extensions/xxxx . In this case Default is the name of my profile. If you have a different profile, substitute it. This is the root folder and it has child folder with the name of the version. Once you go in, you can see the extension code . Have fun !

In Windows 7, you can see the extension source folder at "C:\Users\<username>\AppData\Local\Google\Chrome\User Data\Default\Extensions\xxxx" . Again replace username with your login name, Default with your profile name if you use alternate profile.

Some times, you do not want to install an extension to read the source code. In this case, all you need to do is to download the crx file. At Google’s office Chrome extension page, to download the crx file , go to the extension’s details page (which is of the format https://chrome.google.com/extensions/detail/extensionid ) . Right click on the "Install" button and select "Save Link As". You will get a crx file. Now all you need to do is to use unzip command to extract the contents. If you are in Windows , any extraction software that can extract zip files will do. It might whine about some missing headers. Ignore it. You will get the extension code in the extracted folder.

Playing with Chrome Extension’s Local Storage

One of the coolest feature in HTML 5 is Local Storage which allows to store application info in a hash like data structure (which is usually internally a SQLite database). Most of the extensions use it extensively. So you can learn a lot about their internals by exploring what they store in the local storage. Note that Local Storage usually contains information that are critical to the proper execution of the extension and tampering it is not a good idea !

In Ubuntu, you can take a look at the extension’s local storage file at "~/.config/google-chrome/Default/Local Storage". In Windows 7, you can look at the file at "C:\Users\<username>\AppData\Local\Google\Chrome\User Data\Default\Local Storage". The local storage is nothing but a SQLite file and will have a name like "chrome-extension_xxxx_num.localstorage" where xxxx is the extension id and num is a number (usually 0).

The contents are stored in a table called "ItemTable". You will need a SQLite program to view its contents. I think, if you are in Lucid Lynx (Ubuntu 10.04) , you will already have it in the system (sqlite3) . Else you can install it via update manager. I am not sure what is the best program to view SQLite databases in Windows.

If you do not want to dirty your hand with command line tools , then check out instructions later at the section "Playing with Live Chrome Extensions" .

Playing with Chrome Extension’s Web Databases

HTML 5 also allows an extension to have arbitrarily structured databases. Currently I see only SQLite databases. For my extension, I really wanted to use databases instead of the local storage but I did not find enough good references on using Web databases. Also the problem of migrating one database version structure to another was a nightmare. So I did not invest much time in exploring databases. Again, I think very few extensions use Web Databases (None of the ones I sampled used it !).

In Ubuntu, you can see the database file at ~/.config/google-chrome/Default/databases . In Windows 7, you can see it at C:\Users\<username>\AppData\Local\Google\Chrome\User Data\Default\databases. As above, this is a SQLite file and you can explore it using a SQLite database browser.

Other Stuff

As you have noticed, the folder ~/.config/google-chrome/Default (In Ubuntu) and C:\Users\<username>\AppData\Local\Google\Chrome\User Data\Default\ (in Windows 7) have lot of good stuff. Play around the files. But be cautious as fooling around can cause the extension to malfunction and at worst, crash of Google Chrome.

Playing with Live Chrome Extensions

Chrome’s Developer Tools is a delight. It packs lot of very nifty functions. I will talk more about it in future. If you want to know all about a Chrome extension (especially Js files and local storage) without much pain, Developer tools is the way to go.

Go to the extensions menu (Wrench icon -> Extensions). Lets say you want to dig into extension xxxx. Go to the xxxx’s section in that page. You can see that there is a line "Inspect active views:" . And it usually lists "background.html" (or something similar like bg.html) . If you are viewing some other html file of the extension (say options.html, help.html etc) , then you will see them here too. But you should be able to see background.html (or some background file) always. Click on the link "background.html".

It should open Chrome’s Developer Tools which has many tabs. "Elements" tab has the page’s html content. "Scripts" tab displays all the js file included by the background file. You can read/view all the js file by clicking on the drop down or by using the left/right button. It also has a decent javascript debugger.

My favorite tab is however "Storage". It shows all the extension’s internal stuff like its local storage, web databases (if available), sessions and cookies. So if you want to view the local storage contents without using SQLite program, this is your (GUI) way. It will show all the keys and values. It even allows you to edit/delete the storage !

The last tab is "Console". Most of the extensions typically put lot of log info. So you can take a look at the console and get valuable information about the execution trace. Another thing that you can do is call the internal (JS) functions of the extension. The commands you type run in the context of the extension/page. Its a great way to tinker with the extension. I refrain from giving any direct example but it is trivial to experiment if you had some basic stuff with Firebug or something similar.

The other tabs are very useful but needs a lot more space to explain. But if your aim is to know the internals , then the tabs I mentioned are more than enough.

Reading Firefox Extensions

I did not dig much into Firefox extensions so this section will be brief. In the case of Firefox , getting the extension id is a bit tricky. So I primarily depended on grep to find the information. Most of the extension code will be at "~/.mozilla/firefox/<profile>/extensions/" (In Ubuntu). Most extensions have strange names although some popular ones have their named folder (eg ubiquity is under ‘ubiquity@labs.mozilla.com’. Ditto for foxmarks, listit, moonlight etc). Firefox extensions are also written primarily in Javascript although for UI you need to use XUL.

Misc Stuff – Dealing with Obfuscation

Some times you can see that the code is obfuscated. Some time the intent is to minify the file, some times it is not ! It may even be encoded using some simple scheme like base64. If you find that the code you want to read is unreadble, go to some JS beautifier site. My favorite is JS Beautifier . It is excellent, very flexible with lot of options and can even handle various packers.

Resources

There are lot of good resources available in net.

1. Google Chrome Extensions Tutorial
This page has a pretty good tutorial and a good API documentation . Their page on debugging had lot of useful information .

2. SQLite
If you are a command line person like me, you will want to read about SQLite to browse local storage or databases content. SQLite allows most basic SQL commands although the other commands are non standard (eg .tables, .schema etc) . Check out their docs.

3. Local Storage and Web Databases
These are HTML 5 features and resources can be found in many places in the internet.

 

Add to DeliciousAdd to DiggAdd to FaceBookAdd to Google BookmarkAdd to RedditAdd to StumbleUponAdd to TechnoratiAdd to Twitter

 

If you liked this post , please subscribe to the RSS feed.

Read Full Post »

« Newer Posts - Older Posts »