javascriptgoogle-chromeconsolecustomization

adding custom functionality into chrome's console


Is it possible to have custom functions in google-chrome that will be always available in console (no matter what page is loaded)? For instance, I would like to have a function called echo that would be just a wrapper around console.log. This just saves a bit of typing but later I might want to create some useful debug functionality.


Solution

  • Well it's pretty easy to accomplish. What you need is to create a content script. This script would be injected in any page and create some necessary global functions you would use in your console. The most challenging part is how to make those custom content scrtipt functions to be part of your actual window object, because normally you can't access functions or variables you define in your content script from the rest of the javascript code which is not within content script. Content scripts run in so-called isolated enviroment.

    Content scripts execute in a special environment called an isolated world. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page. It looks to each content script as if there is no other JavaScript executing on the page it is running on. The same is true in reverse: JavaScript running on the page cannot call any functions or access any variables defined by content scripts.

    But there are fancy workaround.
    You define your manifest file as follows:

    manifest.json

    {
        "name": "Content script",
        "version": "0.1",
        "manifest_version": 2,
        "content_scripts": [{
            "matches": ["http://*/*"],
            "js": ["console.js"]
        }]
    }
    

    And your content script:

    console.js

    function customConsole() {
        window.myNewFunction = function() {
            console.log("Hello I'm available from console.");
        };
    }
    
    var script = document.createElement('script'),
        code   = document.createTextNode('(' + customConsole + ')();');
    script.appendChild(code);
    (document.body || document.head || document.documentElement).appendChild(script);
    

    So you specify your new functions as global functions so that you could use them in console.
    Also take a look at this post