Detect a console.warn message

Viewed 4226

I have a need to find out when a warning (not error) message is sent to the browser's console.log . From research, I know that I can detect error messages with JavaScript code similar to this:

window.onerror = function(errorMsg, url, lineNumber){
    // any action you want goes here
    // errorMsg is the error message itself.
    // url should be the file presenting the error, though i have
    //    found that it only presents to me the address of the site.
    // lineNumber is the line number the error occoured on.
    // here is an example of what you could do with it:
    alert("Error in " + url + " at " + lineNumber + ":\n" + errorMsg);
}

But that only shows error messages. It will not show any warning messages.

Is there a similar way to detect a specific warning message in the console.log? Or, alternately, is there some JS code that will allow me to search the console.log for a specific string?

Note that I can see the warning message in the browser's debugging (console logging) window. But I want to 'intercept' the warning message and perform some action if that warning is found.

Added

The intent is to find out when a specific warning message occurs; the message being similar to "Loading failed for the <script> with source "https://www.example.com/js/somescript.js" .

But the question of how to intercept a warning message (not error; the code I included does that) that is output by the browser (not my code).

Added

So, here's what I need. Assume this code

console.warn("Here is a warning!");

What code would you write to see if that message was written to the console as a warning?

3 Answers

How about overriding the console.log()?

let tmpConsoleLog = console.log;
console.log = function(msg){
    // Intercept code goes here using msg variable
    alert(msg);
    // then perform the normal logging
    tmpConsoleLog(msg);
}

console.log("Something");

The warnings you are talking about are generated by the browser, not console.warn. This is why you cannot override it. Most likely, you need to manually add listeners for each event you need. For example, if you want to handle a script loading error use the onerror event:

<script src="https://www.example.com/js/somescript1.js" onerror="console.log('Cannot load script from ' + this.src)"></script>
<script src="https://www.example.com/js/somescript2.js" onerror="console.log('Cannot load script from ' + this.src)"></script>

It's very late, but here's an answer that actually directly answers your question.

var originalConsoleWarn = console.warn;
console.warn = function(message) {
  doSomethingWithWarn(message);
  originalConsoleWarn(message);
};

function doSomethingWithWarn(message){
  console.log("DOING SOMETHING WITH: " + message);
}

console.warn("hi");

Related