onerror 特性为 GlobalEventHandlers 混合 EventHandler 处理 error 事件。

Error events are fired at various targets for different kinds of errors:

  • JavaScript runtime error (including syntax errors and exceptions thrown within handlers) occurs, an error event using interface ErrorEvent is fired at window and window.onerror() is invoked (as well as handlers attached by window.addEventListener (not only capturing)).
  • When a resource (such as an <img> or <script> ) fails to load error event using interface 事件 is fired at the element that initiated the load, and the onerror() handler on the element is invoked. These error events do not bubble up to window, but (at least in Firefox) can be handled with a window.addEventListener configured with useCapture set to True.

Installing a global error event handler is useful for automated collection of error reports.

句法

For historical reasons, different arguments are passed to window.onerror and element.onerror handlers (as well as on error-type window.addEventListener handlers).

window.onerror

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

Function parameters:

  • message : error message (string). Available as event (sic!) in HTML onerror="" handler.
  • source : URL of the script where the error was raised (string)
  • lineno : Line number where error was raised (number)
  • colno : Column number for the line where the error occurred (number)
  • error : Error Object (object)

When the function returns true , this prevents the firing of the default event handler.

window.addEventListener('error')

window.addEventListener('error', function(event) { ... })
					

event 类型 ErrorEvent contains all the information about the event and the error.

element.onerror

element.onerror = function(event) { ... }
					

element.onerror accepts a function with a single argument of type 事件 .

A good example for this is when you are using an image tag, and need to specify a backup image in case the one you need is not available on the server for any reason.

<img src="imagenotfound.gif" onerror="this.onerror=null;this.src='imagefound.gif';" />
					

The reason we have the this.onerror=null in the function is that the browser will be stuck in an endless loop if the onerror image itself generates an error.

注意事项

When an error occurs in a script, loaded from a different origin , the details of the error are not reported to prevent leaking information (see bug 363897 ). Instead the error reported is simply "Script error." This behavior can be overriden in some browsers using the crossorigin attribute on <script> and having the server send the appropriate CORS HTTP response headers.  A workaround is to isolate "Script error." and handle it knowing that the error detail is only viewable in the browser console and not accessible via JavaScript.

window.onerror = function (msg, url, lineNo, columnNo, error) {
  var string = msg.toLowerCase();
  var substring = "script error";
  if (string.indexOf(substring) > -1){
    alert('Script Error: See Browser Console for Detail');
  } else {
    var message = [
      'Message: ' + msg,
      'URL: ' + url,
      'Line: ' + lineNo,
      'Column: ' + columnNo,
      'Error object: ' + JSON.stringify(error)
    ].join(' - ');
    alert(message);
  }
  return false;
};
					

When using the inline HTML markup ( <body onerror="alert('an error occurred')"> ), the HTML specification requires arguments passed to onerror to be named event , source , lineno , colno , error . In browsers that have not implemented this requirement, they can still be obtained via arguments[0] 透过 arguments[2] .

规范

规范 状态 注释
HTML 实时标准
The definition of 'onerror' in that specification.
实时标准

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
onerror Chrome 10 Edge 12 Firefox 1 IE 9 Opera 11.6 Safari 6 WebView Android ≤37 Chrome Android 18 Firefox Android 4 Opera Android 12 Safari iOS 6 Samsung Internet Android 1.0

图例

完整支持

完整支持

另请参阅

元数据

  • 最后修改:
  1. GlobalEventHandlers
  2. 特性
    1. onabort
    2. onanimationcancel
    3. onanimationend
    4. onanimationiteration
    5. onauxclick
    6. onblur
    7. oncancel
    8. oncanplay
    9. oncanplaythrough
    10. onchange
    11. onclick
    12. onclose
    13. oncontextmenu
    14. oncuechange
    15. ondblclick
    16. ondurationchange
    17. onended
    18. onerror
    19. onfocus
    20. onformdata
    21. ongotpointercapture
    22. oninput
    23. oninvalid
    24. onkeydown
    25. onkeypress
    26. onkeyup
    27. onload
    28. onloadeddata
    29. onloadedmetadata
    30. onloadend
    31. onloadstart
    32. onlostpointercapture
    33. onmousedown
    34. onmouseenter
    35. onmouseleave
    36. onmousemove
    37. onmouseout
    38. onmouseover
    39. onmouseup
    40. onpause
    41. onplay
    42. onplaying
    43. onpointercancel
    44. onpointerdown
    45. onpointerenter
    46. onpointerleave
    47. onpointermove
    48. onpointerout
    49. onpointerover
    50. onpointerup
    51. onreset
    52. onresize
    53. onscroll
    54. onselect
    55. onselectionchange
    56. onselectstart
    57. onsubmit
    58. ontouchcancel
    59. ontouchstart
    60. ontransitioncancel
    61. ontransitionend
    62. onwheel
  3. 实现通过:
    1. Document
    2. HTMLElement
    3. SVGElement
    4. Window
    5. XULElement
  4. HTML DOM 相关页面
    1. BeforeUnloadEvent
    2. DOMStringMap
    3. ErrorEvent
    4. HTMLAnchorElement
    5. HTMLAreaElement
    6. HTMLAudioElement
    7. HTMLBRElement
    8. HTMLBaseElement
    9. HTMLBaseFontElement
    10. HTMLBodyElement
    11. HTMLButtonElement
    12. HTMLCanvasElement
    13. HTMLContentElement
    14. HTMLDListElement
    15. HTMLDataElement
    16. HTMLDataListElement
    17. HTMLDialogElement
    18. HTMLDivElement
    19. HTMLDocument
    20. HTMLElement
    21. HTMLEmbedElement
    22. HTMLFieldSetElement
    23. HTMLFormControlsCollection
    24. HTMLFormElement
    25. HTMLFrameSetElement
    26. HTMLHRElement
    27. HTMLHeadElement
    28. HTMLHeadingElement
    29. HTMLHtmlElement
    30. HTMLIFrameElement
    31. HTMLImageElement
    32. HTMLInputElement
    33. HTMLIsIndexElement
    34. HTMLKeygenElement
    35. HTMLLIElement
    36. HTMLLabelElement
    37. HTMLLegendElement
    38. HTMLLinkElement
    39. HTMLMapElement
    40. HTMLMediaElement
    41. HTMLMetaElement
    42. HTMLMeterElement
    43. HTMLModElement
    44. HTMLOListElement
    45. HTMLObjectElement
    46. HTMLOptGroupElement
    47. HTMLOptionElement
    48. HTMLOptionsCollection
    49. HTMLOutputElement
    50. HTMLParagraphElement
    51. HTMLParamElement
    52. HTMLPictureElement
    53. HTMLPreElement
    54. HTMLProgressElement
    55. HTMLQuoteElement
    56. HTMLScriptElement
    57. HTMLSelectElement
    58. HTMLShadowElement
    59. HTMLSourceElement
    60. HTMLSpanElement
    61. HTMLStyleElement
    62. HTMLTableCaptionElement
    63. HTMLTableCellElement
    64. HTMLTableColElement
    65. HTMLTableDataCellElement
    66. HTMLTableElement
    67. HTMLTableHeaderCellElement
    68. HTMLTableRowElement
    69. HTMLTableSectionElement
    70. HTMLTemplateElement
    71. HTMLTextAreaElement
    72. HTMLTimeElement
    73. HTMLTitleElement
    74. HTMLTrackElement
    75. HTMLUListElement
    76. HTMLUnknownElement
    77. HTMLVideoElement
    78. HashChangeEvent
    79. 历史
    80. ImageData
    81. 定位
    82. MessageChannel
    83. MessageEvent
    84. MessagePort
    85. Navigator
    86. NavigatorGeolocation
    87. NavigatorID
    88. NavigatorLanguage
    89. NavigatorOnLine
    90. NavigatorPlugins
    91. PageTransitionEvent
    92. Plugin
    93. PluginArray
    94. PopStateEvent
    95. PortCollection
    96. PromiseRejectionEvent
    97. RadioNodeList
    98. Transferable
    99. ValidityState
    100. Window
    101. WindowBase64
    102. WindowEventHandlers
    103. WindowTimers