Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept calls to console.log in Chrome

I have a script that I can't change that makes a lot of console.log calls. I want to add another layer and respond if the calls contain certain strings. This works in Firefox, but throws an "Illegal invocation" error in Chrome on the 4th line:

var oldConsole = {}; oldConsole.log = console.log; console.log = function (arg) {     oldConsole.log('MY CONSOLE!!');     oldConsole.log(arg); } 

Any ideas how to get around that? I also tried cloning the console...

like image 990
sprugman Avatar asked Feb 09 '12 18:02

sprugman


People also ask

Where does console log go in Chrome?

Console Logs in Chrome: In Google Chrome, the Console Logs are available as a part of Chrome Dev Tools. To open the dedicated Console panel, either: Press Ctrl + Shift + J (Windows / Linux) or Cmd + Opt + J (Mac).

How do I use the console log in browser?

Steps to Open the Console Log in Google Chrome With the Chrome browser open, right-click anywhere in the browser window and select Inspect from the pop-up menu. By default, the Inspect will open the "Elements" tab in the Developer Tools. Click on the "Console" tab which is to the right of "Elements".

What does console log () do?

console. log specifically is a method for developers to write code to inconspicuously inform the developers what the code is doing. It can be used to alert you that there's an issue, but shouldn't take the place of an interactive debugger when it comes time to debug the code.

How do you call a console log in HTML?

press the F12 key on your keyboard.


1 Answers

You need to call console.log in the context of console for chrome:

(function () {   var log = console.log;   console.log = function () {     log.call(this, 'My Console!!!');     log.apply(this, Array.prototype.slice.call(arguments));   }; }()); 

Modern language features can significantly simplify this snippet:

{   const log = console.log.bind(console)   console.log = (...args) => {     log('My Console!!!')     log(...args)   } } 
like image 88
zzzzBov Avatar answered Sep 28 '22 12:09

zzzzBov