Skip to content

Instantly share code, notes, and snippets.

@designbyadrian
Created August 18, 2014 14:41
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save designbyadrian/2eb329c853516cef618a to your computer and use it in GitHub Desktop.
Save designbyadrian/2eb329c853516cef618a to your computer and use it in GitHub Desktop.
Hijack console.log, console.warn, and console.error without breaking the default browser function.
var cl,ce,cw;
if(window.console && console.log){
cl = console.log;
console.log = function(){
MyLogFunction(arguments);
cl.apply(this, arguments)
}
}
if(window.console && console.warn){
cw = console.warn;
console.warn = function(){
MyWarnFunction(arguments);
cw.apply(this, arguments)
}
}
if(window.console && console.error){
ce = console.error;
console.error = function(){
MyErrorFunction(arguments);
ce.apply(this, arguments)
}
}
@adventurist
Copy link

adventurist commented Feb 23, 2018

awesome! Thanks for this

I tweaked and did something like this in ES6

`if (window.console && console) {

    for (let c in console) {

        if (typeof console[c] === 'function') {

            const cx = console[c]

            console[c] = function () {

                const betterArgs = massageArguments(arguments)

                cx.apply(this, [...betterArgs])

            }

        }

    }

}`

@taylorjdawson
Copy link

taylorjdawson commented Jul 12, 2019

if (window.console && console) {

    for (let c in console) {

        if (typeof console[c] === 'function') {

            const cx = console[c]

            console[c] = function () {

                const betterArgs = massageArguments(arguments)

                cx.apply(this, [...betterArgs])

            }

        }

    }

}

Same as above just easier copy and paste.

@leoplaw
Copy link

leoplaw commented May 21, 2021

What would the massageArguments look like? I'm trying to apply formatting to the console output.

@taylorjdawson
Copy link

The massageArguments method will get passed the arguments object and from there you can apply your formatting to each of the arguments that were originally passed to the console.<method>()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment