Check out "Do you speak JavaScript?" - my latest video course on advanced JavaScript.
Language APIs, Popular Concepts, Design Patterns, Advanced Techniques In the Browser

Chrome extension: debugging dev tools tab or how to make console.log

It's really interesting to work on an extension for Chrome. However, sometimes it's a little bit difficult to debug. Especially when you work on a dev tools add-on (i.e. a new tab).

As you may guess

console.log

doesn't work in the code of your new dev tools tab. Instead of that I used alert. If the thing which you want to see is something primitive, it's easy. Just pass it to alert function. If not you can use

alert(JSON.stringify(obj));

Anyway, using alert is not the coolest thing, mainly because you have to comment those lines or manually remove them. Also, it's a little bit irritating from user experience point of view. What I did is to send a message to the background page. That's in one of my dev tools scripts:

// console.log in the background page
var bglog = function(obj) {
    if(chrome && chrome.runtime) {
        chrome.runtime.sendMessage({type: "bglog", obj: obj});
    }
}

Then in the background page:

var onMessageListener = function(message, sender, sendResponse) {
    switch(message.type) {
        case "bglog":
            console.log(message.obj);
        break;
    }
    return true;
}
chrome.runtime.onMessage.addListener(onMessageListener);

Really simple, but the background script could be easily inspected. Open chrome://extensions, find your extension and you will see:

Inspect views: _generated_background_page.html

Click on that link and a new dev tools will be opened. The console there accepts logs from the background script.

If you enjoy this post, share it on Twitter, Facebook or LinkedIn.