小编Jen*_*ita的帖子

如何发送控制台消息和错误以提醒?

我想将错误传递给警报,以警告用户他们在代码中犯了错误,即使他们没有打开控制台.

    var doc=(frame.contentWindow.document || obj.contentDocument|| obj.contentWindow);
    var head = doc.getElementsByTagName('head')[0];
    var scriptElement = doc.createElement('script');
    scriptElement.setAttribute('type', 'text/javascript');
    scriptElement.text = scripts;

    try{
        head.appendChild(scriptElement);
    }
     catch(e){ alert("error:"+e.message +"  linenumber:"+e.lineNumber);}
Run Code Online (Sandbox Code Playgroud)

当脚本包含错误时,appendChild会抛出错误.它直接进入控制台,我希望它显示在警报中,因为它适用于孩子,他们可能不会检查控制台.try catch块不会捕获错误.我用eval(脚本)试了一下.

   try{
   eval(scripts);} catch(e){ alert("error:"+e.message +"  linenumber:"+e.lineNumber);}
Run Code Online (Sandbox Code Playgroud)

这确实有效,但这意味着代码执行了两次,这在某些情况下非常不方便.

我试过猴子修补console.error:

       console.log=function(){alert("taking over the log");}
       console.error=function(){alert("taking over the log");}
Run Code Online (Sandbox Code Playgroud)

但这只有在我真正使用console.error时才有效.不是在抛出实际错误时.如果不是console.error,在真正的错误情况下,什么函数将错误发送到控制台?我可以访问并更改它吗?有任何想法吗?帮助将非常感激.谢谢Jenita

javascript alert exception console.log

12
推荐指数
1
解决办法
1万
查看次数

标签 统计

alert ×1

console.log ×1

exception ×1

javascript ×1