- Error handling in JavaScript walkthrough
- DOM onevent handlers
- Регистрация обработчиков onevent
- Non-element objects
- HTML onevent attributes
- JavaScript
- Result
- Event handler’s parameters, this binding, and the return value
- When the event handler is invoked
- Terminology
- Specifications
- Browser compatibility
- Detecting the presence of event handler properties
- Window
- Constructors
- Properties
- Properties implemented from elsewhere
- Deprecated properties
- Methods
- Methods implemented from elsewhere
- Deprecated methods
- Event handlers
- Event handlers implemented from elsewhere
- Events
Error handling in JavaScript walkthrough
As of June 1, 2020, the Microsoft Ad Monetization platform for Windows UWP apps will be shut down. Learn more
This walkthrough demonstrates how to catch ad-related errors in your JavaScript app. This walkthrough uses an AdControl to display a banner ad, but the general concepts in it also apply to interstitial ads and native ads.
These examples assume that you have a JavaScript app that contains an AdControl. For step-by-step instructions that demonstrate how to add an AdControl to your app, see AdControl in HTML 5 and Javascript. For a complete sample project that demonstrates how to add banner ads to a JavaScript/HTML app, see the advertising samples on GitHub.
- In the default.html file, add a value for the onErrorOccurred event where you define the data-win-options in the div for the AdControl. Find the following code in the default.html file. Following the adUnitId attribute, add the value for the onErrorOccurred event.
Create a div that will display text so you can see the messages being generated. To do this, add the following code after the div for myAd.
Create an AdControl that will trigger an error event. There can only be one application id for all AdControl objects in an app. So creating an additional one with a different application id will trigger an error at runtime. To do this, after the previous div sections you have added, add the following code to the body of the default.html page.
In the project’s default.js file, after the default initialization function, you will add the event handler for errorLogger. Scroll to the end of the file and after the last semi-colon is where you will put the following code.
Build and run the file. You will see the original ad from the sample app you built previously and text under that ad describing the error. You will not see the ad with the id of liveAd.
DOM onevent handlers
Веб-платформа предоставляет несколько способов получения уведомлений о событиях DOM. Два общих подхода — это addEventListener () и конкретные обработчики onevent . Эта страница посвящена тому, как работают последние.
Регистрация обработчиков onevent
Обработчики onevent — это свойства определённых элементов DOM, позволяющие управлять тем, как этот элемент реагирует на события. Элементы могут быть интерактивными (ссылки, кнопки, изображения, формы и т. д.) или неинтерактивными (например, элемент base ). События — это такие действия, как:
- Клик мышкой
- Нажатие клавиш
- Получение фокуса
Обработчик on-event обычно называется с именем события, на которое он реагирует, например onclick , onkeypress , onfocus и т. д.
Вы можете указать обработчик событий on для конкретного события (например, click (en-US) ) для данного объекта различными способами:
- Добавление HTML элемента attribute с событием on :
, - Или установив соответствующий параметр property из JavaScript:
document.querySelector(«button»).onclick = function(event) .
Свойство обработчика событий onevent служит своего рода заполнителем, которому может быть назначен один обработчик событий. Чтобы разрешить установку нескольких обработчиков для одного и того же события на данном объекте, вы можете вызвать метод addEventListener () , который управляет списком обработчиков для данного события на объекте. Затем обработчик можно удалить из объекта, вызвав его функцию removeEventListener() .
Когда происходит событие, которое применяется к элементу, каждый из его обработчиков событий вызывается, чтобы позволить им обрабатывать это событие один за другим. Вам не нужно вызывать их самостоятельно, хотя вы можете сделать это во многих случаях, чтобы легко имитировать происходящее событие. Например, учитывая объект кнопки myButton , вы можете сделать myButton.onclick(myEventObject) для прямого вызова обработчика событий. Если обработчик событий не имеет доступа к каким-либо данным из объекта event, вы можете пропустить это событие при вызове функции onclick() .
This continues until every handler has been called, unless one of the event handlers explicitly halts the processing of the event by calling stopPropagation() on the event object itself.
Это продолжается до тех пор, пока не будет вызван каждый обработчик, если только один из обработчиков событий явно не остановит обработку события, вызвав stopPropagation () на самом объекте события.
Non-element objects
Event handlers can also be set with properties on non-element objects that generate events, like window , document , XMLHttpRequest , and others. For example, for the progress event on instances of XMLHttpRequest :
HTML onevent attributes
HTML elements have attributes named onevent which can be used to register a handler for an event directly within the HTML code. When the element is built from the HTML, the value of its onevent attributes are copied to the DOM object that represents the element, so that accessing the attributes’ values using JavaScript will get the value set in the HTML.
Further changes to the HTML attribute value can be done via the setAttribute method; Making changes to the JavaScript property will have no effect.
Given this HTML document:
JavaScript
Then this JavaScript demonstrates that the value of the HTML attribute is unaffected by changes to the JavaScript object’s property.
Result
For historical reasons, some attributes/properties on the and (en-US) elements instead set event handlers on their parent Window object. (The HTML specification names these: onblur , onerror , onfocus , onload , and onscroll .)
Event handler’s parameters, this binding, and the return value
When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters:
- event — for all event handlers except onerror .
- event , source , lineno , colno , and error for the onerror event handler. Note that the event parameter actually contains the error message as a string.
When the event handler is invoked, the this keyword inside the handler is set to the DOM element on which the handler is registered. For more details, see the this keyword documentation.
The return value from the handler determines if the event is canceled. The specific handling of the return value depends on the kind of event; for details, see «The event handler processing algorithm» in the HTML specification.
When the event handler is invoked
TBD (non-capturing listener)
Terminology
The term event handler may refer to:
- Any function or object that is registered to be notified of events
- Or more specifically, to the mechanism of registering event listeners via on… attributes in HTML or properties in Web APIs, such as or window.onload = function() < … >.
When discussing the various methods of listening to events:
- Event listener refers to a function or object registered via EventTarget.addEventListener()
- Event handler refers to a function registered via on… attributes or properties
Specifications
Specification | Status | Comment |
---|---|---|
HTML Living Standard Определение ‘event handlers’ в этой спецификации. | Живой стандарт | |
HTML5 Определение ‘event handlers’ в этой спецификации. | Рекомендация |
Browser compatibility
Detecting the presence of event handler properties
You can detect the presence of an event handler property with the JavaScript in operator. For example:
Window
The Window interface represents a window containing a DOM document; the document property points to the DOM document loaded in that window. A window for a given document can be obtained using the document.defaultView property.
A global variable, window , representing the window in which the script is running, is exposed to JavaScript code.
The Window interface is home to a variety of functions, namespaces, objects, and constructors which are not necessarily directly associated with the concept of a user interface window. However, the Window interface is a suitable place to include these items that need to be globally available. Many of these are documented in the JavaScript Reference and the DOM Reference.
In a tabbed browser, each tab is represented by its own Window object; the global window seen by JavaScript code running within a given tab always represents the tab in which the code is running. That said, even in a tabbed browser, some properties and methods still apply to the overall window that contains the tab, such as resizeTo() and innerHeight . Generally, anything that can’t reasonably pertain to a tab pertains to the window instead.
Constructors
DOMParser DOMParser can parse XML or HTML source stored in a string into a DOM Document. DOMParser is specified in DOM Parsing and Serialization. HTMLImageElement.Image Used for creating an HTMLImageElement . HTMLOptionElement.Option Used for creating an HTMLOptionElement . StaticRange This is an experimental API that should not be used in production code.
Read only Returns a StaticRange() constructor which creates a StaticRange object. Worker Used for creating a Web worker. XMLSerializer Converts a DOM tree into XML or HTML source.
Properties
This interface inherits properties from the EventTarget interface and implements properties from the WindowOrWorkerGlobalScope and WindowEventHandlers mixins.
Note that properties which are objects (e.g. for overriding the prototype of built-in elements) are listed in a separate section below.
Window.closed Read only This property indicates whether the current window is closed or not. Window.console Read only Returns a reference to the console object which provides access to the browser’s debugging console. Window.controllers Read only This API has not been standardized.
Returns the XUL controller objects for the current chrome window. Window.customElements Read only Returns a reference to the CustomElementRegistry object, which can be used to register new custom elements and get information about previously registered custom elements. Window.crypto Read only Returns the browser crypto object. Window.devicePixelRatio Read only Returns the ratio between physical pixels and device independent pixels in the current display. Window.document Read only Returns a reference to the document that the window contains. Window.DOMMatrix Read only This is an experimental API that should not be used in production code.
Returns a reference to a DOMMatrix object, which represents 4×4 matrices, suitable for 2D and 3D operations. Window.DOMMatrixReadOnly Read only This is an experimental API that should not be used in production code.
Returns a reference to a DOMMatrixReadOnly object, which represents 4×4 matrices, suitable for 2D and 3D operations. Window.DOMPoint Read only This is an experimental API that should not be used in production code.
Returns a reference to a DOMPoint object, which represents a 2D or 3D point in a coordinate system. Window.DOMPointReadOnly Read only This is an experimental API that should not be used in production code.
Returns a reference to a DOMPointReadOnly object, which represents a 2D or 3D point in a coordinate system. Window.DOMQuad Read only This is an experimental API that should not be used in production code.
Returns a reference to a DOMQuad object, which provides represents a quadrilaterial object, that is one having four corners and four sides. Window.DOMRect Read only This is an experimental API that should not be used in production code.
Returns a reference to a DOMRect object, which represents a rectangle. Window.DOMRectReadOnly Read only This is an experimental API that should not be used in production code.
Returns a reference to a DOMRectReadOnly object, which represents a rectangle. Window.event Read only Returns the current event, which is the event currently being handled by the JavaScript code’s context, or undefined if no event is currently being handled. The Event object passed directly to event handlers should be used instead whenever possible. Window.frameElement Read only Returns the element in which the window is embedded, or null if the window is not embedded. Window.frames Read only Returns an array of the subframes in the current window. Window.fullScreen This property indicates whether the window is displayed in full screen or not. Window.history Read only Returns a reference to the history object. Window.innerHeight Read only Gets the height of the content area of the browser window including, if rendered, the horizontal scrollbar. Window.innerWidth Read only Gets the width of the content area of the browser window including, if rendered, the vertical scrollbar. Window.isSecureContext This is an experimental API that should not be used in production code.
Read only Indicates whether a context is capable of using features that require secure contexts. Window.length Read only Returns the number of frames in the window. See also window.frames . Window.location Gets/sets the location, or current URL, of the window object. Window.locationbar Read only Returns the locationbar object, whose visibility can be toggled in the window. Window.localStorage Read only Returns a reference to the local storage object used to store data that may only be accessed by the origin that created it. Window.menubar Read only Returns the menubar object, whose visibility can be toggled in the window. Window.messageManager This API has not been standardized.
Returns the message manager object for this window. Window.mozInnerScreenX Read only This API has not been standardized.
Returns the horizontal (X) coordinate of the top-left corner of the window’s viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel in nsIDOMWindowUtils for a conversion factor to adapt to screen pixels if needed. Window.mozInnerScreenY Read only This API has not been standardized.
Returns the vertical (Y) coordinate of the top-left corner of the window’s viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel for a conversion factor to adapt to screen pixels if needed. Window.name Gets/sets the name of the window. Window.navigator Read only Returns a reference to the navigator object. Window.opener Returns a reference to the window that opened this current window. Window.outerHeight Read only Gets the height of the outside of the browser window. Window.outerWidth Read only Gets the width of the outside of the browser window. Window.pageXOffset Read only An alias for window.scrollX . Window.pageYOffset Read only An alias for window.scrollY Window.parent Read only Returns a reference to the parent of the current window or subframe. Window.performance Read only Returns a Performance object, which includes the timing and navigation attributes, each of which is an object providing performance-related data. See also Using Navigation Timing for additional information and examples. Window.personalbar Read only Returns the personalbar object, whose visibility can be toggled in the window. Window.screen Read only Returns a reference to the screen object associated with the window. Window.screenX and Window.screenLeft Read only Both properties return the horizontal distance from the left border of the user’s browser viewport to the left side of the screen. Window.screenY and Window.screenTop Read only Both properties return the vertical distance from the top border of the user’s browser viewport to the top side of the screen. Window.scrollbars Read only Returns the scrollbars object, whose visibility can be toggled in the window. Window.scrollMaxX This API has not been standardized.
Read only The maximum offset that the window can be scrolled to horizontally, that is the document width minus the viewport width. Window.scrollMaxY This API has not been standardized.
Read only The maximum offset that the window can be scrolled to vertically (i.e., the document height minus the viewport height). Window.scrollX Read only Returns the number of pixels that the document has already been scrolled horizontally. Window.scrollY Read only Returns the number of pixels that the document has already been scrolled vertically. Window.self Read only Returns an object reference to the window object itself. Window.sessionStorage Returns a reference to the session storage object used to store data that may only be accessed by the origin that created it. Window.sidebar This API has not been standardized.
Read only Returns a reference to the window object of the sidebar. Window.speechSynthesis Read only Returns a SpeechSynthesis object, which is the entry point into using Web Speech API speech synthesis functionality. Window.status Gets/sets the text in the statusbar at the bottom of the browser. Window.statusbar Read only Returns the statusbar object, whose visibility can be toggled in the window. Window.toolbar Read only Returns the toolbar object, whose visibility can be toggled in the window. Window.top Read only Returns a reference to the topmost window in the window hierarchy. This property is read only. Window.visualViewport Read only This is an experimental API that should not be used in production code.
Returns a VisualViewport object which represents the visual viewport for a given window. Window.window Read only Returns a reference to the current window. window[0] , window[1] , etc. Returns a reference to the window object in the frames. See Window.frames for more details.
Properties implemented from elsewhere
Deprecated properties
This deprecated API should no longer be used, but will probably still work.
Read only Returns a reference to the content element in the current window. Since Firefox 57 (initially Nightly-only), both versions are only available from chrome (privileged) code, and not available to the web anymore. Window.defaultStatus This deprecated API should no longer be used, but will probably still work.
Gets/sets the status bar text for the given window. Window.dialogArguments This deprecated API should no longer be used, but will probably still work.
Read only Gets the arguments passed to the window (if it’s a dialog box) at the time window.showModalDialog() was called. This is an nsIArray . Window.directories This deprecated API should no longer be used, but will probably still work.
Synonym of window.personalbar Window.globalStorage This API has not been standardized.
This deprecated API should no longer be used, but will probably still work.
Multiple storage objects that were used for storing data across multiple pages. Window.mozAnimationStartTime This API has not been standardized.
This deprecated API should no longer be used, but will probably still work.
The time in milliseconds since epoch at which the current animation cycle began. Use Animation.startTime instead. Window.mozPaintCount This API has not been standardized.
This deprecated API should no longer be used, but will probably still work.
Returns the number of times the current document has been rendered to the screen in this window. This can be used to compute rendering performance. Window.orientation Read only This deprecated API should no longer be used, but will probably still work.
Returns the orientation in degrees (in 90 degree increments) of the viewport relative to the device’s natural orientation. Window.pkcs11 This deprecated API should no longer be used, but will probably still work.
Formerly provided access to install and remove PKCS11 modules. Window.returnValue This deprecated API should no longer be used, but will probably still work.
The return value to be returned to the function that called window.showModalDialog() to display the window as a modal dialog.
Methods
This interface inherits methods from the EventTarget interface and implements methods from WindowOrWorkerGlobalScope and EventTarget .
Window.alert() Displays an alert dialog. Window.blur() Sets focus away from the window. Window.cancelAnimationFrame() This is an experimental API that should not be used in production code.
Enables you to cancel a callback previously scheduled with Window.requestAnimationFrame . Window.cancelIdleCallback() This is an experimental API that should not be used in production code.
Enables you to cancel a callback previously scheduled with Window.requestIdleCallback . Window.clearImmediate() Cancels the repeated execution set using setImmediate . Window.close() Closes the current window. Window.confirm() Displays a dialog with a message that the user needs to respond to. Window.dump() This API has not been standardized.
Writes a message to the console. Window.find() Searches for a given string in a window. Window.focus() Sets focus on the current window. Window.getComputedStyle() Gets computed style for the specified element. Computed style indicates the computed values of all CSS properties of the element. Window.getDefaultComputedStyle() This API has not been standardized.
Gets default computed style for the specified element, ignoring author stylesheets. Window.getSelection() Returns the selection object representing the selected item(s). Window.matchMedia() Returns a MediaQueryList object representing the specified media query string. Window.maximize() FIXME: NeedsContents Window.minimize() (top-level XUL windows only) Minimizes the window. Window.moveBy() Moves the current window by a specified amount. Window.moveTo() Moves the window to the specified coordinates. Window.open() Opens a new window. Window.postMessage() Provides a secure means for one window to send a string of data to another window, which need not be within the same domain as the first. Window.print() Opens the Print Dialog to print the current document. Window.prompt() Returns the text entered by the user in a prompt dialog. Window.requestAnimationFrame() Tells the browser that an animation is in progress, requesting that the browser schedule a repaint of the window for the next animation frame. Window.requestIdleCallback() This is an experimental API that should not be used in production code.
Enables the scheduling of tasks during a browser’s idle periods. Window.resizeBy() Resizes the current window by a certain amount. Window.resizeTo() Dynamically resizes window. Window.scroll() Scrolls the window to a particular place in the document. Window.scrollBy() Scrolls the document in the window by the given amount. Window.scrollByLines() This API has not been standardized.
Scrolls the document by the given number of lines. Window.scrollByPages() This API has not been standardized.
Scrolls the current document by the specified number of pages. Window.scrollTo() Scrolls to a particular set of coordinates in the document. Window.setImmediate() Executes a function after the browser has finished other heavy tasks Window.setResizable() This API has not been standardized.
Toggles a user’s ability to resize a window. Window.sizeToContent() This API has not been standardized.
Sizes the window according to its content. Window.showOpenFilePicker() Shows a file picker that allows a user to select a file or multiple files. Window.showSaveFilePicker() Shows a file picker that allows a user to save a file. Window.showDirectoryPicker() Displays a directory picker which allows the user to select a directory. Window.stop() This method stops window loading. Window.updateCommands() This API has not been standardized.
Updates the state of commands of the current chrome window (UI).
Methods implemented from elsewhere
Deprecated methods
This deprecated API should no longer be used, but will probably still work.
Moves back one in the window history. This method is deprecated; you should instead use window.history.back() . Window.captureEvents() This API has not been standardized.
This deprecated API should no longer be used, but will probably still work.
Registers the window to capture all events of the specified type. Window.forward() This API has not been standardized.
This deprecated API should no longer be used, but will probably still work.
Moves the window one document forward in the history. This method is deprecated; you should instead use window.history.forward() . Window.home() This API has not been standardized.
This deprecated API should no longer be used, but will probably still work.
Returns the browser to the home page. Window.openDialog() This API has not been standardized.
This deprecated API should no longer be used, but will probably still work.
Opens a new dialog window. Window.releaseEvents() This API has not been standardized.
This deprecated API should no longer be used, but will probably still work.
Releases the window from trapping events of a specific type. Window.showModalDialog() This API has not been standardized.
This deprecated API should no longer be used, but will probably still work.
Displays a modal dialog.
Event handlers
These are properties of the window object that can be set to establish event handlers for the various things that can happen in the window that might be of interest.
This interface inherits event handlers from the EventTarget interface and implements event handlers from WindowEventHandlers .
Window.onappinstalled Called when the page is installed as a webapp. See appinstalled event. Window.onbeforeinstallprompt An event handler property dispatched before a user is prompted to save a web site to a home screen on mobile. Window.ondevicelight An event handler property for any ambient light levels changes Window.ondevicemotion Called if accelerometer detects a change (For mobile devices) Window.ondeviceorientation Called when the orientation is changed (For mobile devices) Window.ondeviceorientationabsolute This API has not been standardized.
An event handler property for any device orientation changes. Window.ondeviceproximity An event handler property for device proximity event Window.ongamepadconnected Represents an event handler that will run when a gamepad is connected (when the gamepadconnected event fires). Window.ongamepaddisconnected Represents an event handler that will run when a gamepad is disconnected (when the gamepaddisconnected event fires). Window.onmozbeforepaint An event handler property for the MozBeforePaint event, which is sent before repainting the window if the event has been requested by a call to the window.requestAnimationFrame method. Window.onpaint An event handler property for paint events on the window. WindowEventHandlers.onrejectionhandled An event handler for handled Promise rejection events. Window.onuserproximity An event handler property for user proximity events. Window.onvrdisplayconnect Represents an event handler that will run when a compatible VR device has been connected to the computer (when the vrdisplayconnected event fires). Window.onvrdisplaydisconnect Represents an event handler that will run when a compatible VR device has been disconnected from the computer (when the vrdisplaydisconnected event fires). Window.onvrdisplayactivate Represents an event handler that will run when a display is able to be presented to (when the vrdisplayactivate event fires), for example if an HMD has been moved to bring it out of standby, or woken up by being put on. Window.onvrdisplaydeactivate Represents an event handler that will run when a display can no longer be presented to (when the vrdisplaydeactivate event fires), for example if an HMD has gone into standby or sleep mode due to a period of inactivity. Window.onvrdisplayblur Represents an event handler that will run when presentation to a display has been paused for some reason by the browser, OS, or VR hardware (when the vrdisplayblur event fires) — for example, while the user is interacting with a system menu or browser, to prevent tracking or loss of experience. Window.onvrdisplayfocus Represents an event handler that will run when presentation to a display has resumed after being blurred (when the vrdisplayfocus event fires). Window.onvrdisplaypresentchange represents an event handler that will run when the presenting state of a VR device changes — i.e. goes from presenting to not presenting, or vice versa (when the vrdisplaypresentchange event fires).
Event handlers implemented from elsewhere
An event handler for unhandled Promise rejection events. WindowEventHandlers.onunload Called when the user navigates away from the page.
Events
Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface.
error Fired when a resource failed to load, or can’t be used. For example, if a script has an execution error or an image can’t be found or is invalid.
Also available via the onerror property. languagechange Fired at the global scope object when the user’s preferred language changes.
Also available via the onlanguagechange property. orientationchange Fired when the orientation of the device has changed.
Also available via the onorientationchange property. devicemotion Fired at a regular interval, indicating the amount of physical force of acceleration the device is receiving and the rate of rotation, if available. deviceorientation Fired when fresh data is available from the magnetometer orientation sensor about the current orientation of the device as compared to the Earth coordinate frame. resize Fired when the window has been resized.
Also available via the onresize property. storage Fired when a storage area ( localStorage or sessionStorage ) has been modified in the context of another document.
Also available via the onstorage property.