search
HomeWeb Front-endJS TutorialUsage and example analysis of window.onerror()_javascript skills

onerror syntax uses

onerror has three input parameters by default:

•msg: error message
•url: The file where the error is located
•line: The line of code where the error is located, integer
window.onerror = function(msg, url, line){ // some code };
For the form of

, parameters can be obtained through arguments[0], arguments[1], and arguments[2] in sequence.

What we most commonly use in js is js fault tolerance

window.onerror=function(){return true;}

Basic Features
You can prevent the browser from displaying error messages by setting returnValue=true or returning true directly. But it will not prevent the debugging box from popping up by script debuggers.
Onerror will only be triggered by runtime errors, not by syntax errors.

Onerror can be triggered in the following three ways:

• Runtime errors such as invalid object reference or security restriction
• Download errors such as pictures
•In IE9, failure to obtain multimedia data will also trigger
The <script> tag does not support onerror. </script>

The onerror attribute defined on the

tag is equivalent to window.onerror (tested, supported by Firefox and Opera, but unresponsive in IE9 and chrome).

Browser Compatibility

Support for onError in each browser listed by QuirksMode

•Chrome 13+
•Firefox 6.1+
•Internet Explorer 5.5+
•Safari 5.1+
•Opera 11.61+ (QuirksMode test 11.51 is not supported yet, the 11.61 I have on hand already supports it)
In addition to the window object, elements that support onerror:

Usage and example analysis of window.onerror()_javascript skills Full support
•<script> IE9/IE10/safari 5.1+/chrome 13+ supported<br /> <css> and <iframe> do not support onerror. </script>

Problems and Solutions

For errors in referencing external js files, Webkit and Mozilla browsers will tamper with the original error information, resulting in the last three input parameters obtained by onerror:

Copy code The code is as follows:

"Script error.","", 0

例如http://a.com/index.html,引入了http://b.com/g.js,如果g.js出错,最终传递到window.onerror的信息会被篡改。

浏览器之所以做这样的处理,是考虑到两个特性:

•<script> 能执行非同源下的第三方js文件。<br /> &#8226;<script> 元素会忽略加载的文件的MIME类型,而当作脚本来执行。<br /> 在攻击场景中,恶意页面引入了正常页面的js文件,js文件会自动执行,若发生异常触发的报错信息,可能会泄漏某些敏感数据。这些信息最终会被恶意页面的window.onerror处理。</script>

经测试,存在此特性的浏览器(当前最新版)有Firefox、Chrome、Safari、Opera。

Adam Barth(work on the security of the Chrome browser at Google)建议的解决方案是使用CORS (Cross-Origin Resource Sharing)。

简言之,当在页面中 <script> 引入外部js文件时,增加一个属性crossorigin(类似于<img alt="Usage and example analysis of window.onerror()_javascript skills" > 的CROS属性)。服务器在接受到请求时,在HTTP Header里增加一个授权字段(值可以是具体的某个域名):</script>

Access-Control-Allow-Origin: *

浏览器检测到此js已经授权此页面所在域名,则不用再篡改由此js传递到window.onerror的错误信息了。

经测试,此方案尚未被浏览器实现。
已经在Chrome、Firefox的较新版本中支持。

其他参考资料

Internet Explorer http://msdn.microsoft.com/en-us/library/cc197053.aspx

Mozilla Firefox https://developer.mozilla.org/en/DOM/window.onerror

Opera http://dev.opera.com/articles/view/better-error-handling-with-window-onerror/

Wiki http://www.w3.org/wiki/DOM/window.onerror

syntax errors and runtime errors http://www.htmlgoodies.com/primers/jsp/article.php/3610081/Javascript-Basics-Part-11.htm

window.下面是一些实例大家可以参考下:

onerror = function(sMessage,sUrl,sLine){};

onerror函数的三个参数用于确定错误确切的信息,代表的意思依次为:错误信息;发生错误的文件;发生错误的行号。

示例:

<SCRIPT>
window.onerror=fnErrorTrap;
function fnErrorTrap(sMsg,sUrl,sLine){
oErrorLog.innerHTML="<b>An error was thrown and caught.</b><p>";
oErrorLog.innerHTML+="Error: " + sMsg + "<br>";
oErrorLog.innerHTML+="Line: " + sLine + "<br>";
oErrorLog.innerHTML+="URL: " + sUrl + "<br>";
return false;
}
function fnThrow(){
eval(oErrorCode.value);
}
</SCRIPT>
<INPUT TYPE="text" ID=oErrorCode VALUE="someObject.someProperty=true;">
<INPUT TYPE="button" VALUE="Throw Error" onclick="fnThrow()">
<P>
<DIV ID="oErrorLog">
</DIV>

上面示例的方法很值得借鉴。
在捕获js错误时,我们通常使用try{}catch(e){}的方式,然后通过e.errorMessage等方式获取错误信息然后报告错误。但对于onerror事件可能很少问津,我们是否思考过如何报告错误所在的行号?如果想过这个是否也被这个问题所困扰过,是否认为在js里不可能捕获错误的行号呢?其实本人就遇到上述的几个问题,今日读某人写的一段js代码顿然发现了onerror事件,要说onerror这个时间也是n久以前就知道了,但对于其所带有的三个参数和其特殊性质却一直没有去了解过。经过自己的研究测试,对onerror事件有了一些新的认识和了解。在页面没有错误时,window.onerror事件是不存在的,也就是null(废话!没出错如果onerror出现还正常吗?)我们一般通过函数名传递的方式(引用的方式)将要执行的操作函数传递给onerror事件,如window.onerror=reportError;window.onerror=function(){alert('error')},但我们可能不知道该事件触发时还带有三个默认的参数,他们分别是错误信息,错误页面的url和错误行号。要知道这个可是事件,就如onclick和onmouseover等事件一样,但它是有参数。我们可以这样测试。

<script type="text/javascript">  
  window.onerror=testError;  
  function testError(){  
  arglen=arguments.length;  
  var errorMsg="参数个数:"+arglen+"个";  
  for(var i=0;i<arglen;i++){  
  errorMsg+="/n参数"+(i+1)+":"+arguments[i];  
}  
  alert(errorMsg);  
  window.onerror=null;  
  return true;  
}  
function test(){  
  error  
}  
test()  
</script> 

First bind the testError method to the onerror event, and then trigger an error in the test method. When executing in IE, we found the following prompt:
---------------------------- Microsoft Internet Explorer ------------------ -------
Number of parameters: 3
Parameter 1: 'error' undefined
Parameter 2: file://E:/yanwei/test/testError.html
Parameter 3: 14
--------------------------- Sure---------------------- -----
It can be found that the function testError captures three parameters when an error occurs. By binding the function to the onerror event, you can capture the above three parameters when the page fails.
The following problems were also found during the test:
1. By adding return true at the end of the function, the system error message (IE) will not pop up when an error occurs in the function.
2. If there are multiple errors on the page, only the first error will be captured and processed and then the execution of subsequent programs will be terminated.
3. The onerror event cannot capture all errors. It can only capture errors outside or within functions (?? What does this mean? It’s not a joke). For example, adasdf; function test(){ aaaa; } can capture errors that adasdf has not yet The defined error function test(){ aaaa; } can capture aaaa undefined errors, but errors in function test(){} or function test()dd{} cannot be captured and a system error message will pop up directly.
4. Onerror is executed in the same way in browsers such as IE and FF, and both contain these three parameters.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools