Usage of window. onerror in Javascript

Source: Internet
Author: User

Window. onerror can be thought of as a lot of useful things in js. Next I will introduce how to use window. onerror. If you need to know it, please do not go to the reference.


The onerror syntax uses three input parameters by default:

• Msg: error message
• Url: The file where the error is located
• Line: the code line of the error, which is an integer.
123 window. onerror = function (msg, url, line) {// some code };
For the form of <body onerror = "some code">, you can obtain parameters in sequence through arguments [0], arguments [1], and arguments [2.

Basic Features
You can set returnValue = true or directly return true to prevent the browser from displaying error messages. However, the debugging box popped up by script debuggers is not blocked.

Onerror is triggered only when a running error occurs, and a syntax error is not triggered.

The following three methods can cause onerror:

• Runtime errors, such as invalid object references or security restrictions
• Download error, slice
• Failure to obtain multimedia data in IE9 may also cause
<Script> the tag does not support onerror.

The onerror attribute defined on the <body> label is equivalent to window. onerror (supported by Firefox, Opera, and no response from IE9 and chrome ).

Browser compatibility
Supported onError by browsers listed in QuirksMode:

• Chrome 13 +
• Firefox 6.1 +
• Internet Explorer 5.5 +
• Safari 5.1 +
• Opera 11.61 + (the QuirksMode test is not supported until 11.51, And the 11.61 on hand is supported)
In addition to window objects, onerror elements are supported:

• full support
• <Script> IE9/IE10/safari 5.1 +/chrome 13 + support
<Css> and <iframe> do not support onerror.

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

"Script error.", "", 0

For example, http://www.bKjia. c0m, introduced http:// B .com/g.js, if g.js errors, the final information transmitted to zookeeper onerrorwill be altered.

The reason why the browser does this is to consider two features:

• <Script> attackers can execute third-party js files in different origins.
• The <script> element ignores the MIME type of the loaded file and runs as a script.
In the attack scenario, the Javascript file of a normal page is introduced to a malicious page, and the js file is automatically executed. if an exception is triggered, an error message may leak some sensitive data. This information will eventually be processed by window. onerror on the malicious page.

Tested, browsers with this feature (the latest version) include Firefox, Chrome, Safari, and Opera.

Adam Barth (work on the security of the Chrome browser at Google) Recommended solution is to use CORS (Cross-Origin Resource Sharing ).

In short, when <script> introduces an external js file in the page, add a crossorigin attribute (similar to the CROS attribute of ). When the server receives the request, it adds an authorization field to the HTTP Header (the value can be a specific domain name ):

Access-Control-Allow-Origin :*

The browser detects that this js has authorized the Domain Name of the page, so it does not need to tamper with the error message sent from this js to window. onerror.

After testing, this solution has not been implemented by the browser.
It is supported in later versions of Chrome and Firefox.

When an error does not trigger an onerror
However, if you manually try and catch this error and do not continue to throw it, this error will not trigger onerror.

 

For example:


Try {sdflkjwef} catch (e) {... // The error is not returned}

This error will not trigger the onerror event.

Try {sdflkjwef} catch (e) {... throw e ;}

If you continue to throw this error, the onerror event will be triggered.

 
Blocking error in IE

In the callback method of onerror, if the returned value is true, the exclamation point in the lower left corner of the browser can be avoided in IE, and the error collection continues.

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

The three parameters of the onerror function are used to determine the exact information of the error, which means: Error information, file with an error, and row number with an error.

Example:

The Code is as follows: Copy code
<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>

The method in the preceding example is worth learning. When capturing js errors, we usually use the try {} catch (e) {} method, and then obtain the error information through e. errorMessage and other methods, and then report the error. However, the onerror event may be rarely used. Have we considered how to report the row number of the error? If you have thought about whether this problem is also plagued by this problem, do you think it is impossible to capture the wrong row number in js? In fact, I encountered the above problems. I read a piece of js code written by someone today and suddenly found the onerror event. I 'd like to say that the onerror time was also known n long ago, however, I have never understood the three parameters and their special properties. After my own research and testing, I have a new understanding of the onerror event. When there is no error on the page, the window. onerror event does not exist, that is, null (nonsense! If onerror occurs, is it normal ?) We generally pass the operation function to be executed to the onerror event through the function name transfer method (reference method), such as window. onerror = reportError; window. onerror = function () {alert ('error')}, but we may not know that the event is triggered with three default parameters, which are error messages, the url and line number of the error page. You need to know that this event is like an onclick event or an onmouseover event, but it has parameters. We can test it like this.

The Code is as follows: Copy code
<Script type = "text/javascript">
Window. onerror = testError;
Function testError (){
Arglen = arguments. length;
Var errorMsg = "number of parameters:" + arglen + ";
For (var I = 0; I <arglen; I ++ ){
ErrorMsg + = "/n parameter" + (I + 1) + ":" + arguments [I];
}
Alert (errorMsg );
Window. onerror = null;
Return true;
}
Function test (){
Error
}
Test ()
</Script>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.