Run custom functions in the browser console

Asked

Viewed 1,335 times

5

It’s a little tiring having to keep writing console.log() all the time. I know that in my code I can define the function log that does just that. But outside the app environment, I would like to always have this available in the browser, being that just open the console Ctrl + Alt + I and type log('alou').

For example, the extension Nice Alert Chrome completely replaces the alert() Javascript. My intention is not to replace standard functions, but to do something similar?

1 answer

2


What Nice Alert does is basically:

var w = window;
if (!w.alert.is_nice) {
    w.alert = function alert(msg) {/*etc*}
}

Here is a solution like browser extension and Userscript. An extension has more permissions and runs everywhere. Used as Userscript works on many websites, but not others (like Github), but I don’t know exactly why.


To make a custom extension in Chrome or Opera, these would be the files:

manifest.json

{
    "name": "(SOPT) Console functions",
    "manifest_version": 2,
    "version": "0.1",
    "content_scripts": [{
        "matches": ["http://*/*","https://*/*"],
        "js": ["console.js"],
        "run_at": "document_start"
    }]
}

console.js

Attention to the use of the object arguments that the functions receive.

function main() {
    var w = window;
    if (!w.log) {
        w.log = function log() {
            for( var i=0; i<arguments.length;i++)
            console.log( arguments[i] );
        }
    }
}

if (!document.xmlVersion) {
    var script = document.createElement('script');
    script.appendChild(document.createTextNode('('+ main +')();'));
    document.documentElement.appendChild(script);
}

You can also use a Usercript running in Chrome and Firefox, just paste the following header followed by the code console.js above:

// ==UserScript==
// @name       (SOPT) Console functions
// @namespace  userscripts.pt.stackoverflow.com
// @version    0.1
// @match      http*://*/*
// ==/UserScript==

Upshot:

log personalizado

References:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.