mercredi 2 novembre 2011

console.log Cannot call method 'log' of null

In this post I'll tell you how a simple console.log in my Chrome extension took me 3 hours to figure out why it was throwing the following error:
Uncaught TypeError: Cannot call method 'log' of null
logcommon.js:130
(anonymous function)database.js:68
common.js:130

The short story is that the console.log was inside a database callback function that was called while I was moving to another page.

The long story is :

- The user open the extension popup, and try to log in.
- If login was successful we store in the database his login and status and move the user to the protected content, in our case it is the sms sending page.
if(user.connected){
  database.transaction(function(tx) {
    console.log("Going to persist user with login : "+user.login + " and status " + user.status) ;
    tx.executeSql('INSERT INTO USER (LOGIN,STATUS) VALUES (?, ?)',
                  [user.login, user.status],
                  function(){
                    //because of the window.location below this line will suck
                    console.log("insert ok"); //doesn't work 
                   //Uncaught TypeError: Cannot call method 'log' of null
                  },
                  function(){
                   console.log("insert ko");
                  }); 
   }
  //culprit
  window.location = 'send-sms.html';
}

If we comment the window.location line, the console.log("insert ok") works.

So the bottom line is: Delegate callback work and in general any long-running script to the background page:

chrome.extension.getBackgroundPage().do_Heavy_Work();

Let's go back adding more good stuff into smshare ;)