redirect Javascript syntax errors and console.log to somewhere else

早过忘川 提交于 2021-01-27 13:26:53

问题


I'm trying to send whatever would normally appear in the javascript console to my own custom functions.

I've tried the following

window.console.error = window.console.debug =  window.console.log
window.console.log=mylog;

function mylog(msg){
    //send it somewhere just using alert as an example
      alert("log="+msg);    
}
console.log("yo");
var x=y;//a syntax error

Using the code above I only see the following alert "yo"

In the console log I see "x is not defined"
How do I redirect the syntax errors?


回答1:


You can use onerror it is designed to catch syntax errors.

window.onerror = function(message, source, lineno, colno, error) {
   alert(message);
}

Offical docs on MDN




回答2:


Here's a thread on this. Note the answer that shows how to "hijack" console.log() and send it wherever you want: Capturing javascript console.log?



来源:https://stackoverflow.com/questions/35759269/redirect-javascript-syntax-errors-and-console-log-to-somewhere-else

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!