value consists of a sequence of one or more filter functions or references to SVG filters. The input to the filter is used as the input to the first item in the list. Subsequent items take the output of the previous item as their input. [FILTERS] Coordinates used in the value of the filter attribute are interpreted such that one pixel is equivalent to one SVG user space unit and to one canvas coordinate space unit. Filter coordinates are not affected by the current transformation matrix . The current transformation matrix affects only the input to the filter. Filters are applied in the output bitmap 's coordinate space. When the value of the filter attribute defines lengths using percentages or using 'em' or 'ex' units, these must be interpreted relative to the computed value of the 'font-size' property of the font style source object at the time that the attribute is set, if it is an element. If the computed values are undefined for a particular case (e.g. because the font style source object is not an element or is not being rendered ), then the relative keywords must be interpreted relative to the default value of the font attribute. The 'larger' and 'smaller' keywords are not supported. If the value of the filter attribute refers to an SVG filter in the same document, and this SVG filter changes, then the changed filter is used for the next draw operation. If the value of the filter attribute refers to an SVG filter in an external resource document and that document is not loaded when a drawing operation is invoked, then the drawing operation must proceed with no filtering. 4.12.5.1.20 Working with externally-defined SVG filters This section is non-normative. Since drawing is performed using filter value 'none' until an externally-defined filter has finished loading, authors might wish to determine whether such a filter has finished loading before proceeding with a drawing operation. One way to accomplish this is to load the externally-defined filter elsewhere within the same page in some element that sends a load event (for example, an SVG use element), and wait for the load event to be dispatched. 4.12.5.1.21 Drawing model When a shape or image is painted, user agents must follow these steps, in the order given (or act as if they do): Render the shape or image onto an infinite transparent black bitmap, creating image , as described in the previous sections. For shapes, the current fill, stroke, and line styles must be honored, and the stroke must itself also be subjected to the current transformation matrix. When the filter attribute is set to a value other than 'none' and all the externally-defined filters it references, if any, are in documents that are currently loaded, then use image as the input to the filter , creating image . Otherwise, let be an alias for When shadows are drawn , render the shadow from image using the current shadow styles, creating image When shadows are drawn , multiply the alpha component of every pixel in by globalAlpha When shadows are drawn , composite within the clipping region over the current output bitmap using the current composition operator Multiply the alpha component of every pixel in by globalAlpha Composite within the clipping region over the current output bitmap using the current composition operator When compositing onto the output bitmap , pixels that would fall outside of the output bitmap must be discarded. 4.12.5.1.22 Best practices When a canvas is interactive, authors should include focusable elements in the element's fallback content corresponding to each focusable part of the canvas, as in the example above When rendering focus rings, to ensure that focus rings have the appearance of native focus rings, authors should use the drawFocusIfNeeded() method, passing it the element for which a ring is being drawn. This method only draws the focus ring if the element is focused , so that it can simply be called whenever drawing the element, without checking whether the element is focused or not first. In addition to drawing focus rings, authors should use the scrollPathIntoView() method when an element in the canvas is focused, to make sure it is visible on the screen (if applicable). Authors should avoid implementing text editing controls using the canvas element. Doing so has a large number of disadvantages: Mouse placement of the caret has to be reimplemented. Keyboard movement of the caret has to be reimplemented (possibly across lines, for multiline text input). Scrolling of the text control has to be implemented (horizontally for long lines, vertically for multiline input). Native features such as copy-and-paste have to be reimplemented. Native features such as spell-checking have to be reimplemented. Native features such as drag-and-drop have to be reimplemented. Native features such as page-wide text search have to be reimplemented. Native features specific to the user, for example custom text services, have to be reimplemented. This is close to impossible since each user might have different services installed, and there is an unbounded set of possible such services. Bidirectional text editing has to be reimplemented. For multiline text editing, line wrapping has to be implemented for all relevant languages. Text selection has to be reimplemented. Dragging of bidirectional text selections has to be reimplemented. Platform-native keyboard shortcuts have to be reimplemented. Platform-native input method editors (IMEs) have to be reimplemented. Undo and redo functionality has to be reimplemented. Accessibility features such as magnification following the caret or selection have to be reimplemented. This is a huge amount of work, and authors are most strongly encouraged to avoid doing any of it by instead using the input element, the textarea element, or the contenteditable attribute. 4.12.5.1.23 Examples This section is non-normative. Here is an example of a script that uses canvas to draw pretty glowing lines canvas width "800" height "450" > canvas script var context document getElementsByTagName 'canvas' )[ ]. getContext '2d' ); var lastX context canvas width Math random (); var lastY context canvas height Math random (); var hue function line () context (); context translate context canvas width context canvas height ); context scale 0.9 0.9 ); context translate context canvas width context canvas height ); context beginPath (); context lineWidth Math random () 10 context moveTo lastX lastY ); lastX context canvas width Math random (); lastY context canvas height Math random (); context bezierCurveTo context canvas width Math random (), context canvas height Math random (), context canvas width Math random (), context canvas height Math random (), lastX lastY ); hue hue 10 Math random (); context strokeStyle 'hsl(' hue ', 50%, 50%)' context shadowColor 'white' context shadowBlur 10 context stroke (); context restore (); setInterval line 50 ); function blank () context fillStyle 'rgba(0,0,0,0.1)' context fillRect context canvas width context canvas height ); setInterval blank 40 ); script The 2D rendering context for canvas is often used for sprite-based games. The following example demonstrates this: Here is the source for this example: html lang "en" meta charset "utf-8" title Blue Robot Demo title style html overflow hidden min-height 200 px min-width 380 px body height 200 px position relative margin px buttons position absolute bottom px left px margin px style canvas width "380" height "200" > canvas script var Landscape function context width height this offset this width width this advance function dx this offset += dx }; this horizon height 0.7 // This creates the sky gradient (from a darker blue to white at the bottom) this sky context createLinearGradient this horizon ); this sky addColorStop 0.0 'rgb(55,121,179)' ); this sky addColorStop 0.7 'rgb(121,194,245)' ); this sky addColorStop 1.0 'rgb(164,200,214)' ); // this creates the grass gradient (from a darker green to a lighter green) this earth context createLinearGradient this horizon height ); this earth addColorStop 0.0 'rgb(81,140,20)' ); this earth addColorStop 1.0 'rgb(123,177,57)' ); this paintBackground function context width height // first, paint the sky and grass rectangles context fillStyle this sky context fillRect width this horizon ); context fillStyle this earth context fillRect this horizon width height this horizon ); // then, draw the cloudy banner // we make it cloudy by having the draw text off the top of the // canvas, and just having the blurred shadow shown on the canvas context (); context translate width (( this offset this width 3.2 )) this width 4.0 )) ); context shadowColor 'white' context shadowOffsetY 30 this horizon // offset down on canvas context shadowBlur '5' context fillStyle 'white' context textAlign 'left' context textBaseline 'top' context font '20px sans-serif' context fillText 'WHATWG ROCKS' 10 30 ); // text up above canvas context restore (); // then, draw the background tree context (); context translate width (( this offset this width 0.2 )) this width 1.5 )) 30 ); context beginPath (); context fillStyle 'rgb(143,89,2)' context lineStyle 'rgb(10,10,10)' context lineWidth context rect this horizon 10 50 ); // trunk context fill (); context stroke (); context beginPath (); context fillStyle 'rgb(78,154,6)' context arc this horizon 60 30 Math PI ); // leaves context fill (); context stroke (); context restore (); }; this paintForeground function context width height // draw the box that goes in front context (); context translate width (( this offset this width 0.7 )) this width 1.1 )) ); context beginPath (); context rect this horizon 25 25 ); context fillStyle 'rgb(220,154,94)' context lineStyle 'rgb(10,10,10)' context lineWidth context fill (); context stroke (); context restore (); }; }; script script var BlueRobot function () this sprites new Image (); this sprites src 'blue-robot.png' // this sprite sheet has 8 cells this targetMode 'idle' this walk function () this targetMode 'walk' }; this stop function () this targetMode 'idle' }; this frameIndex 'idle' ], // first cell is the idle frame 'walk' ], // the walking animation is cells 1-6 'stop' ], // last cell is the stopping animation }; this mode 'idle' this frame // index into frameIndex this tick function () // this advances the frame and the robot // the return value is how many pixels the robot has moved this frame += if this frame >= this frameIndex this mode ]. length // we've reached the end of this animation cycle this frame if this mode != this targetMode // switch to next cycle if this mode == 'walk' // we need to stop walking before we decide what to do next this mode 'stop' else if this mode == 'stop' if this targetMode == 'walk' this mode 'walk' else this mode 'idle' else if this mode == 'idle' if this targetMode == 'walk' this mode 'walk' if this mode == 'walk' return return }, this paint function context if this sprites complete return // draw the right frame out of the sprite sheet onto the canvas // we assume each frame is as high as the sprite sheet // the x,y coordinates give the position of the bottom center of the sprite context drawImage this sprites this frameIndex this mode ][ this frame this sprites height this sprites height this sprites height this sprites height this sprites height this sprites height this sprites height ); }; }; script script var canvas document getElementsByTagName 'canvas' )[ ]; var context canvas getContext '2d' ); var landscape new Landscape context canvas width canvas height ); var blueRobot new BlueRobot (); // paint when the browser wants us to, using requestAnimationFrame() function paint () context clearRect canvas width canvas height ); landscape paintBackground context canvas width canvas height ); blueRobot paint context canvas width landscape horizon 1.1 ); landscape paintForeground context canvas width canvas height ); requestAnimationFrame paint ); paint (); // but tick every 100ms, so that we don't slow down when we don't paint setInterval function () var dx blueRobot tick (); landscape advance dx ); }, 100 ); script class "buttons" input type button value "Walk" onclick "blueRobot.walk()" input type button value "Stop" onclick "blueRobot.stop()" footer small Blue Robot Player Sprite by href "https://johncolburn.deviantart.com/" JohnColburn Licensed under the terms of the Creative Commons Attribution Share-Alike 3.0 Unported license. small small This work is itself licensed under a rel "license" href "https://creativecommons.org/licenses/by-sa/3.0/" Creative Commons Attribution-ShareAlike 3.0 Unported License small footer 4.12.5.2 The ImageBitmap rendering context 4.12.5.2.1 Introduction ImageBitmapRenderingContext is a performance-oriented interface that provides a low overhead method for displaying the contents of ImageBitmap objects. It uses transfer semantics to reduce overall memory consumption. It also streamlines performance by avoiding intermediate compositing, unlike the drawImage() method of CanvasRenderingContext2D Using an img element as an intermediate for getting an image resource into a canvas, for example, would result in two copies of the decoded image existing in memory at the same time: the img element's copy, and the one in the canvas's backing store. This memory cost can be prohibitive when dealing with extremely large images. This can be avoided by using ImageBitmapRenderingContext Using ImageBitmapRenderingContext , here is how to transcode an image to the JPEG format in a memory- and CPU-efficient way: createImageBitmap inputImageBlob ). then image => const canvas document createElement 'canvas' ); const context canvas getContext 'bitmaprenderer' ); context transferFromImageBitmap image ); canvas toBlob outputJPEGBlob => // Do something with outputJPEGBlob. }, 'image/jpeg' ); }); 4.12.5.2.2 The ImageBitmapRenderingContext interface ImageBitmapRenderingContext Firefox 46+ Safari No Chrome 56+ Opera 43+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 46+ Safari iOS No Chrome Android 56+ WebView Android 56+ Samsung Internet 6.0+ Opera Android 43+ Exposed =( Window Worker )] interface ImageBitmapRenderingContext readonly attribute HTMLCanvasElement or OffscreenCanvas canvas undefined transferFromImageBitmap ImageBitmap bitmap ); }; dictionary ImageBitmapRenderingContextSettings boolean alpha true }; context canvas getContext ('bitmaprenderer' [, { [ alpha : false ] } ] ) Returns an ImageBitmapRenderingContext object that is permanently bound to a particular canvas element. If the alpha setting is provided and set to false, then the canvas is forced to always be opaque. context canvas Returns the canvas element that the context is bound to. context transferFromImageBitmap (imageBitmap) ImageBitmapRenderingContext/transferFromImageBitmap Firefox 52+ Safari No Chrome 56+ Opera 43+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 52+ Safari iOS No Chrome Android 56+ WebView Android 56+ Samsung Internet 6.0+ Opera Android 43+ Transfers the underlying bitmap data from imageBitmap to context , and the bitmap becomes the contents of the canvas element to which context is bound. context transferFromImageBitmap (null) Replaces contents of the canvas element to which context is bound with a transparent black bitmap whose size corresponds to the width and height content attributes of the canvas element. The canvas attribute must return the value it was initialized to when the object was created. An ImageBitmapRenderingContext object has an output bitmap , which is a reference to bitmap data An ImageBitmapRenderingContext object has a bitmap mode , which can be set to valid or blank . A value of valid indicates that the context's output bitmap refers to bitmap data that was acquired via transferFromImageBitmap() A value blank indicates that the context's output bitmap is a default transparent bitmap. An ImageBitmapRenderingContext object also has an alpha flag, which can be set to true or false. When an ImageBitmapRenderingContext object has its alpha flag set to false, the contents of the canvas element to which the context is bound are obtained by compositing the context's output bitmap onto an opaque black bitmap of the same size using the source-over composite operation. If the alpha flag is set to true, then the output bitmap is used as the contents of the canvas element to which the context is bound. [COMPOSITE] The step of compositing over an opaque black bitmap ought to be elided whenever equivalent results can be obtained more efficiently by other means. When a user agent is required to set an ImageBitmapRenderingContext 's output bitmap , with a context argument that is an ImageBitmapRenderingContext object and an optional argument bitmap that refers to bitmap data , it must run these steps: If a bitmap argument was not provided, then: Set context 's bitmap mode to blank Let canvas be the canvas element to which context is bound. Set context 's output bitmap to be transparent black with an intrinsic width equal to the numeric value of canvas 's width attribute and an intrinsic height equal to the numeric value of canvas 's height attribute, those values being interpreted in CSS pixels Set the output bitmap 's origin-clean flag to true. If a bitmap argument was provided, then: Set context 's bitmap mode to valid Set context 's output bitmap to refer to the same underlying bitmap data as bitmap , without making a copy. The origin-clean flag of bitmap is included in the bitmap data to be referenced by context 's output bitmap The ImageBitmapRenderingContext creation algorithm , which is passed a target and options , consists of running these steps: Let settings be the result of converting options to the dictionary type ImageBitmapRenderingContextSettings . (This can throw an exception.) Let context be a new ImageBitmapRenderingContext object. Initialize context 's canvas attribute to point to target Set context 's output bitmap to the same bitmap as target 's bitmap (so that they are shared). Run the steps to set an ImageBitmapRenderingContext 's output bitmap with context Initialize context 's alpha flag to true. Process each of the members of settings as follows: alpha If false, then set context 's alpha flag to false. Return context The transferFromImageBitmap( imageBitmap method, when invoked, must run these steps: Let bitmapContext be the ImageBitmapRenderingContext object on which the transferFromImageBitmap() method was called. If imageBitmap is null, then run the steps to set an ImageBitmapRenderingContext's output bitmap , with bitmapContext as the context argument and no bitmap argument, then return. If the value of imageBitmap 's [[Detached]] internal slot is set to true, then throw an InvalidStateError DOMException Run the steps to set an ImageBitmapRenderingContext 's output bitmap , with the context argument equal to bitmapContext , and the bitmap argument referring to imageBitmap 's underlying bitmap data Set the value of imageBitmap 's [[Detached]] internal slot to true. Unset imageBitmap's bitmap data 4.12.5.3 The OffscreenCanvas interface OffscreenCanvas Support in one engine only. Firefox 🔰 44+ Safari No Chrome 69+ Opera 56+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 🔰 44+ Safari iOS No Chrome Android 69+ WebView Android No Samsung Internet 10.0+ Opera Android 48+ typedef OffscreenCanvasRenderingContext2D or ImageBitmapRenderingContext or WebGLRenderingContext or WebGL2RenderingContext OffscreenRenderingContext dictionary ImageEncodeOptions DOMString type = "image/png"; unrestricted double quality }; enum OffscreenRenderingContextId 2d bitmaprenderer webgl webgl2 };
Exposed =( Window Worker ), Transferable interface OffscreenCanvas EventTarget constructor ([ EnforceRange unsigned long long width , [ EnforceRange unsigned long long height ); attribute EnforceRange unsigned long long width attribute EnforceRange unsigned long long height OffscreenRenderingContext getContext OffscreenRenderingContextId contextId optional any options null ); ImageBitmap transferToImageBitmap (); Promise Blob convertToBlob optional ImageEncodeOptions options = {}); }; OffscreenCanvas is an EventTarget so that WebGL can fire webglcontextlost and webglcontextrestored events at it. [WEBGL] OffscreenCanvas objects are used to create rendering contexts, much like an HTMLCanvasElement , but with no connection to the DOM. This makes it possible to use canvas rendering contexts in workers WebGLRenderingContext/commit Support in one engine only. Firefox 🔰 44+ Safari No Chrome No Opera No Edge No Edge (Legacy) No Internet Explorer No Firefox Android No Safari iOS No Chrome Android No WebView Android No Samsung Internet No Opera Android No An OffscreenCanvas object may hold a weak reference to a placeholder canvas element , which is typically in the DOM, whose embedded content is provided by the OffscreenCanvas object. The bitmap of the OffscreenCanvas object is pushed to the placeholder canvas element by calling the commit() method of the OffscreenCanvas object's rendering context. All rendering context types that can be created by an OffscreenCanvas object must implement a commit() method. The exact behavior of the commit method (e.g. whether it copies or transfers bitmaps) may vary, as defined by the rendering contexts' respective specifications. Only the 2D context for offscreen canvases is defined in this specification. offscreenCanvas = new OffscreenCanvas width height OffscreenCanvas/OffscreenCanvas Support in one engine only. Firefox 🔰 46+ Safari No Chrome 69+ Opera 56+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 🔰 46+ Safari iOS No Chrome Android 69+ WebView Android No Samsung Internet 10.0+ Opera Android Yes Returns a new OffscreenCanvas object that is not linked to a placeholder canvas element , and whose bitmap's size is determined by the width and height arguments. context offscreenCanvas getContext contextId [, options ] ) OffscreenCanvas/getContext Support in one engine only. Firefox 🔰 44+ Safari No Chrome 69+ Opera 56+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 🔰 44+ Safari iOS No Chrome Android 69+ WebView Android No Samsung Internet 10.0+ Opera Android 48+ Returns an object that exposes an API for drawing on the OffscreenCanvas object. contextId specifies the desired API: " 2d ", " bitmaprenderer ", " webgl ", or " webgl2 ". options is handled by that API. This specification defines the " 2d " context below, which is similar but distinct from the " 2d context that is created from a canvas element. The WebGL specifications define the webgl " and " webgl2 " contexts. [WEBGL] Returns null if the canvas has already been initialized with another context type (e.g., trying to get a " 2d " context after getting a webgl " context). An OffscreenCanvas object has an internal bitmap that is initialized when the object is created. The width and height of the bitmap are equal to the values of the width and height attributes of the OffscreenCanvas object. Initially, all the bitmap's pixels are transparent black An OffscreenCanvas object can have a rendering context bound to it. Initially, it does not have a bound rendering context. To keep track of whether it has a rendering context or not, and what kind of rendering context it is, an OffscreenCanvas object also has a context mode , which is initially none but can be changed to either 2d bitmaprenderer webgl webgl2 , or detached by algorithms defined in this specification. The constructor OffscreenCanvas( width height , when invoked, must create a new OffscreenCanvas object with its bitmap initialized to a rectangular array of transparent black pixels of the dimensions specified by width and height ; and its width and height attributes initialized to width and height respectively. OffscreenCanvas objects are transferable . Their transfer steps , given value and dataHolder , are as follows: If value 's context mode is not equal to none , then throw an InvalidStateError DOMException Set value 's context mode to detached Let width and height be the dimensions of value 's bitmap Unset value 's bitmap Set dataHolder .[[Width]] to width and dataHolder .[[Height]] to height Set dataHolder .[[PlaceholderCanvas]] to be a weak reference to value 's placeholder canvas element , if value has one, or null if it does not. Their transfer-receiving steps , given dataHolder and value are: Initialize value 's bitmap to a rectangular array of transparent black pixels with width given by dataHolder .[[Width]] and height given by dataHolder .[[Height]]. If dataHolder .[[PlaceholderCanvas]] is not null, set value 's placeholder canvas element to dataHolder .[[PlaceholderCanvas]] (while maintaining the weak reference semantics). The getContext( contextId options method of an OffscreenCanvas object, when invoked, must run these steps: If options is not an object , then set options to null. Set options to the result of converting options to a JavaScript value. Run the steps in the cell of the following table whose column header matches this OffscreenCanvas object's context mode and whose row header matches contextId none 2d bitmaprenderer webgl or webgl2 detached 2d Follow the offscreen 2D context creation algorithm defined in the section below, passing it this OffscreenCanvas object and options , to obtain an OffscreenCanvasRenderingContext2D object; if this does not throw an exception, then set this OffscreenCanvas object's context mode to 2d , and return the new OffscreenCanvasRenderingContext2D object. Return the same object as was returned the last time the method was invoked with this same first argument. Return null. Return null. Throw an InvalidStateError DOMException bitmaprenderer Follow the ImageBitmapRenderingContext creation algorithm defined in the section above, passing it this OffscreenCanvas object and options to obtain an ImageBitmapRenderingcontext object; if this does not throw an exception, then set this OffscreenCanvas object's context mode to bitmaprenderer , and return the new ImageBitmapRenderingcontext object. Return null. Return the same object as was returned the last time the method was invoked with this same first argument. Return null. Throw an InvalidStateError DOMException webgl " or " webgl2 Follow the instructions given in the WebGL specifications' Context Creation sections to obtain either a WebGLRenderingContext WebGL2RenderingContext or null; if the returned value is null, then return null; otherwise, set this OffscreenCanvas object's context mode to webgl or webgl2 , and return the WebGLRenderingContext or WebGL2RenderingContext object. [WEBGL] Return null. Return null. Return the same value as was returned the last time the method was invoked with this same first argument. Throw an InvalidStateError DOMException offscreenCanvas width value OffscreenCanvas/width Support in one engine only. Firefox 🔰 44+ Safari No Chrome 69+ Opera 56+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 🔰 44+ Safari iOS No Chrome Android 69+ WebView Android No Samsung Internet 10.0+ Opera Android 48+ offscreenCanvas height value OffscreenCanvas/height Support in one engine only. Firefox 🔰 44+ Safari No Chrome 69+ Opera 56+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 🔰 44+ Safari iOS No Chrome Android 69+ WebView Android No Samsung Internet 10.0+ Opera Android 48+ These attributes return the dimensions of the OffscreenCanvas object's bitmap They can be set, to replace the bitmap with a new, transparent black bitmap of the specified dimensions (effectively resizing it). If either the width or height attributes of an OffscreenCanvas object are set (to a new value or to the same value as before) and the OffscreenCanvas object's context mode is 2d , then reset the rendering context to its default state and resize the OffscreenCanvas object's bitmap to the new values of the width and height attributes. The resizing behavior for " webgl " and " webgl2 " contexts is defined in the WebGL specifications. [WEBGL] If an OffscreenCanvas object whose dimensions were changed has placeholder canvas element , then the placeholder canvas element 's intrinsic size will only be updated via the commit() method of the OffscreenCanvas object's rendering context. promise offscreenCanvas convertToBlob ( [ options ] ) OffscreenCanvas/convertToBlob Support in one engine only. Firefox 🔰 46+ Safari No Chrome 69+ Opera 56+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 🔰 46+ Safari iOS No Chrome Android 69+ WebView Android No Samsung Internet 10.0+ Opera Android 48+ Returns a promise that will fulfill with a new Blob object representing a file containing the image in the OffscreenCanvas object. The argument, if provided, is a dictionary that controls the encoding options of the image file to be created. The type field specifies the file format and has a default value of " image/png "; that type is also used if the requested type isn't supported. If the image format supports variable quality (such as " image/jpeg "), then the quality field is a number in the range 0.0 to 1.0 inclusive indicating the desired quality level for the resulting image. canvas transferToImageBitmap () OffscreenCanvas/transferToImageBitmap Support in one engine only. Firefox 🔰 46+ Safari No Chrome 69+ Opera 56+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 🔰 46+ Safari iOS No Chrome Android 69+ WebView Android No Samsung Internet 10.0+ Opera Android 48+ Returns a newly created ImageBitmap object with the image in the OffscreenCanvas object. The image in the OffscreenCanvas object is replaced with a new blank image. The convertToBlob( options method, when invoked, must run the following steps: If the value of this OffscreenCanvas object's [[Detached]] internal slot is set to true, then return a promise rejected with an InvalidStateError DOMException If this OffscreenCanvas object's context mode is 2d and the rendering context's bitmap 's origin-clean flag is set to false, then return a promise rejected with a SecurityError DOMException If this OffscreenCanvas object's bitmap has no pixels (i.e., either its horizontal dimension or its vertical dimension is zero) then return a promise rejected with an IndexSizeError DOMException Let bitmap be a copy of this OffscreenCanvas object's bitmap Let result be a new promise object. Run these steps in parallel Let file be serialization of bitmap as a file , with options 's type and quality if present. Queue an element task on the canvas blob serialization task source given the canvas element to run these steps: If file is null, then reject result with an EncodingError DOMException Otherwise, resolve result with a new Blob object, created in the relevant Realm of this OffscreenCanvas object, representing file [FILEAPI] Return result The transferToImageBitmap() method, when invoked, must run the following steps: If the value of this OffscreenCanvas object's [[Detached]] internal slot is set to true, then throw an InvalidStateError DOMException If this OffscreenCanvas object's context mode is set to none , then throw an InvalidStateError DOMException Let image be a newly created ImageBitmap object that references the same underlying bitmap data as this OffscreenCanvas object's bitmap Set this OffscreenCanvas object's bitmap to reference a newly created bitmap of the same dimensions and color space as the previous bitmap, and with its pixels initialized to transparent black , or opaque black if the rendering context's alpha flag is set to false. This means that if the rendering context of this OffscreenCanvas is WebGLRenderingContext , the value of preserveDrawingBuffer will have no effect. [WEBGL] Return image 4.12.5.3.1 The offscreen 2D rendering context Exposed =( Window Worker )] interface OffscreenCanvasRenderingContext2D undefined commit (); readonly attribute OffscreenCanvas canvas }; OffscreenCanvasRenderingContext2D includes CanvasState OffscreenCanvasRenderingContext2D includes CanvasTransform OffscreenCanvasRenderingContext2D includes CanvasCompositing OffscreenCanvasRenderingContext2D includes CanvasImageSmoothing OffscreenCanvasRenderingContext2D includes CanvasFillStrokeStyles OffscreenCanvasRenderingContext2D includes CanvasShadowStyles OffscreenCanvasRenderingContext2D includes CanvasFilters OffscreenCanvasRenderingContext2D includes CanvasRect OffscreenCanvasRenderingContext2D includes CanvasDrawPath OffscreenCanvasRenderingContext2D includes CanvasText OffscreenCanvasRenderingContext2D includes CanvasDrawImage OffscreenCanvasRenderingContext2D includes CanvasImageData OffscreenCanvasRenderingContext2D includes CanvasPathDrawingStyles OffscreenCanvasRenderingContext2D includes CanvasTextDrawingStyles OffscreenCanvasRenderingContext2D includes CanvasPath The OffscreenCanvasRenderingContext2D object is a rendering context for drawing to the bitmap of an OffscreenCanvas object. It is similar to the CanvasRenderingContext2D object, with the following differences: there is no support for user interface features; its canvas attribute refers to an OffscreenCanvas object rather than a canvas element; it has a commit() method for pushing the rendered image to the context's OffscreenCanvas object's placeholder canvas element An OffscreenCanvasRenderingContext2D object has a bitmap that is initialized when the object is created. The bitmap has an origin-clean flag, which can be set to true or false. Initially, when one of these bitmaps is created, its origin-clean flag must be set to true. An OffscreenCanvasRenderingContext2D object also has an alpha flag, which can be set to true or false. Initially, when the context is created, its alpha flag must be set to true. When an OffscreenCanvasRenderingContext2D object has its alpha flag set to false, then its alpha channel must be fixed to 1.0 (fully opaque) for all pixels, and attempts to change the alpha component of any pixel must be silently ignored. An OffscreenCanvasRenderingContext2D object also has a color space setting of type PredefinedColorSpace . The color space for the context's bitmap is set to the context's color space An OffscreenCanvasRenderingContext2D object has an associated OffscreenCanvas object , which is the OffscreenCanvas object from which the OffscreenCanvasRenderingContext2D object was created. offscreenCanvasRenderingContext2D commit () Copies the rendering context's bitmap to the bitmap of the placeholder canvas element of the associated OffscreenCanvas object . The copy operation is synchronous. Calling this method is not needed for the transfer, since it happens automatically during the event loop execution. offscreenCanvas offscreenCanvasRenderingContext2D canvas Returns the associated OffscreenCanvas object The offscreen 2D context creation algorithm , which is passed a target (an OffscreenCanvas object) and optionally some arguments, consists of running the following steps: If the algorithm was passed some arguments, let arg be the first such argument. Otherwise, let arg be undefined. Let settings be the result of converting arg to the dictionary type CanvasRenderingContext2DSettings . (This can throw an exception.). Let context be a new OffscreenCanvasRenderingContext2D object. Set context 's associated OffscreenCanvas object to target If settings [" alpha "] is false, then set context 's alpha flag to false. Set context 's color space to settings [" colorSpace "]. Set context 's bitmap to a newly created bitmap with the dimensions specified by the width and height attributes of target , and set target 's bitmap to the same bitmap (so that they are shared). If context 's alpha flag is set to true, initialize all the pixels of context 's bitmap to transparent black . Otherwise, initialize the pixels to opaque black Return context The commit() method, when invoked, must run the following steps: If this OffscreenCanvasRenderingContext2D 's associated OffscreenCanvas object does not have a placeholder canvas element , then return. Let image be a copy of this OffscreenCanvasRenderingContext2D 's bitmap , including the value of its origin-clean flag. Queue an element task on the DOM manipulation task source given the placeholder canvas element to set the placeholder canvas element 's output bitmap to be a reference to image If image has different dimensions than the bitmap previously referenced as the placeholder canvas element 's output bitmap , then this task will result in a change in the placeholder canvas element 's intrinsic size , which can affect document layout. Implementations are encouraged to short-circuit the graphics update steps of the window event loop for the purposes of updating the contents of a placeholder canvas element to the display. This could mean, for example, that the commit() method can copy the bitmap contents directly to a graphics buffer that is mapped to the physical display location of the placeholder canvas element . This or similar short-circuiting approaches can significantly reduce display latency, especially in cases where the commit() method is invoked from a worker event loop and the window event loop of the placeholder canvas element is busy. However, such shortcuts can not have any script-observable side-effects. This means that the committed bitmap still needs to be sent to the placeholder canvas element , in case the element is used as a CanvasImageSource , as an ImageBitmapSource , or in case toDataURL() or toBlob() are called on it. The canvas attribute, on getting, must return this OffscreenCanvasRenderingContext2D 's associated OffscreenCanvas object 4.12.5.4 Color spaces and color space conversion The canvas APIs provide mechanisms for specifying the color space of the canvas's backing store. The default backing store color space for all canvas APIs is 'srgb' Color space conversion must be applied to the canvas's backing store when rendering the canvas to the output device. This color space conversion must be identical to the color space conversion that would be applied to an img element with a color profile that specifies the same color space as the canvas's backing store. When drawing content to a 2D context, all inputs must be converted to the context's color space before drawing. Interpolation of gradient color stops must be performed on color values after conversion to the context's color space . Alpha blending must be performed on values after conversion to the context's color space There do not exist any inputs to a 2D context for which the color space is undefined. The color space for CSS colors is defined in CSS Color . The color space for images that specify no color profile information is assumed to be 'srgb' , as specified in the Color Spaces of Untagged Colors section of CSS Color [CSSCOLOR] 4.12.5.5 Serializing bitmaps to a file When a user agent is to create serialization of the bitmap as a file , given a type and an optional quality , it must create an image file in the format given by type . If an error occurs during the creation of the image file (e.g. an internal encoder error), then the result of the serialization is null. [PNG] The image file's pixel data must be the bitmap's pixel data scaled to one image pixel per coordinate space unit, and if the file format used supports encoding resolution metadata, the resolution must be given as 96dpi (one image pixel per CSS pixel ). If type is supplied, then it must be interpreted as a MIME type giving the format to use. If the type has any parameters, then it must be treated as not supported. For example, the value " image/png " would mean to generate a PNG image, the value " image/jpeg " would mean to generate a JPEG image, and the value image/svg+xml " would mean to generate an SVG image (which would require that the user agent track how the bitmap was generated, an unlikely, though potentially awesome, feature). User agents must support PNG (" image/png "). User agents may support other types. If the user agent does not support the requested type, then it must create the file using the PNG format. [PNG] User agents must convert the provided type to ASCII lowercase before establishing if they support that type. For image types that do not support an alpha channel, the serialized image must be the bitmap image composited onto an opaque black background using the source-over operator. For image types that support color profiles, the serialized image must include a color profile indicating the color space of the underlying bitmap. For image types that do not support color profiles, the serialized image must be converted to the 'srgb' color space using 'relative-colorimetric' rendering intent. Thus, in the 2D context, calling the drawImage() method to render the output of the toDataURL() or toBlob() method to the canvas, given the appropriate dimensions, has no visible effect beyond, at most, clipping colors of the canvas to a more narrow gamut. If type is an image format that supports variable quality (such as image/jpeg "), quality is given, and type is not image/png ", then, if Type quality ) is Number, and quality is in the range 0.0 to 1.0 inclusive, the user agent must treat quality as the desired quality level. Otherwise, the user agent must use its default quality value, as if the quality argument had not been given. The use of type-testing here, instead of simply declaring quality as a Web IDL double , is a historical artifact. Different implementations can have slightly different interpretations of "quality". When the quality is not specified, an implementation-specific default is used that represents a reasonable compromise between compression ratio, image quality, and encoding time. 4.12.5.6 Security with canvas elements This section is non-normative. Information leakage can occur if scripts from one origin can access information (e.g. read pixels) from images from another origin (one that isn't the same ). To mitigate this, bitmaps used with canvas elements and ImageBitmap objects are defined to have a flag indicating whether they are origin-clean . All bitmaps start with their origin-clean set to true. The flag is set to false when cross-origin images are used. The toDataURL() toBlob() , and getImageData() methods check the flag and will throw a SecurityError DOMException rather than leak cross-origin data. The value of the origin-clean flag is propagated from a source canvas element's bitmap to a new ImageBitmap object by createImageBitmap() . Conversely, a destination canvas element's bitmap will have its origin-clean flags set to false by drawImage if the source image is an ImageBitmap object whose bitmap has its origin-clean flag set to false. The flag can be reset in certain situations; for example, when changing the value of the width or the height content attribute of the canvas element to which a CanvasRenderingContext2D is bound, the bitmap is cleared and its origin-clean flag is reset. When using an ImageBitmapRenderingContext , the value of the origin-clean flag is propagated from ImageBitmap objects when they are transferred to the canvas via transferFromImageBitmap() 4.12.5.7 Premultiplied alpha and the 2D rendering context Premultiplied alpha refers to one way of representing transparency in an image, the other being non-premultiplied alpha. Under non-premultiplied alpha, the red, green, and blue channels of a pixel represent that pixel's color, and its alpha channel represents that pixel's opacity. Under premultiplied alpha, however, the red, green, and blue channels of a pixel represent the amounts of color that the pixel adds to the image, and its alpha channel represents the amount that the pixel obscures whatever is behind it. For instance, assuming the color channels range from 0 (off) to 255 (full intensity), these example colors are represented in the following ways: CSS color representation Premultiplied representation Non-premultiplied representation Description of color Image of color blended above other content rgba(255, 127, 0, 1) 255, 127, 0, 255 255, 127, 0, 255 Completely-opaque orange rgba(255, 255, 0, 0.5) 127, 127, 0, 127 255, 255, 0, 127 Halfway-opaque yellow Unrepresentable 255, 127, 0, 127 Unrepresentable Additive halfway-opaque orange Unrepresentable 255, 127, 0, 0 Unrepresentable Additive fully-transparent orange rgba(255, 127, 0, 0) 0, 0, 0, 0 255, 127, 0, 0 Fully-transparent ("invisible") orange rgba(0, 127, 255, 0) 0, 0, 0, 0 255, 127, 0, 0 Fully-transparent ("invisible") turquoise Converting a color value from a non-premultiplied representation to a premultiplied one involves multiplying the color's red, green, and blue channels by its alpha channel (remapping the range of the alpha channel such that "fully transparent" is 0, and "fully opaque" is 1). Converting a color value from a premultiplied representation to a non-premultiplied one involves the inverse: dividing the color's red, green, and blue channels by its alpha channel. As certain colors can only be represented under premultiplied alpha (for instance, additive colors), and others can only be represented under non-premultiplied alpha (for instance, "invisible" colors which hold certain red, green, and blue values even with no opacity); and division and multiplication on 8-bit integers (which is how canvas's colors are currently stored) entails a loss of precision, converting between premultiplied and non-premultiplied alpha is a lossy operation on colors that are not fully opaque. CanvasRenderingContext2D 's output bitmap and an OffscreenCanvasRenderingContext2D 's bitmap must use premultiplied alpha to represent transparent colors. It is important for canvas bitmaps to represent colors using premultiplied alpha because it affects the range of representable colors. While additive colors cannot currently be drawn onto canvases directly because CSS colors are non-premultiplied and cannot represent them, it is still possible to, for instance, draw additive colors onto a WebGL canvas and then draw that WebGL canvas onto a 2D canvas via drawImage() 4.13 Custom elements Using_custom_elements Support in all current engines. Firefox 63+ Safari 10.1+ Chrome 54+ Opera 41+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 63+ Safari iOS 10.3+ Chrome Android 54+ WebView Android 54+ Samsung Internet 6.0+ Opera Android 41+ 4.13.1 Introduction This section is non-normative. Custom elements provide a way for authors to build their own fully-featured DOM elements. Although authors could always use non-standard elements in their documents, with application-specific behavior added after the fact by scripting or similar, such elements have historically been non-conforming and not very functional. By defining a custom element, authors can inform the parser how to properly construct an element and how elements of that class should react to changes. Custom elements are part of a larger effort to "rationalise the platform", by explaining existing platform features (like the elements of HTML) in terms of lower-level author-exposed extensibility points (like custom element definition). Although today there are many limitations on the capabilities of custom elements—both functionally and semantically—that prevent them from fully explaining the behaviors of HTML's existing elements, we hope to shrink this gap over time. 4.13.1.1 Creating an autonomous custom element This section is non-normative. For the purposes of illustrating how to create an autonomous custom element , let's define a custom element that encapsulates rendering a small icon for a country flag. Our goal is to be able to use it like so: flag-icon country "nl" > flag-icon To do this, we first declare a class for the custom element, extending HTMLElement class FlagIcon extends HTMLElement constructor () super (); this _countryCode null static get observedAttributes () return "country" ]; attributeChangedCallback name oldValue newValue // name will always be "country" due to observedAttributes this _countryCode newValue this _updateRendering (); connectedCallback () this _updateRendering (); get country () return this _countryCode set country this setAttribute "country" ); _updateRendering () // Left as an exercise for the reader. But, you'll probably want to // check this.ownerDocument.defaultView to see if we've been // inserted into a document with a browsing context, and avoid // doing any work if not. We then need to use this class to define the element: customElements define "flag-icon" FlagIcon ); At this point, our above code will work! The parser, whenever it sees the flag-icon tag, will construct a new instance of our FlagIcon class, and tell our code about its new country attribute, which we then use to set the element's internal state and update its rendering (when appropriate). You can also create flag-icon elements using the DOM API: const flagIcon document createElement "flag-icon" flagIcon country "jp" document body appendChild flagIcon Finally, we can also use the custom element constructor itself. That is, the above code is equivalent to: const flagIcon new FlagIcon () flagIcon country "jp" document body appendChild flagIcon 4.13.1.2 Creating a form-associated custom element This section is non-normative. Adding a static formAssociated property, with a true value, makes an autonomous custom element form-associated custom element . The ElementInternals interface helps you to implement functions and properties common to form control elements. class MyCheckbox extends HTMLElement static get formAssociated () return true static get observedAttributes () return 'checked' ]; constructor () super (); this _internals this attachInternals (); this addEventListener 'click' this _onClick bind this )); get form () return this _internals form get name () return this getAttribute 'name' ); get type () return this localName get checked () return this getAttribute 'checked' ); set checked flag this toggleAttribute 'checked' Boolean flag )); attributeChangedCallback name oldValue newValue // name will always be "checked" due to observedAttributes this _internals setFormValue this checked 'on' null ); _onClick event this checked this checked customElements define 'my-checkbox' MyCheckbox ); You can use the custom element my-checkbox like a built-in form-associated element. For example, putting it in form or label associates the my-checkbox element with them, and submitting the form will send data provided by my-checkbox implementation. form action "..." method "..." label >< my-checkbox name "agreed" > my-checkbox I read the agreement. label input type "submit" form 4.13.1.3 Creating a custom element with default accessible roles, states, and properties This section is non-normative. By using the appropriate properties of ElementInternals , your custom element can have default accessibility semantics. The following code expands our form-associated checkbox from the previous section to properly set its default role and checkedness, as viewed by accessibility technology: class MyCheckbox extends HTMLElement static get formAssociated () return true static get observedAttributes () return 'checked' ]; constructor () super (); this _internals this attachInternals (); this addEventListener 'click' this _onClick bind this )); this _internals role 'checkbox' this _internals ariaChecked false get form () return this _internals form get name () return this getAttribute 'name' ); get type () return this localName get checked () return this getAttribute 'checked' ); set checked flag this toggleAttribute 'checked' Boolean flag )); attributeChangedCallback name oldValue newValue // name will always be "checked" due to observedAttributes this _internals setFormValue this checked 'on' null ); this _internals ariaChecked this checked _onClick event this checked this checked customElements define 'my-checkbox' MyCheckbox ); Note that, like for built-in elements, these are only defaults, and can be overridden by the page author using the role and aria-* attributes: input type "checkbox" checked role "button" aria-checked "false" my-checkbox role "button" checked aria-checked "false" Custom element authors are encouraged to state what aspects of their accessibility semantics are strong native semantics, i.e., should not be overridden by users of the custom element. In our example, the author of the my-checkbox element would state that its role and aria-checked values are strong native semantics, thus discouraging code such as the above. 4.13.1.4 Creating a customized built-in element This section is non-normative. Customized built-in elements are a distinct kind of custom element , which are defined slightly differently and used very differently compared to autonomous custom elements . They exist to allow reuse of behaviors from the existing elements of HTML, by extending those elements with new custom functionality. This is important since many of the existing behaviors of HTML elements can unfortunately not be duplicated by using purely autonomous custom elements . Instead, customized built-in elements allow the installation of custom construction behavior, lifecycle hooks, and prototype chain onto existing elements, essentially "mixing in" these capabilities on top of the already-existing element. Customized built-in elements require a distinct syntax from autonomous custom elements because user agents and other software key off an element's local name in order to identify the element's semantics and behavior. That is, the concept of customized built-in elements building on top of existing behavior depends crucially on the extended elements retaining their original local name. In this example, we'll be creating a customized built-in element named plastic-button , which behaves like a normal button but gets fancy animation effects added whenever you click on it. We start by defining a class, just like before, although this time we extend HTMLButtonElement instead of HTMLElement class PlasticButton extends HTMLButtonElement constructor () super (); this addEventListener "click" () => // Draw some fancy animation effects! }); When defining our custom element, we have to also specify the extends option: customElements define "plastic-button" PlasticButton extends "button" }); In general, the name of the element being extended cannot be determined simply by looking at what element interface it extends, as many elements share the same interface (such as and blockquote both sharing HTMLQuoteElement ). To construct our customized built-in element from parsed HTML source text, we use the is attribute on a button element: button is "plastic-button" Click Me! button Trying to use a customized built-in element as an autonomous custom element will not work; that is,Click me? will simply create an HTMLElement with no special behavior. If you need to create a customized built-in element programmatically, you can use the following form of createElement() const plasticButton document createElement "button" is "plastic-button" }); plasticButton textContent "Click me!" And as before, the constructor will also work: const plasticButton2 new PlasticButton (); console log plasticButton2 localName ); // will output "button" console assert plasticButton2 instanceof PlasticButton ); console assert plasticButton2 instanceof HTMLButtonElement ); Note that when creating a customized built-in element programmatically, the is attribute will not be present in the DOM, since it was not explicitly set. However, it will be added to the output when serializing console assert plasticButton hasAttribute "is" )); console log plasticButton outerHTML ); // will output ' ' Regardless of how it is created, all of the ways in which button is special apply to such "plastic buttons" as well: their focus behavior, ability to participate in form submission , the disabled attribute, and so on. Customized built-in elements are designed to allow extension of existing HTML elements that have useful user-agent supplied behavior or APIs. As such, they can only extend existing HTML elements defined in this specification, and cannot extend legacy elements such as bgsound blink isindex keygen multicol nextid , or spacer that have been defined to use HTMLUnknownElement as their element interface One reason for this requirement is future-compatibility: if a customized built-in element was defined that extended a currently-unknown element, for example combobox , this would prevent this specification from defining a combobox element in the future, as consumers of the derived customized built-in element would have come to depend on their base element having no interesting user-agent-supplied behavior. 4.13.1.5 Drawbacks of autonomous custom elements This section is non-normative. As specified below, and alluded to above, simply defining and using an element called taco-button does not mean that such elements represent buttons. That is, tools such as web browsers, search engines, or accessibility technology will not automatically treat the resulting element as a button just based on its defined name. To convey the desired button semantics to a variety of users, while still using an autonomous custom element , a number of techniques would need to be employed: The addition of the tabindex attribute would make the taco-button focusable . Note that if the taco-button were to become logically disabled, the tabindex attribute would need to be removed. The addition of an ARIA role and various ARIA states and properties helps convey semantics to accessibility technology. For example, setting the role to " button " will convey the semantics that this is a button, enabling users to successfully interact with the control using usual button-like interactions in their accessibility technology. Setting the aria-label property is necessary to give the button an accessible name , instead of having accessibility technology traverse its child text nodes and announce them. And setting the aria-disabled state to true " when the button is logically disabled conveys to accessibility technology the button's disabled state. The addition of event handlers to handle commonly-expected button behaviors helps convey the semantics of the button to web browser users. In this case, the most relevant event handler would be one that proxies appropriate keydown events to become click events, so that you can activate the button both with keyboard and by clicking. In addition to any default visual styling provided for taco-button elements, the visual styling will also need to be updated to reflect changes in logical state, such as becoming disabled; that is, whatever style sheet has rules for taco-button will also need to have rules for taco-button[disabled] With these points in mind, a full-featured taco-button that took on the responsibility of conveying button semantics (including the ability to be disabled) might look something like this: class TacoButton extends HTMLElement static get observedAttributes () return "disabled" ]; constructor () super (); this _internals this attachInternals (); this _internals role "button" this addEventListener "keydown" => if code === "Enter" || code === "Space" this dispatchEvent new PointerEvent "click" bubbles true cancelable true })); }); this addEventListener "click" => if this disabled preventDefault (); stopImmediatePropagation (); }); this _observer new MutationObserver (() => this _internals ariaLabel this textContent }); connectedCallback () this setAttribute "tabindex" "0" ); this _observer observe this childList true characterData true subtree true }); disconnectedCallback () this _observer disconnect (); get disabled () return this hasAttribute "disabled" ); set disabled flag this toggleAttribute "disabled" Boolean flag )); attributeChangedCallback name oldValue newValue // name will always be "disabled" due to observedAttributes if this disabled this removeAttribute "tabindex" ); this _internals ariaDisabled "true" else this setAttribute "tabindex" "0" ); this _internals ariaDisabled "false" Even with this rather-complicated element definition, the element is not a pleasure to use for consumers: it will be continually "sprouting" tabindex attributes of its own volition, and its choice of tabindex="0" focusability behavior may not match the button behavior on the current platform. This is because as of now there is no way to specify default focus behavior for custom elements, forcing the use of the tabindex attribute to do so (even though it is usually reserved for allowing the consumer to override default behavior). In contrast, a simple customized built-in element , as shown in the previous section, would automatically inherit the semantics and behavior of the button element, with no need to implement these behaviors manually. In general, for any elements with nontrivial behavior and semantics that build on top of existing elements of HTML, customized built-in elements will be easier to develop, maintain, and consume. 4.13.1.6 Upgrading elements after their creation This section is non-normative. Because element definition can occur at any time, a non-custom element could be created , and then later become a custom element after an appropriate definition is registered. We call this process "upgrading" the element, from a normal element into a custom element. Upgrades enable scenarios where it may be preferable for custom element definitions to be registered after relevant elements have been initially created, such as by the parser. They allow progressive enhancement of the content in the custom element. For example, in the following HTML document the element definition for img-viewer is loaded asynchronously: html lang "en" title Image viewer example title img-viewer filter "Kelvin" img src "images/tree.jpg" alt "A beautiful tree towering over an empty savannah" img-viewer script src "js/elements/img-viewer.js" async > script The definition for the img-viewer element here is loaded using a script element marked with the async attribute, placed after the tag in the markup. While the script is loading, the img-viewer element will be treated as an undefined element, similar to a span . Once the script loads, it will define the img-viewer element, and the existing img-viewer element on the page will be upgraded, applying the custom element's definition (which presumably includes applying an image filter identified by the string "Kelvin", enhancing the image's visual appearance). Note that upgrades only apply to elements in the document tree. (Formally, elements that are connected .) An element that is not inserted into a document will stay un-upgraded. An example illustrates this point: html lang "en" title Upgrade edge-cases example title example-element > example-element script "use strict" const inDocument document querySelector "example-element" ); const outOfDocument document createElement "example-element" ); // Before the element definition, both are HTMLElement: console assert inDocument instanceof HTMLElement ); console assert outOfDocument instanceof HTMLElement ); class ExampleElement extends HTMLElement {} customElements define "example-element" ExampleElement ); // After element definition, the in-document element was upgraded: console assert inDocument instanceof ExampleElement ); console assert outOfDocument instanceof ExampleElement )); document body appendChild outOfDocument ); // Now that we've moved the element into the document, it too was upgraded: console assert outOfDocument instanceof ExampleElement ); script 4.13.2 Requirements for custom element constructors and reactions When authoring custom element constructors authors are bound by the following conformance requirements: A parameter-less call to super() must be the first statement in the constructor body, to establish the correct prototype chain and this value before any further code is run. return statement must not appear anywhere inside the constructor body, unless it is a simple early-return ( return or return this ). The constructor must not use the document.write() or document.open() methods. The element's attributes and children must not be inspected, as in the non- upgrade case none will be present, and relying on upgrades makes the element less usable. The element must not gain any attributes or children, as this violates the expectations of consumers who use the createElement or createElementNS methods. In general, work should be deferred to connectedCallback as much as possible—especially work involving fetching resources or rendering. However, note that connectedCallback can be called more than once, so any initialization work that is truly one-time will need a guard to prevent it from running twice. In general, the constructor should be used to set up initial state and default values, and to set up event listeners and possibly a shadow root Several of these requirements are checked during element creation , either directly or indirectly, and failing to follow them will result in a custom element that cannot be instantiated by the parser or DOM APIs. This is true even if the work is done inside a constructor-initiated microtask , as a microtask checkpoint can occur immediately after construction. When authoring custom element reactions authors should avoid manipulating the node tree as this can lead to unexpected results. An element's connectedCallback can be queued before the element is disconnected, but as the callback queue is still processed, it results in a connectedCallback for an element that is no longer connected: class CParent extends HTMLElement connectedCallback () this firstChild remove (); customElements define "c-parent" CParent ); class CChild extends HTMLElement connectedCallback () console log "CChild connectedCallback: isConnected =" this isConnected ); customElements define "c-child" CChild ); const parent new CParent (), child new CChild (); parent append child ); document body append parent ); // Logs: // CChild connectedCallback: isConnected = false 4.13.3 Core concepts custom element is an element that is custom . Informally, this means that its constructor and prototype are defined by the author, instead of by the user agent. This author-supplied constructor function is called the custom element constructor Two distinct types of custom elements can be defined: Global_attributes/is Firefox 63+ Safari No Chrome 67+ Opera 54+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 63+ Safari iOS No Chrome Android 67+ WebView Android 67+ Samsung Internet 9.0+ Opera Android 48+ An autonomous custom element , which is defined with no extends option. These types of custom elements have a local name equal to their defined name customized built-in element , which is defined with an extends option. These types of custom elements have a local name equal to the value passed in their extends option, and their defined name is used as the value of the is attribute, which therefore must be a valid custom element name After a custom element is created changing the value of the is attribute does not change the element's behavior, as it is saved on the element as its is value Autonomous custom elements have the following element definition: Categories Flow content Phrasing content Palpable content For form-associated custom elements Listed labelable submittable , and resettable form-associated element Contexts in which this element can be used Where phrasing content is expected. Content model Transparent Content attributes Global attributes , except the is attribute form , for form-associated custom elements — Associates the element with a form element disabled , for form-associated custom elements — Whether the form control is disabled readonly , for form-associated custom elements — Affects willValidate , plus any behavior added by the custom element author name , for form-associated custom elements — Name of the element to use for form submission and in the form.elements API Any other attribute that has no namespace (see prose). Accessibility considerations For form-associated custom elements for authors for implementers Otherwise: for authors for implementers DOM interface Supplied by the element's author (inherits from HTMLElement An autonomous custom element does not have any special meaning: it represents its children. A customized built-in element inherits the semantics of the element that it extends. Any namespace-less attribute that is relevant to the element's functioning, as determined by the element's author, may be specified on an autonomous custom element , so long as the attribute name is XML-compatible and contains no ASCII upper alphas . The exception is the is attribute, which must not be specified on an autonomous custom element (and which will have no effect if it is). Customized built-in elements follow the normal requirements for attributes, based on the elements they extend. To add custom attribute-based behavior, use data-* attributes. An autonomous custom element is called a form-associated custom element if the element is associated with a custom element definition whose form-associated field is set to true. The name attribute represents the form-associated custom element 's name. The disabled attribute is used to make the form-associated custom element non-interactive and to prevent its submission value from being submitted. The form attribute is used to explicitly associate the form-associated custom element with its form owner The readonly attribute of form-associated custom elements specifies that the element is barred from constraint validation . User agents don't provide any other behavior for the attribute, but custom element authors should, where possible, use its presence to make their control non-editable in some appropriate fashion, similar to the behavior for the readonly attribute on built-in form controls. Constraint validation : If the readonly attribute is specified on a form-associated custom element , the element is barred from constraint validation The reset algorithm for form-associated custom elements is to enqueue a custom element callback reaction with the element, callback name " formResetCallback ", and an empty argument list. valid custom element name is a sequence of characters name that meets all of the following requirements: name must match the PotentialCustomElementName production: PotentialCustomElementName ::= [a-z] ( PCENChar )* '-' PCENChar )* PCENChar ::= "-" | "." | [0-9] | "_" | [a-z] | #xB7 | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x203F-#x2040] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] This uses the EBNF notation from the XML specification. [XML] name must not be any of the following: annotation-xml color-profile font-face font-face-src font-face-uri font-face-format font-face-name missing-glyph The list of names above is the summary of all hyphen-containing element names from the applicable specifications , namely SVG 2 and MathML [SVG] [MATHML] These requirements ensure a number of goals for valid custom element names They start with an ASCII lower alpha , ensuring that the HTML parser will treat them as tags instead of as text. They do not contain any ASCII upper alphas ensuring that the user agent can always treat HTML elements ASCII-case-insensitively. They contain a hyphen, used for namespacing and to ensure forward compatibility (since no elements will be added to HTML, SVG, or MathML with hyphen-containing local names in the future). They can always be created with createElement() and createElementNS() , which have restrictions that go beyond the parser's. Apart from these restrictions, a large variety of names is allowed, to give maximum flexibility for use cases like or custom element definition describes a custom element and consists of: name valid custom element name local name A local name constructor A Web IDL CustomElementConstructor callback function type value wrapping the custom element constructor A list of observed attributes sequence A collection of lifecycle callbacks A map, whose keys are the strings " connectedCallback ", disconnectedCallback ", " adoptedCallback ", attributeChangedCallback ", formAssociatedCallback ", formDisabledCallback ", formResetCallback ", and " formStateRestoreCallback ". The corresponding values are either a Web IDL Function callback function type value, or null. By default the value of each entry is null. construction stack A list, initially empty, that is manipulated by the upgrade an element algorithm and the HTML element constructors . Each entry in the list will be either an element or an already constructed marker form-associated boolean If this is true, user agent treats elements associated to this custom element definition as form-associated custom elements disable internals boolean Controls attachInternals() disable shadow boolean Controls attachShadow() To look up a custom element definition , given a document namespace localName , and is , perform the following steps. They will return either a custom element definition or null: If namespace is not the HTML namespace , return null. If document 's browsing context is null, return null. Let registry be document 's relevant global object 's CustomElementRegistry object. If there is custom element definition in registry with name and local name both equal to localName , return that custom element definition If there is a custom element definition in registry with name equal to is and local name equal to localName , return that custom element definition Return null. 4.13.4 The CustomElementRegistry interface Each Window object is associated with a unique instance of a CustomElementRegistry object, allocated when the Window object is created. Custom element registries are associated with Window objects, instead of Document objects, since each custom element constructor inherits from the HTMLElement interface, and there is exactly one HTMLElement interface per Window object. Window/customElements Support in all current engines. Firefox 63+ Safari 10.1+ Chrome 54+ Opera 41+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 63+ Safari iOS 10.3+ Chrome Android 54+ WebView Android 54+ Samsung Internet 6.0+ Opera Android 41+ The customElements attribute of the Window interface must return the CustomElementRegistry object for that Window object. CustomElementRegistry Support in all current engines. Firefox 63+ Safari 10.1+ Chrome 54+ Opera 41+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 63+ Safari iOS 10.3+ Chrome Android 54+ WebView Android 54+ Samsung Internet 6.0+ Opera Android 41+ Exposed Window interface CustomElementRegistry CEReactions undefined define DOMString name CustomElementConstructor constructor optional ElementDefinitionOptions options = {}); CustomElementConstructor or undefined get DOMString name ); Promise CustomElementConstructor whenDefined DOMString name ); CEReactions undefined upgrade Node root ); }; callback CustomElementConstructor HTMLElement (); dictionary ElementDefinitionOptions DOMString extends }; Every CustomElementRegistry has a set of custom element definitions , initially empty. In general, algorithms in this specification look up elements in the registry by any of name local name , or constructor Every CustomElementRegistry also has an element definition is running flag which is used to prevent reentrant invocations of element definition . It is initially unset. Every CustomElementRegistry also has a when-defined promise map mapping valid custom element names to promises. It is used to implement the whenDefined() method. window customElements define name constructor CustomElementRegistry/define Support in all current engines. Firefox 63+ Safari 10.1+ Chrome 67+ Opera 54+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 63+ Safari iOS 10.3+ Chrome Android 67+ WebView Android 67+ Samsung Internet 9.0+ Opera Android 48+ Defines a new custom element , mapping the given name to the given constructor as an autonomous custom element window customElements define name constructor { extends: baseLocalName }) Defines a new custom element , mapping the given name to the given constructor as customized built-in element for the element type identified by the supplied baseLocalName . A NotSupportedError DOMException will be thrown upon trying to extend a custom element or an unknown element. window customElements get name CustomElementRegistry/get Support in all current engines. Firefox 63+ Safari 10.1+ Chrome 67+ Opera 54+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 63+ Safari iOS 10.3+ Chrome Android 67+ WebView Android 67+ Samsung Internet 9.0+ Opera Android 48+ Retrieves the custom element constructor defined for the given name . Returns undefined if there is no custom element definition with the given name window customElements whenDefined name CustomElementRegistry/whenDefined Support in all current engines. Firefox 63+ Safari 10.1+ Chrome 67+ Opera 54+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 63+ Safari iOS 10.3+ Chrome Android 67+ WebView Android 67+ Samsung Internet 9.0+ Opera Android 48+ Returns a promise that will be fulfilled with the custom element 's constructor when a custom element becomes defined with the given name. (If such a custom element is already defined, the returned promise will be immediately fulfilled.) Returns a promise rejected with a SyntaxError DOMException if not given a valid custom element name window customElements upgrade root CustomElementRegistry/upgrade Support in all current engines. Firefox 63+ Safari 12.1+ Chrome 68+ Opera 55+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 63+ Safari iOS 12.2+ Chrome Android 68+ WebView Android 68+ Samsung Internet 10.0+ Opera Android 48+ Tries to upgrade all shadow-including inclusive descendant elements of root , even if they are not connected Element definition is a process of adding a custom element definition to the CustomElementRegistry . This is accomplished by the define() method. When invoked, the define( name constructor options method must run these steps: If IsConstructor constructor ) is false, then throw a TypeError If name is not a valid custom element name , then throw a SyntaxError DOMException If this CustomElementRegistry contains an entry with name name , then throw a NotSupportedError DOMException If this CustomElementRegistry contains an entry with constructor constructor then throw a NotSupportedError DOMException Let localName be name Let extends be the value of the extends member of options , or null if no such member exists. If extends is not null, then: If extends is a valid custom element name , then throw a NotSupportedError DOMException If the element interface for extends and the HTML namespace is HTMLUnknownElement (e.g., if extends does not indicate an element definition in this specification), then throw a NotSupportedError DOMException Set localName to extends If this CustomElementRegistry 's element definition is running flag is set, then throw a NotSupportedError DOMException Set this CustomElementRegistry 's element definition is running flag. Let formAssociated be false. Let disableInternals be false. Let disableShadow be false. Let observedAttributes be an empty sequence Run the following substeps while catching any exceptions: Let prototype be Get constructor "prototype"). Rethrow any exceptions. If Type prototype ) is not Object, then throw a TypeError exception. Let lifecycleCallbacks be a map with the keys " connectedCallback ", " disconnectedCallback ", " adoptedCallback ", and " attributeChangedCallback ", each of which belongs to an entry whose value is null. For each of the keys callbackName in lifecycleCallbacks , in the order listed in the previous step: Let callbackValue be Get prototype callbackName ). Rethrow any exceptions. If callbackValue is not undefined, then set the value of the entry in lifecycleCallbacks with key callbackName to the result of converting callbackValue to the Web IDL Function callback type. Rethrow any exceptions from the conversion. If the value of the entry in lifecycleCallbacks with key " attributeChangedCallback " is not null, then: Let observedAttributesIterable be Get constructor , "observedAttributes"). Rethrow any exceptions. If observedAttributesIterable is not undefined, then set observedAttributes to the result of converting observedAttributesIterable to a sequence . Rethrow any exceptions from the conversion. Let disabledFeatures be an empty sequence Let disabledFeaturesIterable be Get constructor , "disabledFeatures"). Rethrow any exceptions. If disabledFeaturesIterable is not undefined, then set disabledFeatures to the result of converting disabledFeaturesIterable to a sequence . Rethrow any exceptions from the conversion. Set disableInternals to true if disabledFeatures contains internals ". Set disableShadow to true if disabledFeatures contains shadow ". Let formAssociatedValue be Get constructor , "formAssociated"). Rethrow any exceptions. Set formAssociated to the result of converting formAssociatedValue to a boolean . Rethrow any exceptions from the conversion. If formAssociated is true, for each of formAssociatedCallback ", " formResetCallback ", formDisabledCallback ", and formStateRestoreCallback callbackName Let callbackValue be Get prototype callbackName ). Rethrow any exceptions. If callbackValue is not undefined, then set the value of the entry in lifecycleCallbacks with key callbackName to the result of converting callbackValue to the Web IDL Function callback type. Rethrow any exceptions from the conversion. Then, perform the following substep, regardless of whether the above steps threw an exception or not: Unset this CustomElementRegistry 's element definition is running flag. Finally, if the first set of substeps threw an exception, then rethrow that exception (thus terminating this algorithm). Otherwise, continue onward. Let definition be a new custom element definition with name name local name localName constructor constructor observed attributes observedAttributes lifecycle callbacks lifecycleCallbacks form-associated formAssociated disable internals disableInternals , and disable shadow disableShadow Add definition to this CustomElementRegistry Let document be this CustomElementRegistry 's relevant global object 's associated Document Let upgrade candidates be all elements that are shadow-including descendants of document , whose namespace is the HTML namespace and whose local name is localName , in shadow-including tree order . Additionally, if extends is non-null, only include elements whose is value is equal to name For each element element in upgrade candidates enqueue a custom element upgrade reaction given element and definition If this CustomElementRegistry 's when-defined promise map contains an entry with key name Let promise be the value of that entry. Resolve promise with constructor Delete the entry with key name from this CustomElementRegistry 's when-defined promise map When invoked, the get( name method must run these steps: If this CustomElementRegistry contains an entry with name name , then return that entry's constructor Otherwise, return undefined. When invoked, the whenDefined( name method must run these steps: If name is not a valid custom element name , then return a new promise rejected with a SyntaxError DOMException If this CustomElementRegistry contains an entry with name name , then return a new promise resolved with that entry's constructor Let map be this CustomElementRegistry 's when-defined promise map If map does not contain an entry with key name , create an entry in map with key name and whose value is a new promise. Let promise be the value of the entry in map with key name Return promise The whenDefined() method can be used to avoid performing an action until all appropriate custom elements are defined . In this example, we combine it with the :defined pseudo-class to hide a dynamically-loaded article's contents until we're sure that all of the autonomous custom elements it uses are defined. articleContainer hidden true fetch articleURL then response => response text ()) then text => articleContainer innerHTML text return Promise all [... articleContainer querySelectorAll ":not(:defined)" )] map el => customElements whenDefined el localName )) ); }) then (() => articleContainer hidden false }); When invoked, the upgrade( root method must run these steps: Let candidates be a list of all of root 's shadow-including inclusive descendant elements, in shadow-including tree order For each candidate of candidates try to upgrade candidate The upgrade() method allows upgrading of elements at will. Normally elements are automatically upgraded when they become connected , but this method can be used if you need to upgrade before you're ready to connect the element. const el document createElement "spider-man" ); class SpiderMan extends HTMLElement {} customElements define "spider-man" SpiderMan ); console assert el instanceof SpiderMan )); // not yet upgraded customElements upgrade el ); console assert el instanceof SpiderMan ); // upgraded! 4.13.5 Upgrades To upgrade an element , given as input a custom element definition definition and an element element run the following steps: If element 's custom element state is not " undefined " or " uncustomized ", then return. One scenario where this can occur due to reentrant invocation of this algorithm, as in the following example: x-foo id "a" > x-foo x-foo id "b" > x-foo script // Defining enqueues upgrade reactions for both "a" and "b" customElements define "x-foo" class extends HTMLElement constructor () super (); const document querySelector "#b" ); remove (); // While this constructor is running for "a", "b" is still // undefined, and so inserting it into the document will enqueue a // second upgrade reaction for "b" in addition to the one enqueued // by defining x-foo. document body appendChild ); }) script This step will thus bail out the algorithm early when upgrade an element is invoked with " " a second time. Set element 's custom element definition to definition Set element 's custom element state to " failed ". It will be set to " custom after the upgrade succeeds . For now, we set it to " failed " so that any reentrant invocations will hit the above early-exit step For each attribute in element 's attribute list , in order, enqueue a custom element callback reaction with element , callback name " attributeChangedCallback ", and an argument list containing attribute 's local name, null, attribute 's value, and attribute 's namespace. If element is connected , then enqueue a custom element callback reaction with element , callback name " connectedCallback ", and an empty argument list. Add element to the end of definition 's construction stack Let be definition 's constructor Run the following substeps while catching any exceptions: If definition 's disable shadow is true and element 's shadow root is non-null, then throw a NotSupportedError DOMException This is needed as attachShadow() does not use look up a custom element definition while attachInternals() does. Set element 's custom element state to " precustomized ". Let constructResult be the result of constructing , with no arguments. If non-conformantly uses an API decorated with the [CEReactions] extended attribute, then the reactions enqueued at the beginning of this algorithm will execute during this step, before finishes and control returns to this algorithm. Otherwise, they will execute after and the rest of the upgrade process finishes. If SameValue constructResult element ) is false, then throw a TypeError This can occur if constructs another instance of the same custom element before calling super() , or if uses JavaScript's return -override feature to return an arbitrary HTMLElement object from the constructor. Then, perform the following substep, regardless of whether the above steps threw an exception or not: Remove the last entry from the end of definition 's construction stack Assuming calls super() (as it will if it is conformant ), and that the call succeeds, this will be the already constructed marker that replaced the element we pushed at the beginning of this algorithm. (The HTML element constructor carries out this replacement.) If does not call super() (i.e. it is not conformant ), or if any step in the HTML element constructor throws, then this entry will still be element Finally, if the above steps threw an exception, then: Set element 's custom element definition to null. Empty element 's custom element reaction queue Rethrow the exception (thus terminating this algorithm). If the above steps threw an exception, then element 's custom element state will remain " failed " or " precustomized ". If element is a form-associated custom element , then: Reset the form owner of element . If element is associated with a form element, then enqueue a custom element callback reaction with element , callback name " formAssociatedCallback ", and « the associated form ». If element is disabled , then enqueue a custom element callback reaction with element , callback name formDisabledCallback " and « true ». Set element 's custom element state to " custom ". To try to upgrade an element , given as input an element element , run the following steps: Let definition be the result of looking up a custom element definition given element 's node document element 's namespace, element 's local name, and element 's is value If definition is not null, then enqueue a custom element upgrade reaction given element and definition 4.13.6 Custom element reactions custom element possesses the ability to respond to certain occurrences by running author code: When upgraded , its constructor is run, with no arguments. When it becomes connected , its connectedCallback is called, with no arguments. When it becomes disconnected , its disconnectedCallback is called, with no arguments. When it is adopted into a new document, its adoptedCallback is called, given the old document and new document as arguments. When any of its attributes are changed appended removed , or replaced , its attributeChangedCallback is called, given the attribute's local name, old value, new value, and namespace as arguments. (An attribute's old or new value is considered to be null when the attribute is added or removed, respectively.) When the user agent resets the form owner of a form-associated custom element and doing so changes the form owner, its formAssociatedCallback is called, given the new form owner (or null if no owner) as an argument. When the form owner of a form-associated custom element is reset , its formResetCallback is called. When the disabled state of a form-associated custom element is changed, its formDisabledCallback is called, given the new state as an argument. When user agent updates a form-associated custom element 's value on behalf of a user, its formStateRestoreCallback is called, given the new value and a string indicating a reason, " restore " or " autocomplete ", as arguments. We call these reactions collectively custom element reactions The way in which custom element reactions are invoked is done with special care, to avoid running author code during the middle of delicate operations. Effectively, they are delayed until "just before returning to user script". This means that for most purposes they appear to execute synchronously, but in the case of complicated composite operations (like cloning , or range manipulation), they will instead be delayed until after all the relevant user agent processing steps have completed, and then run together as a batch. Additionally, the precise ordering of these reactions is managed via a somewhat-complicated stack-of-queues system, described below. The intention behind this system is to guarantee that custom element reactions always are invoked in the same order as their triggering actions, at least within the local context of a single custom element . (Because custom element reaction code can perform its own mutations, it is not possible to give a global ordering guarantee across multiple elements.) Each similar-origin window agent has a custom element reactions stack which is initially empty. A similar-origin window agent 's current element queue is the element queue at the top of its custom element reactions stack . Each item in the stack is an element queue , which is initially empty as well. Each item in an element queue is an element. (The elements are not necessarily custom yet, since this queue is used for upgrades as well.) Each custom element reactions stack has an associated backup element queue , which an initially-empty element queue . Elements are pushed onto the backup element queue during operations that affect the DOM without going through an API decorated with [CEReactions] , or through the parser's create an element for the token algorithm. An example of this is a user-initiated editing operation which modifies the descendants or attributes of an editable element. To prevent reentrancy when processing the backup element queue , each custom element reactions stack also has a processing the backup element queue flag, initially unset. All elements have an associated custom element reaction queue , initially empty. Each item in the custom element reaction queue is of one of two types: An upgrade reaction , which will upgrade the custom element and contains a custom element definition ; or callback reaction , which will call a lifecycle callback, and contains a callback function as well as a list of arguments. This is all summarized in the following schematic diagram: To enqueue an element on the appropriate element queue , given an element element , run the following steps: Let reactionsStack be element 's relevant agent 's custom element reactions stack If reactionsStack is empty, then: Add element to reactionsStack 's backup element queue If reactionsStack 's processing the backup element queue flag is set, then return. Set reactionsStack 's processing the backup element queue flag. Queue a microtask to perform the following steps: Invoke custom element reactions in reactionsStack 's backup element queue Unset reactionsStack 's processing the backup element queue flag. Otherwise, add element to element 's relevant agent 's current element queue To enqueue a custom element callback reaction , given a custom element element , a callback name callbackName , and a list of arguments args , run the following steps: Let definition be element 's custom element definition Let callback be the value of the entry in definition 's lifecycle callbacks with key callbackName If callback is null, then return If callbackName is " attributeChangedCallback ", then: Let attributeName be the first element of args If definition 's observed attributes does not contain attributeName , then return. Add a new callback reaction to element 's custom element reaction queue , with callback function callback and arguments args Enqueue an element on the appropriate element queue given element To enqueue a custom element upgrade reaction , given an element element and custom element definition definition , run the following steps: Add a new upgrade reaction to element 's custom element reaction queue , with custom element definition definition Enqueue an element on the appropriate element queue given element To invoke custom element reactions in an element queue queue , run the following steps: While queue is not empty Let element be the result of dequeuing from queue Let reactions be element 's custom element reaction queue Repeat until reactions is empty: Remove the first element of reactions , and let reaction be that element. Switch on reaction 's type: upgrade reaction Upgrade element using reaction 's custom element definition callback reaction Invoke reaction 's callback function with reaction 's arguments, and with element as the callback this value If this throws an exception, catch it, and report the exception To ensure custom element reactions are triggered appropriately, we introduce the [CEReactions] IDL extended attribute . It indicates that the relevant algorithm is to be supplemented with additional steps in order to appropriately track and invoke custom element reactions The [CEReactions] extended attribute must take no arguments, and must not appear on anything other than an operation, attribute, setter, or deleter. Additionally, it must not appear on readonly attributes. Operations, attributes, setters, or deleters annotated with the [CEReactions] extended attribute must run the following steps in place of the ones specified in their description: Push a new element queue onto this object's relevant agent 's custom element reactions stack Run the originally-specified steps for this construct, catching any exceptions. If the steps return a value, let value be the returned value. If they throw an exception, let exception be the thrown exception. Let queue be the result of popping from this object's relevant agent 's custom element reactions stack Invoke custom element reactions in queue If an exception exception was thrown by the original steps, rethrow exception If a value value was returned from the original steps, return value The intent behind this extended attribute is somewhat subtle. One way of accomplishing its goals would be to say that every operation, attribute, setter, and deleter on the platform must have these steps inserted, and to allow implementers to optimize away unnecessary cases (where no DOM mutation is possible that could cause custom element reactions to occur). However, in practice this imprecision could lead to non-interoperable implementations of custom element reactions , as some implementations might forget to invoke these steps in some cases. Instead, we settled on the approach of explicitly annotating all relevant IDL constructs, as a way of ensuring interoperable behavior and helping implementations easily pinpoint all cases where these steps are necessary. Any nonstandard APIs introduced by the user agent that could modify the DOM in such a way as to cause enqueuing a custom element callback reaction or enqueuing a custom element upgrade reaction , for example by modifying any attributes or child elements, must also be decorated with the [CEReactions] attribute. As of the time of this writing, the following nonstandard or not-yet-standardized APIs are known to fall into this category: HTMLInputElement 's webkitdirectory and incremental IDL attributes HTMLLinkElement 's scope IDL attribute 4.13.7 Element internals Certain capabilities are meant to be available to a custom element author, but not to a custom element consumer. These are provided by the element.attachInternals() method, which returns an instance of ElementInternals . The properties and methods of ElementInternals allow control over internal features which the user agent provides to all elements. element attachInternals() Returns an ElementInternals object targeting the custom element element . Throws an exception if element is not a custom element , if the " internals " feature was disabled as part of the element definition, or if it is called twice on the same element. Each HTMLElement has an attached internals boolean, initially false. The attachInternals() method steps are: If this 's is value is not null, then throw a NotSupportedError DOMException Let definition be the result of looking up a custom element definition given this's node document , its namespace, its local name, and null as the is value If definition is null, then throw an NotSupportedError DOMException If definition 's disable internals is true, then throw a NotSupportedError DOMException If this 's attached internals is true, then throw an NotSupportedError DOMException If this 's custom element state is not " precustomized " or " custom ", then throw a NotSupportedError DOMException Set this 's attached internals to true. Return a new ElementInternals instance whose target element is this 4.13.7.1 The ElementInternals interface The IDL for the ElementInternals interface is as follows, with the various operations and attributes defined in the following sections: Exposed Window interface ElementInternals // Shadow root access readonly attribute ShadowRoot shadowRoot
// Form-associated custom elements undefined setFormValue (( File or USVString or FormData )? value optional File or USVString or FormData )? state ); readonly attribute HTMLFormElement form undefined setValidity optional ValidityStateFlags flags = {}, optional DOMString message optional HTMLElement anchor ); readonly attribute boolean willValidate readonly attribute ValidityState validity readonly attribute DOMString validationMessage boolean checkValidity (); boolean reportValidity (); readonly attribute NodeList labels };
// Accessibility semantics ElementInternals includes ARIAMixin dictionary ValidityStateFlags boolean valueMissing false boolean typeMismatch false boolean patternMismatch false boolean tooLong false boolean tooShort false boolean rangeUnderflow false boolean rangeOverflow false boolean stepMismatch false boolean badInput false boolean customError false }; Each ElementInternals has a target element which is a custom element 4.13.7.2 Shadow root access internals shadowRoot Returns the ShadowRoot for internals 's target element , if the target element is a shadow host , or null otherwise. The shadowRoot getter steps are: Let target be this 's target element If target is not a shadow host , then return null. Let shadow be target 's shadow root If shadow 's available to element internals is false, then return null. Return shadow 4.13.7.3 Form-associated custom elements internals setFormValue value Sets both the state and submission value of internals 's target element to value If value is null, the element won't participate in form submission. internals setFormValue value state Sets the submission value of internals 's target element to value , and its state to state If value is null, the element won't participate in form submission. internals form Returns the form owner of internals 's target element internals setValidity flags message [, anchor ]) Marks internals 's target element as suffering from the constraints indicated by the flags argument, and sets the element's validation message to message . If anchor is specified, the user agent might use it to indicate problems with the constraints of internals 's target element when the form owner is validated interactively or reportValidity() is called. internals setValidity ({}) Marks internals 's target element as satisfying its constraints internals willValidate Returns true if internals 's target element will be validated when the form is submitted; false otherwise. internals validity Returns the ValidityState object for internals 's target element internals validationMessage Returns the error message that would be shown to the user if internals 's target element was to be checked for validity. valid internals checkValidity() Returns true if internals 's target element has no validity problems; false otherwise. Fires an invalid event at the element in the latter case. valid internals reportValidity() Returns true if internals 's target element has no validity problems; otherwise, returns false, fires an invalid event at the element, and (if the event isn't canceled) reports the problem to the user. internals labels Returns a NodeList of all the label elements that internals 's target element is associated with. Each form-associated custom element has submission value . It is used to provide one or more entries on form submission. The initial value of submission value is null, and submission value can be null, a string, a File , or a list of entries Each form-associated custom element has state It is information with which the user agent can restore a user's input for the element. The initial value of state is null, and state can be null, a string, a File , or a list of entries The setFormValue() method is used by the custom element author to set the element's submission value and state , thus communicating these to the user agent. When the user agent believes it is a good idea to restore a form-associated custom element 's state , for example after navigation or restarting the user agent, they may enqueue a custom element callback reaction with that element, callback name " formStateRestoreCallback ", and an argument list containing the state to be restored, and "restore" If the user agent has a form-filling assist feature, then when the feature is invoked, it may enqueue a custom element callback reaction with form-associated custom element , callback name formStateRestoreCallback ", and an argument list containing the state value determined by history of state value and some heuristics, and "autocomplete" In general, the state is information specified by a user, and the submission value is a value after canonicalization or sanitization, suitable for submission to the server. The following examples makes this concrete: Suppose that we have a form-associated custom element which asks a user to specify a date. The user specifies "3/15/2019" , but the control wishes to submit "2019-03-15" to the server. "3/15/2019" would be a state of the element, and "2019-03-15" would be submission value Suppose you develop a custom element emulating a the behavior of the existing checkbox input type. Its submission value would be the value of its value content attribute, or the string "on" . Its state would be one of "checked" "unchecked" "checked/indeterminate" , or "unchecked/indeterminate" The setFormValue( value state method steps are: Let element be this 's target element If element is not a form-associated custom element , then throw a NotSupportedError DOMException Set target element 's submission value to value if value is not a FormData object, or to a clone of the entry list associated with value otherwise. If the state argument of the function is omitted, set element 's state to its submission value Otherwise, if state is a FormData object, set element 's state to clone of the entry list associated with state Otherwise, set element 's state to state Each form-associated custom element has validity flags named valueMissing typeMismatch patternMismatch tooLong tooShort rangeUnderflow rangeOverflow stepMismatch , and customError . They are false initially. Each form-associated custom element has a validation message string. It is the empty string initially. Each form-associated custom element has a validation anchor element. It is null initially. The setValidity( flags message anchor method steps are: Let element be this 's target element If element is not a form-associated custom element , then throw a NotSupportedError DOMException If flags contains one or more true values and message is not given or is the empty string, then throw a TypeError For each entry flag value of flags , set element 's validity flag with the name flag to value Set element 's validation message to the empty string if message is not given or all of element 's validity flags are false, or to message otherwise. If element 's customError validity flag is true, then set element 's custom validity error message to element 's validation message . Otherwise, set element 's custom validity error message to the empty string. Set element 's validation anchor to null if anchor is not given. Otherwise, if anchor is not a shadow-including descendant of element , then throw a NotFoundError DOMException . Otherwise, set element 's validation anchor to anchor The validationMessage getter steps are to return the validation message of this 's target element The entry construction algorithm for a form-associated custom element , given an element element and a list entry list , consists of the following steps: If element 's submission value is a list of entries , then append each item of element 's submission value to entry list , and return. In this case, user agent does not refer to the name content attribute value. An implementation of form-associated custom element is responsible to decide names of entries . They can be the name content attribute value, they can be strings based on the name content attribute value, or they can be unrelated to the name content attribute. If the element does not have a name attribute specified, or its name attribute's value is the empty string, then return. If the element's submission value is not null, append an entry to entry list with the name attribute value and the submission value 4.13.7.4 Accessibility semantics internals role [ = value Sets or retrieves the default ARIA role for internals 's target element , which will be used unless the page author overrides it using the role attribute. internals aria* [ = value Sets or retrieves various default ARIA states or property values for internals 's target element , which will be used unless the page author overrides them using the aria-* attributes. By using the role and aria* properties of ElementInternals , custom element authors can set default accessibile roles, states, and property values for their custom element, similar to how native elements behave. See the example above for more details. Each custom element has a native accessibility semantics map , which is map , initially empty. See the Requirements related to ARIA and to platform accessibility APIs section for information on how this impacts platform accessibility APIs. ElementInternals includes the ARIAMixin mixin. The accessors provided by this mixin are used to manipulate the target element 's native accessibility semantics map , as follows: The ARIAMixin getter steps for ElementInternals , given internals idlAttribute , and contentAttribute , are: Let map be internals 's target element 's native accessibility semantics map If map contentAttribute exists then return it. Return null. The ARIAMixin setter steps for ElementInternals , given internals idlAttribute contentAttribute , and value , are: Let map be internals 's target element 's native accessibility semantics map If value is null, then remove map contentAttribute ]. Otherwise, set map contentAttribute to value 4.14 Common idioms without dedicated elements 4.14.1 Bread crumb navigation This specification does not provide a machine-readable way of describing bread-crumb navigation menus. Authors are encouraged to just use a series of links in a paragraph. The nav element can be used to mark the section containing these paragraphs as being navigation blocks. In the following example, the current page can be reached via two paths. nav href "/" Main href "/products/" Products href "/products/dishwashers/" Dishwashers Second hand href "/" Main href "/second-hand/" Second hand Dishwashers nav 4.14.2 Tag clouds This specification does not define any markup specifically for marking up lists of keywords that apply to a group of pages (also known as tag clouds ). In general, authors are encouraged to either mark up such lists using ul elements with explicit inline counts that are then hidden and turned into a presentational effect using a style sheet, or to use SVG. Here, three tags are included in a short tag cloud: style tag-cloud li span display none tag-cloud li display inline tag-cloud-1 font-size 0.7 em tag-cloud-2 font-size 0.9 em tag-cloud-3 font-size 1.1 em tag-cloud-4 font-size 1.3 em tag-cloud-5 font-size 1.5 em media speech tag-cloud li span display inline style ... ul class "tag-cloud" li class "tag-cloud-4" >< title "28 instances" href "/t/apple" apple span (popular) span li class "tag-cloud-2" >< title "6 instances" href "/t/kiwi" kiwi span (rare) span li class "tag-cloud-5" >< title "41 instances" href "/t/pear" pear span (very popular) span ul The actual frequency of each tag is given using the title attribute. A CSS style sheet is provided to convert the markup into a cloud of differently-sized words, but for user agents that do not support CSS or are not visual, the markup contains annotations like "(popular)" or "(rare)" to categorize the various tags by frequency, thus enabling all users to benefit from the information. The ul element is used (rather than ol ) because the order is not particularly important: while the list is in fact ordered alphabetically, it would convey the same information if ordered by, say, the length of the tag. The tag rel -keyword is not used on these elements because they do not represent tags that apply to the page itself; they are just part of an index listing the tags themselves. 4.14.3 Conversations This specification does not define a specific element for marking up conversations, meeting minutes, chat transcripts, dialogues in screenplays, instant message logs, and other situations where different players take turns in discourse. Instead, authors are encouraged to mark up conversations using elements and punctuation. Authors who need to mark the speaker for styling purposes are encouraged to use span or . Paragraphs with their text wrapped in the element can be used for marking up stage directions. This example demonstrates this using an extract from Abbot and Costello's famous sketch, Who's on first Costello: Look, you gotta first baseman? Abbott: Certainly. Costello: Who's playing first? Abbott: That's right. Costello becomes exasperated. Costello: When you pay off the first baseman every month, who gets the money? Abbott: Every dollar of it. The following extract shows how an IM conversation log could be marked up, using the data element to provide Unix timestamps for each line. Note that the timestamps are provided in a format that the time element does not support, so the data element is used instead (namely, Unix time_t timestamps). Had the author wished to mark up the data using one of the date and time formats supported by the time element, that element could have been used instead of data . This could be advantageous as it would allow data analysis tools to detect the timestamps unambiguously, without coordination with the page author. data value "1319898155" 14:22 data egof I'm not that nerdy, I've only seen 30% of the star trek episodes data value "1319898192" 14:23 data kaj if you know what percentage of the star trek episodes you have seen, you are inarguably nerdy data value "1319898200" 14:23 data egof it's unarguably data value "1319898228" 14:23 data * kaj blinks data value "1319898260" 14:24 data kaj you are not helping your case HTML does not have a good way to mark up graphs, so descriptions of interactive conversations from games are more difficult to mark up. This example shows one possible convention using dl elements to list the possible responses at each point in the conversation. Another option to consider is describing the conversation in the form of a DOT file, and outputting the result as an SVG image to place in the document. [DOT] Next, you meet a fisher. You can say one of several greetings: dl dt "Hello there!" dd She responds with "Hello, how may I help you?"; you can respond with: dl dt "I would like to buy a fish." dd She sells you a fish and the conversation finishes. dt "Can I borrow your boat?" dd She is surprised and asks "What are you offering in return?". dl dt "Five gold." (if you have enough) dt "Ten gold." (if you have enough) dt "Fifteen gold." (if you have enough) dd She lends you her boat. The conversation ends. dt "A fish." (if you have one) dt "A newspaper." (if you have one) dt "A pebble." (if you have one) dd "No thanks", she replies. Your conversation options at this point are the same as they were after asking to borrow her boat, minus any options you've suggested before. dl dd dl dd dt "Vote for me in the next election!" dd She turns away. The conversation finishes. dt "Madam, are you aware that your fish are running away?" dd She looks at you skeptically and says "Fish cannot run, miss". dl dt "You got me!" dd The fisher sighs and the conversation ends. dt "Only kidding." dd "Good one!" she retorts. Your conversation options at this point are the same as those following "Hello there!" above. dt "Oh, then what are they doing?" dd She looks at her fish, giving you an opportunity to steal her boat, which you do. The conversation ends. dl dd dl In some games, conversations are simpler: each character merely has a fixed set of lines that they say. In this example, a game FAQ/walkthrough lists some of the known possible responses for each character: section h1 Dialogue h1 >< small Some characters repeat their lines in order each time you interact with them, others randomly pick from amongst their lines. Those who respond in order have numbered entries in the lists below. small h2 The Shopkeeper h2 ul li How may I help you? li Fresh apples! li A loaf of bread for madam? ul h2 The pilot h2 Before the accident: ul li I'm about to fly out, sorry! li Sorry, I'm just waiting for flight clearance and then I'll be off! ul After the accident: ol li I'm about to fly out, sorry! li Ok, I'm not leaving right now, my plane is being cleaned. li Ok, it's not being cleaned, it needs a minor repair first. li Ok, ok, stop bothering me! Truth is, I had a crash. ol h2 Clan Leader h2 During the first clan meeting: ul li Hey, have you seen my daughter? I bet she's up to something nefarious again... li Nice weather we're having today, eh? li The name is Bailey, Jeff Bailey. How can I help you today? li A glass of water? Fresh from the well! ul After the earthquake: ol li Everyone is safe in the shelter, we just have to put out the fire! li I'll go and tell the fire brigade, you keep hosing it down! ol section 4.14.4 Footnotes HTML does not have a dedicated mechanism for marking up footnotes. Here are the suggested alternatives. For short inline annotations, the title attribute could be used. In this example, two parts of a dialogue are annotated with footnote-like content using the title attribute. Customer : Hello! I wish to register a complaint. Hello. Miss? Shopkeeper span title "Colloquial pronunciation of 'What do you'" Watcha span mean, miss? Customer : Uh, I'm sorry, I have a cold. I wish to make a complaint. Shopkeeper : Sorry, span title "This is, of course, a lie." we're closing for lunch span Unfortunately, relying on the title attribute is currently discouraged as many user agents do not expose the attribute in an accessible manner as required by this specification (e.g. requiring a pointing device such as a mouse to cause a tooltip to appear, which excludes keyboard-only users and touch-only users, such as anyone with a modern phone or tablet). If the title attribute is used, CSS can be used to draw the reader's attention to the elements with the attribute. For example, the following CSS places a dashed line below elements that have a title attribute. [title] border-bottom thin dashed For longer annotations, the element should be used, pointing to an element later in the document. The convention is that the contents of the link be a number in square brackets. In this example, a footnote in the dialogue links to a paragraph below the dialogue. The paragraph then reciprocally links back to the dialogue, allowing the user to return to the location of the footnote. Announcer: Number 16: The hand Interviewer: Good evening. I have with me in the studio tonight Mr Norman St John Polevaulter, who for the past few years has been contradicting people. Mr Polevaulter, why em do em you contradict people? Norman: I don't. sup >< href "#fn1" id "r1" [1] > sup Interviewer: You told me you did! ... section id "fn1" >< href "#r1" [1] This is, naturally, a lie, but paradoxically if it were true he could not say so without contradicting the interviewer and thus making it false. section For side notes, longer annotations that apply to entire sections of the text rather than just specific words or sentences, the aside element should be used. In this example, a sidebar is given after a dialogue, giving it some context. span class "speaker" Customer span : I will not buy this record, it is scratched. span class "speaker" Shopkeeper span : I'm sorry? span class "speaker" Customer span : I will not buy this record, it is scratched. span class "speaker" Shopkeeper span : No no no, this's'a tobacconist's. aside In 1970, the British Empire lay in ruins, and foreign nationalists frequented the streets — many of them Hungarians (not the streets — the foreign nationals). Sadly, Alexander Yalt has been publishing incompetently-written phrase books. aside For figures or tables, footnotes can be included in the relevant figcaption or caption element, or in surrounding prose. In this example, a table has cells with footnotes that are given in prose. A figure element is used to give a single legend to the combination of the table and its footnotes. figure figcaption Table 1. Alternative activities for knights. figcaption table tr th Activity th Location th Cost tr td Dance td Wherever possible td £0 sup >< href "#fn1" > sup tr td Routines, chorus scenes sup >< href "#fn2" > sup td Undisclosed td Undisclosed tr td Dining sup >< href "#fn3" > sup td Camelot td Cost of ham, jam, and spam sup >< href "#fn4" > sup table id "fn1" 1. Assumed. id "fn2" 2. Footwork impeccable. id "fn3" 3. Quality described as "well". id "fn4" 4. A lot. figure 4.15 Disabled elements An element is said to be actually disabled if it is one of the following: button element that is disabled an input element that is disabled select element that is disabled textarea element that is disabled an optgroup element that has a disabled attribute an option element that is disabled fieldset element that is a disabled fieldset form-associated custom element that is disabled This definition is used to determine what elements are focusable and which elements match the :enabled and :disabled pseudo classes 4.16 Matching HTML elements using selectors and CSS 4.16.1 Case-sensitivity of the CSS 'attr()' function CSS Values and Units leaves the case-sensitivity of attribute names for the purpose of the 'attr()' function to be defined by the host language. [CSSVALUES] When comparing the attribute name part of a CSS 'attr()' function to the names of namespace-less attributes on HTML elements in HTML documents , the name part of the CSS 'attr()' function must first be converted to ASCII lowercase . The same function when compared to other attributes must be compared according to its original case. In both cases, to match the values must be identical to each other (and therefore the comparison is case sensitive). This is the same as comparing the name part of a CSS attribute selector , specified in the next section. 4.16.2 Case-sensitivity of selectors Selectors leaves the case-sensitivity of element names, attribute names, and attribute values to be defined by the host language. [SELECTORS] When comparing a CSS element type selector to the names of HTML elements in HTML documents , the CSS element type selector must first be converted to ASCII lowercase . The same selector when compared to other elements must be compared according to its original case. In both cases, to match the values must be identical to each other (and therefore the comparison is case sensitive). When comparing the name part of a CSS attribute selector to the names of attributes on HTML elements in HTML documents , the name part of the CSS attribute selector must first be converted to ASCII lowercase . The same selector when compared to other attributes must be compared according to its original case. In both cases, the comparison is case-sensitive. Attribute selectors on an HTML element in an HTML document must treat the values of attributes with the following names as ASCII case-insensitive accept accept-charset align alink axis bgcolor charset checked clear codetype color compact declare defer dir direction disabled enctype face frame hreflang http-equiv lang language link media method multiple nohref noresize noshade nowrap readonly rel rev rules scope scrolling selected shape target text type valign valuetype vlink For example, the selector [bgcolor="#ffffff"] will match any HTML element with a bgcolor attribute with values including #ffffff #FFFFFF and #fffFFF . This happens even if bgcolor has no effect for a given element (e.g., div ). The selector [type=a s] will match any HTML element with a type attribute whose value is , but not whose value is , due to the flag. All other attribute values and everything else must be treated as entirely identical to each other for the purposes of selector matching. This includes: IDs and classes in no-quirks mode and limited-quirks mode the names of elements not in the HTML namespace the names of HTML elements in XML documents the names of attributes of elements not in the HTML namespace the names of attributes of HTML elements in XML documents the names of attributes that themselves have namespaces Selectors defines that ID and class selectors (such as #foo and .bar ), when matched against elements in documents that are in quirks mode , will be matched in an ASCII case-insensitive manner. However, this does not apply for attribute selectors with " id " or class " as the name part. The selector [class="foobar"] will treat its value as case-sensitive even in quirks mode 4.16.3 Pseudo-classes Pseudo-classes There are a number of dynamic selectors that can be used with HTML. This section defines when these selectors match HTML elements. [SELECTORS] [CSSUI] :defined :defined Support in all current engines. Firefox 63+ Safari 10+ Chrome 54+ Opera 41+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 63+ Safari iOS 10+ Chrome Android 54+ WebView Android 54+ Samsung Internet 6.0+ Opera Android 41+ The :defined pseudo-class must match any element that is defined :link :link Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 3.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 3+ Firefox Android 4+ Safari iOS 3.2+ Chrome Android 18+ WebView Android 1.5+ Samsung Internet 1.0+ Opera Android 14+ :visited :visited Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 3.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 4.4+ Samsung Internet 1.0+ Opera Android 10.1+ All elements that have an href attribute, and all area elements that have an href attribute, must match one of :link and :visited Other specifications might apply more specific rules regarding how these elements are to match these pseudo-classes , to mitigate some privacy concerns that apply with straightforward implementations of this requirement. :active :active Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 10.1+ The :active pseudo-class is defined to match an element while an element is being activated by the user To determine whether a particular element is being activated for the purposes of defining the :active pseudo-class only, an HTML user agent must use the first relevant entry in the following list. If the element has a descendant that is currently matching the :active pseudo-class The element is being activated If the element is the labeled control of a label element that is currently matching :active The element is being activated If the element is a button element If the element is an input element whose type attribute is in the Submit Button Image Button Reset Button , or Button state The element is being activated if it is in a formal activation state and it is not disabled For example, if the user is using a keyboard to push a button element by pressing the space bar, the element would match this pseudo-class in between the time that the element received the keydown event and the time the element received the keyup event. If the element is an element that has an href attribute If the element is an area element that has an href attribute If the element is a link element that has an href attribute If the element is focusable The element is being activated if it is in a formal activation state If the element is being actively pointed at The element is being activated An element is said to be in a formal activation state between the time the user begins to indicate an intent to trigger the element's activation behavior and either the time the user stops indicating an intent to trigger the element's activation behavior , or the time the element's activation behavior has finished running, which ever comes first. An element is said to be being actively pointed at while the user indicates the element using a pointing device while that pointing device is in the "down" state (e.g. for a mouse, between the time the mouse button is pressed and the time it is depressed; for a finger in a multitouch environment, while the finger is touching the display surface). :hover :hover Support in all current engines. Firefox 1+ Safari 2+ Chrome 1+ Opera 4+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 10.1+ The :hover pseudo-class is defined to match an element while the user designates an element with a pointing device . For the purposes of defining the :hover pseudo-class only, an HTML user agent must consider an element as being one that the user designates if it is: An element that the user indicates using a pointing device. An element that has a descendant that the user indicates using a pointing device. An element that is the labeled control of a label element that is currently matching :hover Consider in particular a fragment such as: label for input id label span id input id span If the user designates the element with ID " " with their pointing device, then the element (and all its ancestors not shown in the snippet above), the label element, the element with ID " ", and the element with ID " " will match the :hover pseudo-class . The element with ID " " matches it from condition 1, the label and elements match it because of condition 2 (one of their descendants is designated), and the element with ID " matches it through condition 3 (its label element matches :hover ). However, the element with ID " does not match :hover : its descendant is not designated, even though it matches :hover :focus :focus Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 7+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 8+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 10.1+ For the purposes of the CSS :focus pseudo-class , an element has the focus when: it is not itself a browsing context container ; and at least one of the following is true: it is one of the elements listed in the current focus chain of the top-level browsing context or its shadow root shadowRoot is not null and shadowRoot is the root of at least one element that has the focus :target :target Support in all current engines. Firefox 1+ Safari 1.3+ Chrome 1+ Opera 9.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 4+ Safari iOS 2+ Chrome Android 18+ WebView Android 2+ Samsung Internet 1.0+ Opera Android 10.1+ For the purposes of the CSS :target pseudo-class , the Document 's target elements are a list containing the Document 's target element , if it is not null, or containing no elements, if it is. [SELECTORS] :enabled :enabled Support in all current engines. Firefox 1+ Safari 3.1+ Chrome 1+ Opera 9+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 4+ Safari iOS 3.1+ Chrome Android 18+ WebView Android 2+ Samsung Internet 1.0+ Opera Android 10.1+ The :enabled pseudo-class must match any button input select textarea optgroup option fieldset element, or form-associated custom element that is not actually disabled :disabled :disabled Support in all current engines. Firefox 1+ Safari 3.1+ Chrome 1+ Opera 9+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 4+ Safari iOS 3.1+ Chrome Android 18+ WebView Android 2+ Samsung Internet 1.0+ Opera Android 10.1+ The :disabled pseudo-class must match any element that is actually disabled :checked :checked Support in all current engines. Firefox 1+ Safari 3.1+ Chrome 1+ Opera 9+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 4+ Safari iOS 3.1+ Chrome Android 18+ WebView Android 2+ Samsung Internet 1.0+ Opera Android 10.1+ The :checked pseudo-class must match any element falling into one of the following categories: input elements whose type attribute is in the Checkbox state and whose checkedness state is true input elements whose type attribute is in the Radio Button state and whose checkedness state is true option elements whose selectedness is true :indeterminate :indeterminate Support in all current engines. Firefox 2+ Safari 3+ Chrome 1+ Opera 9+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 10.1+ The :indeterminate pseudo-class must match any element falling into one of the following categories: input elements whose type attribute is in the Checkbox state and whose indeterminate IDL attribute is set to true input elements whose type attribute is in the Radio Button state and whose radio button group contains no input elements whose checkedness state is true. progress elements with no value content attribute :default :default Support in all current engines. Firefox 4+ Safari 5+ Chrome 10+ Opera 10+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 4+ Safari iOS 5+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 10.1+ The :default pseudo-class must match any element falling into one of the following categories: Submit buttons that are default buttons of their form owner input elements to which the checked attribute applies and that have a checked attribute option elements that have a selected attribute :placeholder-shown The :placeholder-shown pseudo-class must match any element falling into one of the following categories: input elements that have a placeholder attribute whose value is currently being presented to the user. textarea elements that have a placeholder attribute whose value is currently being presented to the user. :valid :valid Support in all current engines. Firefox 4+ Safari 5+ Chrome 10+ Opera 10+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 5+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 10.1+ The :valid pseudo-class must match any element falling into one of the following categories: elements that are candidates for constraint validation and that satisfy their constraints form elements that are not the form owner of any elements that themselves are candidates for constraint validation but do not satisfy their constraints fieldset elements that have no descendant elements that themselves are candidates for constraint validation but do not satisfy their constraints :invalid :invalid Support in all current engines. Firefox 4+ Safari 5+ Chrome 10+ Opera 10+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 5+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 10.1+ The :invalid pseudo-class must match any element falling into one of the following categories: elements that are candidates for constraint validation but that do not satisfy their constraints form elements that are the form owner of one or more elements that themselves are candidates for constraint validation but do not satisfy their constraints fieldset elements that have of one or more descendant elements that themselves are candidates for constraint validation but do not satisfy their constraints :in-range :in-range Support in all current engines. Firefox 29+ Safari 5.1+ Chrome 10+ Opera 11+ Edge 79+ Edge (Legacy) 13+ Internet Explorer No Firefox Android 16+ Safari iOS 5+ Chrome Android 18+ WebView Android 2.3+ Samsung Internet 1.0+ Opera Android 11+ The :in-range pseudo-class must match all elements that are candidates for constraint validation have range limitations , and that are neither suffering from an underflow nor suffering from an overflow :out-of-range :out-of-range Support in all current engines. Firefox 29+ Safari 5.1+ Chrome 10+ Opera 11+ Edge 79+ Edge (Legacy) 13+ Internet Explorer No Firefox Android 16+ Safari iOS 5+ Chrome Android 18+ WebView Android 2.3+ Samsung Internet 1.0+ Opera Android 11+ The :out-of-range pseudo-class must match all elements that are candidates for constraint validation have range limitations , and that are either suffering from an underflow or suffering from an overflow :required :required Support in all current engines. Firefox 4+ Safari 5+ Chrome 10+ Opera 10+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 5+ Chrome Android 18+ WebView Android 4.4.3+ Samsung Internet 1.0+ Opera Android 10.1+ The :required pseudo-class must match any element falling into one of the following categories: input elements that are required select elements that have a required attribute textarea elements that have a required attribute :optional :optional Support in all current engines. Firefox 4+ Safari 5+ Chrome 10+ Opera 10+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 5+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 10.1+ The :optional pseudo-class must match any element falling into one of the following categories: input elements to which the required attribute applies that are not required select elements that do not have a required attribute textarea elements that do not have a required attribute :autofill :autofill Support in one engine only. Firefox 86+ Safari 🔰 3+ Chrome 🔰 1+ Opera 🔰 15+ Edge 🔰 79+ Edge (Legacy) No Internet Explorer No Firefox Android 86+ Safari iOS 🔰 1+ Chrome Android 🔰 18+ WebView Android 🔰 1+ Samsung Internet 🔰 1.0+ Opera Android 🔰 14+ :-webkit-autofill The :autofill and :-webkit-autofill pseudo-classes must match input elements which have been autofilled by user agent. These pseudo-classes must stop matching if the user edits the autofilled field. One way such autofilling might happen is via the autocomplete attribute, but user agents could autofill even without that attribute being involved. :read-only :read-only Support in all current engines. Firefox 78+ Safari 4+ Chrome 1+ Opera 9+ Edge 79+ Edge (Legacy) 13+ Internet Explorer No Firefox Android 🔰 4+ Safari iOS 3.2+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 10.1+ :read-write :read-write Support in all current engines. Firefox 78+ Safari 4+ Chrome 1+ Opera 9+ Edge 79+ Edge (Legacy) 13+ Internet Explorer No Firefox Android 🔰 4+ Safari iOS 3.2+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 10.1+ The :read-write pseudo-class must match any element falling into one of the following categories, which for the purposes of Selectors are thus considered user-alterable [SELECTORS] input elements to which the readonly attribute applies, and that are mutable (i.e. that do not have the readonly attribute specified and that are not disabled textarea elements that do not have a readonly attribute, and that are not disabled elements that are editing hosts or editable and are neither input elements nor textarea elements The :read-only pseudo-class must match all other HTML elements :dir(ltr) :dir Support in one engine only. Firefox 49+ Safari No Chrome No Opera No Edge No Edge (Legacy) No Internet Explorer No Firefox Android 49+ Safari iOS No Chrome Android No WebView Android No Samsung Internet No Opera Android No The :dir(ltr) pseudo-class must match all elements whose directionality is ' ltr '. :dir(rtl) The :dir(rtl) pseudo-class must match all elements whose directionality is ' rtl '. This specification does not define when an element matches the :lang() dynamic pseudo-class , as it is defined in sufficient detail in a language-agnostic fashion in Selectors [SELECTORS] Microdata 5.1 Introduction 5.1.1 Overview This section is non-normative. Sometimes, it is desirable to annotate content with specific machine-readable labels, e.g. to allow generic scripts to provide services that are customized to the page, or to enable content from a variety of cooperating authors to be processed by a single script in a consistent manner. For this purpose, authors can use the microdata features described in this section. Microdata allows nested groups of name-value pairs to be added to documents, in parallel with the existing content. 5.1.2 The basic syntax This section is non-normative. At a high level, microdata consists of a group of name-value pairs. The groups are called items , and each name-value pair is a property. Items and properties are represented by regular elements. To create an item, the itemscope attribute is used. To add a property to an item, the itemprop attribute is used on one of the item's descendants. Here there are two items, each of which has the property "name": div itemscope My name is span itemprop "name" Elizabeth span div div itemscope My name is span itemprop "name" Daniel span div Markup without the microdata-related attributes does not have any effect on the microdata model. These two examples are exactly equivalent, at a microdata level, as the previous two examples respectively: div itemscope My em name em is span itemprop "name" strong liz strong abeth span div section div itemscope aside My name is span itemprop "name" >< href "/?user=daniel" Daniel > span aside div section Properties generally have values that are strings. Here the item has three properties: div itemscope My name is span itemprop "name" Neil span My band is called span itemprop "band" Four Parts Water span I am span itemprop "nationality" British span div When a string value is a URL , it is expressed using the element and its href attribute, the img element and its src attribute, or other elements that link to or embed external resources. In this example, the item has one property, "image", whose value is a URL: div itemscope img itemprop "image" src "google-logo.png" alt "Google" div When a string value is in some machine-readable format unsuitable for human consumption, it is expressed using the value attribute of the data element, with the human-readable version given in the element's contents. Here, there is an item with a property whose value is a product ID. The ID is not human-friendly, so the product's name is used the human-visible text instead of the ID. h1 itemscope data itemprop "product-id" value "9678AOU879" The Instigator 2000 data h1 For numeric data, the meter element and its value attribute can be used instead. Here a rating is given using a meter element. div itemscope itemtype "http://schema.org/Product" span itemprop "name" Panasonic White 60L Refrigerator span img src "panasonic-fridge-60l-white.jpg" alt "" div itemprop "aggregateRating" itemscope itemtype "http://schema.org/AggregateRating" meter itemprop "ratingValue" min value 3.5 max Rated 3.5/5 meter (based on span itemprop "reviewCount" 11 span customer reviews) div div Similarly, for date- and time-related data, the time element and its datetime attribute can be used instead. In this example, the item has one property, "birthday", whose value is a date: div itemscope I was born on time itemprop "birthday" datetime "2009-05-10" May 10th 2009 time div Properties can also themselves be groups of name-value pairs, by putting the itemscope attribute on the element that declares the property. Items that are not part of others are called top-level microdata items In this example, the outer item represents a person, and the inner one represents a band: div itemscope Name: span itemprop "name" Amanda span > Band: span itemprop "band" itemscope span itemprop "name" Jazz Band span span itemprop "size" 12 span players) span > div The outer item here has two properties, "name" and "band". The "name" is "Amanda", and the "band" is an item in its own right, with two properties, "name" and "size". The "name" of the band is "Jazz Band", and the "size" is "12". The outer item in this example is a top-level microdata item. Properties that are not descendants of the element with the itemscope attribute can be associated with the item using the itemref attribute. This attribute takes a list of IDs of elements to crawl in addition to crawling the children of the element with the itemscope attribute. This example is the same as the previous one, but all the properties are separated from their items div itemscope id "amanda" itemref "a b" > div id "a" Name: span itemprop "name" Amanda span > div id "b" itemprop "band" itemscope itemref "c" > div div id "c" Band: span itemprop "name" Jazz Band span > Size: span itemprop "size" 12 span players div This gives the same result as the previous example. The first item has two properties, "name", set to "Amanda", and "band", set to another item. That second item has two further properties, "name", set to "Jazz Band", and "size", set to "12". An item can have multiple properties with the same name and different values. This example describes an ice cream, with two flavors: div itemscope Flavors in my favorite ice cream: ul li itemprop "flavor" Lemon sorbet li li itemprop "flavor" Apricot sorbet li ul div This thus results in an item with two properties, both "flavor", having the values "Lemon sorbet" and "Apricot sorbet". An element introducing a property can also introduce multiple properties at once, to avoid duplication when some of the properties have the same value. Here we see an item with two properties, "favorite-color" and "favorite-fruit", both set to the value "orange": div itemscope span itemprop "favorite-color favorite-fruit" orange span div It's important to note that there is no relationship between the microdata and the content of the document where the microdata is marked up. There is no semantic difference, for instance, between the following two examples: figure img src "castle.jpeg" figcaption >< span itemscope >< span itemprop "name" The Castle span > span (1986) figcaption figure span itemscope >< meta itemprop "name" content "The Castle" > span figure img src "castle.jpeg" figcaption The Castle (1986) figcaption figure Both have a figure with a caption, and both, completely unrelated to the figure, have an item with a name-value pair with the name "name" and the value "The Castle". The only difference is that if the user drags the caption out of the document, in the former case, the item will be included in the drag-and-drop data. In neither case is the image in any way associated with the item. 5.1.3 Typed items This section is non-normative. The examples in the previous section show how information could be marked up on a page that doesn't expect its microdata to be re-used. Microdata is most useful, though, when it is used in contexts where other authors and readers are able to cooperate to make new uses of the markup. For this purpose, it is necessary to give each item a type, such as "https://example.com/person", or "https://example.org/cat", or "https://band.example.net/". Types are identified as URLs The type for an item is given as the value of an itemtype attribute on the same element as the itemscope attribute. Here, the item's type is "https://example.org/animals#cat": section itemscope itemtype "https://example.org/animals#cat" h1 itemprop "name" Hedral h1 itemprop "desc" Hedral is a male american domestic shorthair, with a fluffy black fur with white paws and belly. img itemprop "img" src "hedral.jpeg" alt "" title "Hedral, age 18 months" section In this example the "https://example.org/animals#cat" item has three properties, a "name" ("Hedral"), a "desc" ("Hedral is..."), and an "img" ("hedral.jpeg"). The type gives the context for the properties, thus selecting a vocabulary: a property named "class" given for an item with the type "https://census.example/person" might refer to the economic class of an individual, while a property named "class" given for an item with the type "https://example.com/school/teacher" might refer to the classroom a teacher has been assigned. Several types can share a vocabulary. For example, the types " " and " " could be defined to use the same vocabulary (though maybe some properties would not be especially useful in both cases, e.g. maybe the " " type might not typically be used with the classroom " property). Multiple types defined to use the same vocabulary can be given for a single item by listing the URLs as a space-separated list in the attribute' value. An item cannot be given two types if they do not use the same vocabulary, however. 5.1.4 Global identifiers for items This section is non-normative. Sometimes, an item gives information about a topic that has a global identifier. For example, books can be identified by their ISBN number. Vocabularies (as identified by the itemtype attribute) can be designed such that items get associated with their global identifier in an unambiguous way by expressing the global identifiers as URLs given in an itemid attribute. The exact meaning of the URLs given in itemid attributes depends on the vocabulary used. Here, an item is talking about a particular book: dl itemscope itemtype "https://vocab.example.net/book" itemid "urn:isbn:0-330-34032-8" dt Title dd itemprop "title" The Reality Dysfunction dt Author dd itemprop "author" Peter F. Hamilton dt Publication date dd >< time itemprop "pubdate" datetime "1996-01-26" 26 January 1996 time dl The " " vocabulary in this example would define that the itemid attribute takes a urn: URL pointing to the ISBN of the book. 5.1.5 Selecting names when defining vocabularies This section is non-normative. Using microdata means using a vocabulary. For some purposes, an ad-hoc vocabulary is adequate. For others, a vocabulary will need to be designed. Where possible, authors are encouraged to re-use existing vocabularies, as this makes content re-use easier. When designing new vocabularies, identifiers can be created either using URLs , or, for properties, as plain words (with no dots or colons). For URLs, conflicts with other vocabularies can be avoided by only using identifiers that correspond to pages that the author has control over. For instance, if Jon and Adam both write content at example.com , at and respectively, then they could select identifiers of the form "https://example.com/~jon/name" and "https://example.com/~adam/name" respectively. Properties whose names are just plain words can only be used within the context of the types for which they are intended; properties named using URLs can be reused in items of any type. If an item has no type, and is not part of another item, then if its properties have names that are just plain words, they are not intended to be globally unique, and are instead only intended for limited use. Generally speaking, authors are encouraged to use either properties with globally unique names (URLs) or ensure that their items are typed. Here, an item is an "https://example.org/animals#cat", and most of the properties have names that are words defined in the context of that type. There are also a few additional properties whose names come from other vocabularies. section itemscope itemtype "https://example.org/animals#cat" h1 itemprop "name https://example.com/fn" Hedral h1 itemprop "desc" Hedral is a male American domestic shorthair, with a fluffy span itemprop "https://example.com/color" black span fur with span itemprop "https://example.com/color" white span paws and belly. img itemprop "img" src "hedral.jpeg" alt "" title "Hedral, age 18 months" section This example has one item with the type "https://example.org/animals#cat" and the following properties: Property Value name Hedral Hedral desc Hedral is a male American domestic shorthair, with a fluffy black fur with white paws and belly. black white img .../hedral.jpeg 5.2 Encoding microdata 5.2.1 The microdata model The microdata model consists of groups of name-value pairs known as items Each group is known as an item . Each item can have item types , a global identifier (if the vocabulary specified by the item types support global identifiers for items ), and a list of name-value pairs. Each name in the name-value pair is known as a property , and each property has one or more values . Each value is either a string or itself a group of name-value pairs (an item ). The names are unordered relative to each other, but if a particular name has multiple values, they do have a relative order. 5.2.2 Items Global_attributes/itemscope Support in all current engines. Firefox Yes Safari Yes Chrome Yes Opera Yes Edge Yes Edge (Legacy) 12+ Internet Explorer Yes Firefox Android Yes Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes Every HTML element may have an itemscope attribute specified. The itemscope attribute is a boolean attribute An element with the itemscope attribute specified creates a new item , a group of name-value pairs. Global_attributes/itemtype Support in all current engines. Firefox Yes Safari Yes Chrome Yes Opera Yes Edge Yes Edge (Legacy) 12+ Internet Explorer Yes Firefox Android Yes Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes Elements with an itemscope attribute may have an itemtype attribute specified, to give the item types of the item The itemtype attribute, if specified, must have a value that is an unordered set of unique space-separated tokens , none of which are identical to another token and each of which is a valid URL string that is an absolute URL , and all of which are defined to use the same vocabulary. The attribute's value must have at least one token. The item types of an item are the tokens obtained by splitting the element's itemtype attribute's value on ASCII whitespace . If the itemtype attribute is missing or parsing it in this way finds no tokens, the item is said to have no item types The item types must all be types defined in applicable specifications and must all be defined to use the same vocabulary. Except if otherwise specified by that specification, the URLs given as the item types should not be automatically dereferenced. A specification could define that its item type can be dereferenced to provide the user with help information, for example. In fact, vocabulary authors are encouraged to provide useful information at the given URL Item types are opaque identifiers, and user agents must not dereference unknown item types , or otherwise deconstruct them, in order to determine how to process items that use them. The itemtype attribute must not be specified on elements that do not have an itemscope attribute specified. An item is said to be a typed item when either it has an item type , or it is the value of a property of a typed item . The relevant types for a typed item is the item 's item types if it has any, or else is the relevant types of the item for which it is a property 's value Global_attributes/itemid Support in all current engines. Firefox Yes Safari Yes Chrome Yes Opera Yes Edge Yes Edge (Legacy) 12+ Internet Explorer Yes Firefox Android Yes Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes Elements with an itemscope attribute and an itemtype attribute that references a vocabulary that is defined to support global identifiers for items may also have an itemid attribute specified, to give a global identifier for the item , so that it can be related to other items on pages elsewhere on the web. The itemid attribute, if specified, must have a value that is valid URL potentially surrounded by spaces The global identifier of an item is the value of its element's itemid attribute, if it has one, parsed relative to the node document of the element on which the attribute is specified. If the itemid attribute is missing or if resolving it fails, it is said to have no global identifier The itemid attribute must not be specified on elements that do not have both an itemscope attribute and an itemtype attribute specified, and must not be specified on elements with an itemscope attribute whose itemtype attribute specifies a vocabulary that does not support global identifiers for items , as defined by that vocabulary's specification. The exact meaning of a global identifier is determined by the vocabulary's specification. It is up to such specifications to define whether multiple items with the same global identifier (whether on the same page or on different pages) are allowed to exist, and what the processing rules for that vocabulary are with respect to handling the case of multiple items with the same ID. Global_attributes/itemref Support in all current engines. Firefox Yes Safari Yes Chrome Yes Opera Yes Edge Yes Edge (Legacy) 12+ Internet Explorer Yes Firefox Android Yes Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes Elements with an itemscope attribute may have an itemref attribute specified, to give a list of additional elements to crawl to find the name-value pairs of the item The itemref attribute, if specified, must have a value that is an unordered set of unique space-separated tokens none of which are identical to another token and consisting of IDs of elements in the same tree The itemref attribute must not be specified on elements that do not have an itemscope attribute specified. The itemref attribute is not part of the microdata data model. It is merely a syntactic construct to aid authors in adding annotations to pages where the data to be annotated does not follow a convenient tree structure. For example, it allows authors to mark up data in a table so that each column defines a separate item , while keeping the properties in the cells. This example shows a simple vocabulary used to describe the products of a model railway manufacturer. The vocabulary has just five property names: product-code An integer that names the product in the manufacturer's catalog. name A brief description of the product. scale One of "HO", "1", or "Z" (potentially with leading or trailing whitespace), indicating the scale of the product. digital If present, one of "Digital", "Delta", or "Systems" (potentially with leading or trailing whitespace) indicating that the product has a digital decoder of the given type. track-type For track-specific products, one of "K", "M", "C" (potentially with leading or trailing whitespace) indicating the type of track for which the product is intended. This vocabulary has four defined item types Rolling stock with an engine Passenger rolling stock Track pieces Equipment with lighting Each item that uses this vocabulary can be given one or more of these types, depending on what the product is. Thus, a locomotive might be marked up as: dl itemscope itemtype "https://md.example.com/loco dt Name: dd itemprop "name" Tank Locomotive (DB 80) dt Product code: dd itemprop "product-code" 33041 dt Scale: dd itemprop "scale" HO dt Digital: dd itemprop "digital" Delta dl A turnout lantern retrofit kit might be marked up as: dl itemscope itemtype "https://md.example.com/track dt Name: dd itemprop "name" Turnout Lantern Kit dt Product code: dd itemprop "product-code" 74470 dt Purpose: dd For retrofitting 2 span itemprop "track-type" span Track turnouts. meta itemprop "scale" content "HO" dl A passenger car with no lighting might be marked up as: dl itemscope itemtype "https://md.example.com/passengers" dt Name: dd itemprop "name" Express Train Passenger Car (DB Am 203) dt Product code: dd itemprop "product-code" 8710 dt Scale: dd itemprop "scale" dl Great care is necessary when creating new vocabularies. Often, a hierarchical approach to types can be taken that results in a vocabulary where each item only ever has a single type, which is generally much simpler to manage. 5.2.3 Names: the itemprop attribute Global_attributes/itemprop Support in all current engines. Firefox Yes Safari Yes Chrome Yes Opera Yes Edge Yes Edge (Legacy) 12+ Internet Explorer Yes Firefox Android Yes Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes Every HTML element may have an itemprop attribute specified, if doing so adds one or more properties to one or more items (as defined below). The itemprop attribute, if specified, must have a value that is an unordered set of unique space-separated tokens none of which are identical to another token, representing the names of the name-value pairs that it adds. The attribute's value must have at least one token. Each token must be either: If the item is a typed item : a defined property name allowed in this situation according to the specification that defines the relevant types for the item, or valid URL string that is an absolute URL defined as an item property name allowed in this situation by a vocabulary specification, or valid URL string that is an absolute URL , used as a proprietary item property name (i.e. one used by the author for private purposes, not defined in a public specification), or If the item is not a typed item : a string that contains no U+002E FULL STOP characters (.) and no U+003A COLON characters (:), used as a proprietary item property name (i.e. one used by the author for private purposes, not defined in a public specification). Specifications that introduce defined property names must ensure all such property names contain no U+002E FULL STOP characters (.), no U+003A COLON characters (:), and no ASCII whitespace The rules above disallow U+003A COLON characters (:) in non-URL values because otherwise they could not be distinguished from URLs. Values with U+002E FULL STOP characters (.) are reserved for future extensions. ASCII whitespace are disallowed because otherwise the values would be parsed as multiple tokens. When an element with an itemprop attribute adds a property to multiple items the requirement above regarding the tokens applies for each item individually. The property names of an element are the tokens that the element's itemprop attribute is found to contain when its value is split on ASCII whitespace , with the order preserved but with duplicates removed (leaving only the first occurrence of each name). Within an item , the properties are unordered with respect to each other, except for properties with the same name, which are ordered in the order they are given by the algorithm that defines the properties of an item In the following example, the "a" property has the values "1" and "2", in that order but whether the "a" property comes before the "b" property or not is not important: div itemscope itemprop "a" itemprop "a" itemprop "b" test div Thus, the following is equivalent: div itemscope itemprop "b" test itemprop "a" itemprop "a" div As is the following: div itemscope itemprop "a" itemprop "b" test itemprop "a" div And the following: div id "x" itemprop "a" div div itemscope itemref "x" itemprop "b" test itemprop "a" div 5.2.4 Values The property value of a name-value pair added by an element with an itemprop attribute is as given for the first matching case in the following list: If the element also has an itemscope attribute The value is the item created by the element. If the element is a meta element The value is the value of the element's content attribute, if any, or the empty string if there is no such attribute. If the element is an audio embed iframe img source track , or video element The value is the resulting URL string that results from parsing the value of the element's src attribute relative to the node document of the element at the time the attribute is set, or the empty string if there is no such attribute or if parsing it results in an error. If the element is an area , or link element The value is the resulting URL string that results from parsing the value of the element's href attribute relative to the node document of the element at the time the attribute is set, or the empty string if there is no such attribute or if parsing it results in an error. If the element is an object element The value is the resulting URL string that results from parsing the value of the element's data attribute relative to the node document of the element at the time the attribute is set, or the empty string if there is no such attribute or if parsing it results in an error. If the element is a data element The value is the value of the element's value attribute, if it has one, or the empty string otherwise. If the element is a meter element The value is the value of the element's value attribute, if it has one, or the empty string otherwise. If the element is a time element The value is the element's datetime value Otherwise The value is the element's descendant text content The URL property elements are the area audio embed iframe img link object source track , and video elements. If a property's value , as defined by the property's definition, is an absolute URL , the property must be specified using a URL property element These requirements do not apply just because a property value happens to match the syntax for a URL. They only apply if the property is explicitly defined as taking such a value. For example, a book about the first moon landing could be called "mission:moon". A "title" property from a vocabulary that defines a title as being a string would not expect the title to be given in an element, even though it looks like a URL . On the other hand, if there was a (rather narrowly scoped!) vocabulary for "books whose titles look like URLs" which had a "title" property defined to take a URL, then the property would expect the title to be given in an element (or one of the other URL property elements ), because of the requirement above. 5.2.5 Associating names with items To find the properties of an item defined by the element root the user agent must run the following steps. These steps are also used to flag microdata errors Let results memory , and pending be empty lists of elements. Add the element root to memory Add the child elements of root , if any, to pending If root has an itemref attribute, split the value of that itemref attribute on ASCII whitespace . For each resulting token ID , if there is an element in the tree of root with the ID ID , then add the first such element to pending While pending is not empty: Remove an element from pending and let current be that element. If current is already in memory , there is a microdata error ; continue. Add current to memory If current does not have an itemscope attribute, then: add all the child elements of current to pending If current has an itemprop attribute specified and has one or more property names , then add current to results Sort results in tree order Return results A document must not contain any items for which the algorithm to find the properties of an item finds any microdata errors An item is a top-level microdata item if its element does not have an itemprop attribute. All itemref attributes in a Document must be such that there are no cycles in the graph formed from representing each item in the Document as a node in the graph and each property of an item whose value is another item as an edge in the graph connecting those two items. A document must not contain any elements that have an itemprop attribute that would not be found to be a property of any of the items in that document were their properties all to be determined. In this example, a single license statement is applied to two works, using itemref from the items representing the works: html lang "en" head title Photo gallery title head body h1 My photos h1 figure itemscope itemtype "http://n.whatwg.org/work" itemref "licenses" img itemprop "work" src "images/house.jpeg" alt "A white house, boarded up, sits in a forest." figcaption itemprop "title" The house I found. figcaption figure figure itemscope itemtype "http://n.whatwg.org/work" itemref "licenses" img itemprop "work" src "images/mailbox.jpeg" alt "Outside the house is a mailbox. It has a leaflet inside." figcaption itemprop "title" The mailbox. figcaption figure footer id "licenses" All images licensed under the itemprop "license" href "http://www.opensource.org/licenses/mit-license.php" MIT license footer body html The above results in two items with the type " ", one with: work images/house.jpeg title The house I found. license ...and one with: work images/mailbox.jpeg title The mailbox. license 5.2.6 Microdata and other namespaces Currently, the itemscope itemprop , and other microdata attributes are only defined for HTML elements . This means that attributes with the literal names " itemscope ", " itemprop ", etc, do not cause microdata processing to occur on elements in other namespaces, such as SVG. Thus, in the following example there is only one item, not two. itemscope > svg itemscope > svg 5.3 Sample microdata vocabularies The vocabularies in this section are primarily intended to demonstrate how a vocabulary is specified, though they are also usable in their own right. 5.3.1 vCard An item with the item type represents a person's or organization's contact information. This vocabulary does not support global identifiers for items The following are the type's defined property names . They are based on the vocabulary defined in vCard Format Specification vCard ) and its extensions, where more information on how to interpret the values can be found. [RFC6350] kind Describes what kind of contact the item represents. The value must be text that is identical to one of the kind strings A single property with the name kind may be present within each item with the type fn Gives the formatted text corresponding to the name of the person or organization. The value must be text. Exactly one property with the name fn must be present within each item with the type Gives the structured name of the person or organization. The value must be an item with zero or more of each of the family-name given-name additional-name honorific-prefix , and honorific-suffix properties. Exactly one property with the name must be present within each item with the type family-name (inside Gives the family name of the person, or the full name of the organization. The value must be text. Any number of properties with the name family-name may be present within the item that forms the value of the property of an item with the type given-name (inside Gives the given-name of the person. The value must be text. Any number of properties with the name given-name may be present within the item that forms the value of the property of an item with the type additional-name (inside Gives the any additional names of the person. The value must be text. Any number of properties with the name additional-name may be present within the item that forms the value of the property of an item with the type honorific-prefix (inside Gives the honorific prefix of the person. The value must be text. Any number of properties with the name honorific-prefix may be present within the item that forms the value of the property of an item with the type honorific-suffix (inside Gives the honorific suffix of the person. The value must be text. Any number of properties with the name honorific-suffix may be present within the item that forms the value of the property of an item with the type nickname Gives the nickname of the person or organization. The nickname is the descriptive name given instead of or in addition to the one belonging to a person, place, or thing. It can also be used to specify a familiar form of a proper name specified by the fn or properties. The value must be text. Any number of properties with the name nickname may be present within each item with the type photo Gives a photograph of the person or organization. The value must be an absolute URL Any number of properties with the name photo may be present within each item with the type bday Gives the birth date of the person or organization. The value must be a valid date string A single property with the name bday may be present within each item with the type anniversary Gives the birth date of the person or organization. The value must be a valid date string A single property with the name anniversary may be present within each item with the type sex Gives the biological sex of the person. The value must be one of , meaning "female", , meaning "male", , meaning "none or not applicable", , meaning "other", or , meaning "unknown". A single property with the name sex may be present within each item with the type gender-identity Gives the gender identity of the person. The value must be text. A single property with the name gender-identity may be present within each item with the type adr Gives the delivery address of the person or organization. The value must be an item with zero or more type post-office-box extended-address , and street-address properties, and optionally a locality property, optionally a region property, optionally a postal-code property, and optionally a country-name property. If no type properties are present within an item that forms the value of an adr property of an item with the type , then the address type string work is implied. Any number of properties with the name adr may be present within each item with the type type (inside adr Gives the type of delivery address. The value must be text that is identical to one of the address type strings Any number of properties with the name type may be present within the item that forms the value of an adr property of an item with the type , but within each such adr property item there must only be one type property per distinct value. post-office-box (inside adr Gives the post office box component of the delivery address of the person or organization. The value must be text. Any number of properties with the name post-office-box may be present within the item that forms the value of an adr property of an item with the type vCard urges authors not to use this field. extended-address (inside adr Gives an additional component of the delivery address of the person or organization. The value must be text. Any number of properties with the name extended-address may be present within the item that forms the value of an adr property of an item with the type vCard urges authors not to use this field. street-address (inside adr Gives the street address component of the delivery address of the person or organization. The value must be text. Any number of properties with the name street-address may be present within the item that forms the value of an adr property of an item with the type locality (inside adr Gives the locality component (e.g. city) of the delivery address of the person or organization. The value must be text. A single property with the name locality may be present within the item that forms the value of an adr property of an item with the type region (inside adr Gives the region component (e.g. state or province) of the delivery address of the person or organization. The value must be text. A single property with the name region may be present within the item that forms the value of an adr property of an item with the type postal-code (inside adr Gives the postal code component of the delivery address of the person or organization. The value must be text. A single property with the name postal-code may be present within the item that forms the value of an adr property of an item with the type country-name (inside adr Gives the country name component of the delivery address of the person or organization. The value must be text. A single property with the name country-name may be present within the item that forms the value of an adr property of an item with the type tel Gives the telephone number of the person or organization. The value must be either text that can be interpreted as a telephone number as defined in the CCITT specifications E.163 and X.121, or an item with zero or more type properties and exactly one value property. [E163] [X121] If no type properties are present within an item that forms the value of a tel property of an item with the type , or if the value of such a tel property is text, then the telephone type string voice is implied. Any number of properties with the name tel may be present within each item with the type type (inside tel Gives the type of telephone number. The value must be text that is identical to one of the telephone type strings Any number of properties with the name type may be present within the item that forms the value of a tel property of an item with the type , but within each such tel property item there must only be one type property per distinct value. value (inside tel Gives the actual telephone number of the person or organization. The value must be text that can be interpreted as a telephone number as defined in the CCITT specifications E.163 and X.121. [E163] [X121] Exactly one property with the name value must be present within the item that forms the value of a tel property of an item with the type email Gives the email address of the person or organization. The value must be text. Any number of properties with the name email may be present within each item with the type impp Gives a URL for instant messaging and presence protocol communications with the person or organization. The value must be an absolute URL Any number of properties with the name impp may be present within each item with the type lang Gives a language understood by the person or organization. The value must be a valid BCP 47 language tag. [BCP47] Any number of properties with the name lang may be present within each item with the type tz Gives the time zone of the person or organization. The value must be text and must match the following syntax: Either a U+002B PLUS SIGN character (+) or a U+002D HYPHEN-MINUS character (-). valid non-negative integer that is exactly two digits long and that represents a number in the range 00..23. A U+003A COLON character (:). valid non-negative integer that is exactly two digits long and that represents a number in the range 00..59. Any number of properties with the name tz may be present within each item with the type geo Gives the geographical position of the person or organization. The value must be text and must match the following syntax: Optionally, either a U+002B PLUS SIGN character (+) or a U+002D HYPHEN-MINUS character (-). One or more ASCII digits Optionally*, a U+002E FULL STOP character (.) followed by one or more ASCII digits A U+003B SEMICOLON character (;). Optionally, either a U+002B PLUS SIGN character (+) or a U+002D HYPHEN-MINUS character (-). One or more ASCII digits Optionally*, a U+002E FULL STOP character (.) followed by one or more ASCII digits The optional components marked with an asterisk (*) should be included, and should have six digits each. The value specifies latitude and longitude, in that order (i.e., "LAT LON" ordering), in decimal degrees. The longitude represents the location east and west of the prime meridian as a positive or negative real number, respectively. The latitude represents the location north and south of the equator as a positive or negative real number, respectively. Any number of properties with the name geo may be present within each item with the type title Gives the job title, functional position or function of the person or organization. The value must be text. Any number of properties with the name title may be present within each item with the type role Gives the role, occupation, or business category of the person or organization. The value must be text. Any number of properties with the name role may be present within each item with the type logo Gives the logo of the person or organization. The value must be an absolute URL Any number of properties with the name logo may be present within each item with the type agent Gives the contact information of another person who will act on behalf of the person or organization. The value must be either an item with the type , or an absolute URL or text. Any number of properties with the name agent may be present within each item with the type org Gives the name and units of the organization. The value must be either text or an item with one organization-name property and zero or more organization-unit properties. Any number of properties with the name org may be present within each item with the type organization-name (inside org Gives the name of the organization. The value must be text. Exactly one property with the name organization-name must be present within the item that forms the value of an org property of an item with the type organization-unit (inside org Gives the name of the organization unit. The value must be text. Any number of properties with the name organization-unit may be present within the item that forms the value of the org property of an item with the type member Gives a URL that represents a member of the group. The value must be an absolute URL Any number of properties with the name member may be present within each item with the type if the item also has a property with the name kind whose value is " group ". related Gives a relationship to another entity. The value must be an item with one url property and one rel properties. Any number of properties with the name related may be present within each item with the type url (inside related Gives the URL for the related entity. The value must be an absolute URL Exactly one property with the name url must be present within the item that forms the value of a related property of an item with the type rel (inside related Gives the relationship between the entity and the related entity. The value must be text that is identical to one of the relationship strings Exactly one property with the name rel must be present within the item that forms the value of a related property of an item with the type categories Gives the name of a category or tag that the person or organization could be classified as. The value must be text. Any number of properties with the name categories may be present within each item with the type note Gives supplemental information or a comment about the person or organization. The value must be text. Any number of properties with the name note may be present within each item with the type rev Gives the revision date and time of the contact information. The value must be text that is a valid global date and time string The value distinguishes the current revision of the information for other renditions of the information. Any number of properties with the name rev may be present within each item with the type sound Gives a sound file relating to the person or organization. The value must be an absolute URL Any number of properties with the name sound may be present within each item with the type uid Gives a globally unique identifier corresponding to the person or organization. The value must be text. A single property with the name uid may be present within each item with the type url Gives a URL relating to the person or organization. The value must be an absolute URL Any number of properties with the name url may be present within each item with the type The kind strings are: individual Indicates a single entity (e.g. a person). group Indicates multiple entities (e.g. a mailing list). org Indicates a single entity that is not a person (e.g. a company). location Indicates a geographical place (e.g. an office building). The address type strings are: Indicates a delivery address for a residence. work Indicates a delivery address for a place of work. The telephone type strings are: Indicates a residential number. work Indicates a telephone number for a place of work. text Indicates that the telephone number supports text messages (SMS). voice Indicates a voice telephone number. fax Indicates a facsimile telephone number. cell Indicates a cellular telephone number. video Indicates a video conferencing telephone number. pager Indicates a paging device telephone number. textphone Indicates a telecommunication device for people with hearing or speech difficulties. The relationship strings are: emergency An emergency contact. agent Another entity that acts on behalf of this entity. contact acquaintance friend met worker colleague resident neighbor child parent sibling spouse kin muse crush date sweetheart me Has the meaning defined in XFN. [XFN] 5.3.1.1 Conversion to vCard Given a list of nodes nodes in a Document , a user agent must run the following algorithm to extract any vCard data represented by those nodes (only the first vCard is returned): If none of the nodes in nodes are items with the item type , then there is no vCard. Abort the algorithm, returning nothing. Let node be the first node in nodes that is an item with the item type Let output be an empty string. Add a vCard line with the type " BEGIN " and the value VCARD " to output Add a vCard line with the type " PROFILE " and the value VCARD " to output Add a vCard line with the type " VERSION " and the value 4.0 " to output Add a vCard line with the type " SOURCE " and the result of escaping the vCard text string that is the document's URL as the value to output If the title element is not null, add a vCard line with the type " NAME " and with the result of escaping the vCard text string obtained from the title element 's descendant text content as the value to output Let sex be the empty string. Let gender-identity be the empty string. For each element element that is a property of the item node : for each name name in element 's property names , run the following substeps: Let parameters be an empty set of name-value pairs. Run the appropriate set of substeps from the following list. The steps will set a variable value , which is used in the next step. If the property's value is an item subitem and name is Let value be the empty string. Append to value the result of collecting the first vCard subproperty named family-name in subitem Append a U+003B SEMICOLON character (;) to value Append to value the result of collecting the first vCard subproperty named given-name in subitem Append a U+003B SEMICOLON character (;) to value Append to value the result of collecting the first vCard subproperty named additional-name in subitem Append a U+003B SEMICOLON character (;) to value Append to value the result of collecting the first vCard subproperty named honorific-prefix in subitem Append a U+003B SEMICOLON character (;) to value Append to value the result of collecting the first vCard subproperty named honorific-suffix in subitem If the property's value is an item subitem and name is adr Let value be the empty string. Append to value the result of collecting vCard subproperties named post-office-box in subitem Append a U+003B SEMICOLON character (;) to value Append to value the result of collecting vCard subproperties named extended-address in subitem Append a U+003B SEMICOLON character (;) to value Append to value the result of collecting vCard subproperties named street-address in subitem Append a U+003B SEMICOLON character (;) to value Append to value the result of collecting the first vCard subproperty named locality in subitem Append a U+003B SEMICOLON character (;) to value Append to value the result of collecting the first vCard subproperty named region in subitem Append a U+003B SEMICOLON character (;) to value Append to value the result of collecting the first vCard subproperty named postal-code in subitem Append a U+003B SEMICOLON character (;) to value Append to value the result of collecting the first vCard subproperty named country-name in subitem If there is a property named type in subitem , and the first such property has a value that is not an item and whose value consists only of ASCII alphanumerics , then add a parameter named " TYPE " whose value is the value of that property to parameters If the property's value is an item subitem and name is org Let value be the empty string. Append to value the result of collecting the first vCard subproperty named organization-name in subitem For each property named organization-unit in subitem , run the following steps: If the value of the property is an item , then skip this property. Append a U+003B SEMICOLON character (;) to value Append the result of escaping the vCard text string given by the value of the property to value If the property's value is an item subitem with the item type and name is related Let value be the empty string. If there is a property named url in subitem , and its element is a URL property element , then append the result of escaping the vCard text string given by the value of the first such property to value , and add a parameter with the name " VALUE " and the value " URI " to parameters If there is a property named rel in subitem , and the first such property has a value that is not an item and whose value consists only of ASCII alphanumerics , then add a parameter named " RELATION " whose value is the value of that property to parameters If the property's value is an item and name is none of the above Let value be the result of collecting the first vCard subproperty named value in subitem If there is a property named type in subitem , and the first such property has a value that is not an item and whose value consists only of ASCII alphanumeric , then add a parameter named " TYPE " whose value is the value of that property to parameters If the property's value is not an item and its name is sex If this is the first such property to be found, set sex to the property's value If the property's value is not an item and its name is gender-identity If this is the first such property to be found, set gender-identity to the property's value Otherwise (the property's value is not an item Let value be the property's value If element is one of the URL property elements , add a parameter with the name " VALUE " and the value " URI " to parameters Otherwise, if name is bday or anniversary and the value is valid date string , add a parameter with the name " VALUE " and the value " DATE " to parameters Otherwise, if name is rev and the value is a valid global date and time string , add a parameter with the name " VALUE " and the value " DATE-TIME " to parameters Prefix every U+005C REVERSE SOLIDUS character (\) in value with another U+005C REVERSE SOLIDUS character (\). Prefix every U+002C COMMA character (,) in value with a U+005C REVERSE SOLIDUS character (\). Unless name is geo , prefix every U+003B SEMICOLON character (;) in value with a U+005C REVERSE SOLIDUS character (\). Replace every U+000D CARRIAGE RETURN U+000A LINE FEED character pair (CRLF) in value with a U+005C REVERSE SOLIDUS character (\) followed by a U+006E LATIN SMALL LETTER N character (n). Replace every remaining U+000D CARRIAGE RETURN (CR) or U+000A LINE FEED (LF) character in value with a U+005C REVERSE SOLIDUS character (\) followed by a U+006E LATIN SMALL LETTER N character (n). Add a vCard line with the type name , the parameters parameters , and the value value to output If either sex or gender-identity has a value that is not the empty string, add a vCard line with the type " GENDER " and the value consisting of the concatenation of sex a U+003B SEMICOLON character (;), and gender-identity to output Add a vCard line with the type " END " and the value VCARD " to output When the above algorithm says that the user agent is to add a vCard line consisting of a type type , optionally some parameters, and a value value to a string output , it must run the following steps: Let line be an empty string. Append type converted to ASCII uppercase , to line If there are any parameters, then for each parameter, in the order that they were added, run these substeps: Append a U+003B SEMICOLON character (;) to line Append the parameter's name to line Append a U+003D EQUALS SIGN character (=) to line Append the parameter's value to line Append a U+003A COLON character (:) to line Append value to line Let maximum length be 75. While line 's code point length is greater than maximum length Append the first maximum length code points of line to output Remove the first maximum length code points from line Append a U+000D CARRIAGE RETURN character (CR) to output Append a U+000A LINE FEED character (LF) to output Append a U+0020 SPACE character to output Let maximum length be 74. Append (what remains of) line to output Append a U+000D CARRIAGE RETURN character (CR) to output Append a U+000A LINE FEED character (LF) to output When the steps above require the user agent to obtain the result of collecting vCard subproperties named subname in subitem , the user agent must run the following steps: Let value be the empty string. For each property named subname in the item subitem run the following substeps: If the value of the property is itself an item , then skip this property. If this is not the first property named subname in subitem (ignoring any that were skipped by the previous step), then append a U+002C COMMA character (,) to value Append the result of escaping the vCard text string given by the value of the property to value Return value When the steps above require the user agent to obtain the result of collecting the first vCard subproperty named subname in subitem , the user agent must run the following steps: If there are no properties named subname in subitem , then return the empty string. If the value of the first property named subname in subitem is an item , then return the empty string. Return the result of escaping the vCard text string given by the value of the first property named subname in subitem When the above algorithms say the user agent is to escape the vCard text string value , the user agent must use the following steps: Prefix every U+005C REVERSE SOLIDUS character (\) in value with another U+005C REVERSE SOLIDUS character (\). Prefix every U+002C COMMA character (,) in value with a U+005C REVERSE SOLIDUS character (\). Prefix every U+003B SEMICOLON character (;) in value with a U+005C REVERSE SOLIDUS character (\). Replace every U+000D CARRIAGE RETURN U+000A LINE FEED character pair (CRLF) in value with a U+005C REVERSE SOLIDUS character (\) followed by a U+006E LATIN SMALL LETTER N character (n). Replace every remaining U+000D CARRIAGE RETURN (CR) or U+000A LINE FEED (LF) character in value with a U+005C REVERSE SOLIDUS character (\) followed by a U+006E LATIN SMALL LETTER N character (n). Return the mutated value This algorithm can generate invalid vCard output, if the input does not conform to the rules described for the item type and defined property names 5.3.1.2 Examples This section is non-normative. Here is a long example vCard for a fictional character called "Jack Bauer": section id "jack" itemscope itemtype "http://microformats.org/profile/hcard" h1 itemprop "fn" span itemprop "n" itemscope span itemprop "given-name" Jack span span itemprop "family-name" Bauer span span h1 img itemprop "photo" alt "" src "jack-bauer.jpg" itemprop "org" itemscope span itemprop "organization-name" Counter-Terrorist Unit span span itemprop "organization-unit" Los Angeles Division span span itemprop "adr" itemscope span itemprop "street-address" 10201 W. Pico Blvd. span >< br span itemprop "locality" Los Angeles span span itemprop "region" CA span span itemprop "postal-code" 90064 span >< br span itemprop "country-name" United States span >< br span span itemprop "geo" 34.052339;-118.410623 span h2 Assorted Contact Methods h2 ul li itemprop "tel" itemscope span itemprop "value" +1 (310) 597 3781 span span itemprop "type" work span meta itemprop "type" content "voice" li li >< itemprop "url" href "https://en.wikipedia.org/wiki/Jack_Bauer" I'm on Wikipedia so you can leave a message on my user talk page. li li >< itemprop "url" href "http://www.jackbauerfacts.com/" Jack Bauer Facts > li li itemprop "email" >< href "mailto:j.bauer@la.ctu.gov.invalid" j.bauer@la.ctu.gov.invalid > li li itemprop "tel" itemscope span itemprop "value" +1 (310) 555 3781 span span meta itemprop "type" content "cell" mobile phone span li ul ins datetime "2008-07-20 21:00:00+01:00" meta itemprop "rev" content "2008-07-20 21:00:00+01:00" itemprop "tel" itemscope >< strong Update! strong My new span itemprop "type" span phone number is span itemprop "value" 01632 960 123 span ins section The odd line wrapping is needed because newlines are meaningful in microdata: newlines would be preserved in a conversion to, for example, the vCard format. This example shows a site's contact details (using the address element) containing an address with two street components: address itemscope itemtype "http://microformats.org/profile/hcard" strong itemprop "fn" >< span itemprop "n" itemscope >< span itemprop "given-name" Alfred span span itemprop "family-name" Person span > span > strong br span itemprop "adr" itemscope span itemprop "street-address" 1600 Amphitheatre Parkway span br span itemprop "street-address" Building 43, Second Floor span br span itemprop "locality" Mountain View span span itemprop "region" CA span span itemprop "postal-code" 94043 span span address The vCard vocabulary can be used to just mark up people's names: span itemscope itemtype "http://microformats.org/profile/hcard" >< span itemprop fn >< span itemprop "n" itemscope >< span itemprop "given-name" George span span itemprop "family-name" Washington span > span > span > span This creates a single item with a two name-value pairs, one with the name "fn" and the value "George Washington", and the other with the name "n" and a second item as its value, the second item having the two name-value pairs "given-name" and "family-name" with the values "George" and "Washington" respectively. This is defined to map to the following vCard: BEGIN:VCARD PROFILE:VCARD VERSION:4.0 SOURCE: document's address FN:George Washington N:Washington;George;;; END:VCARD 5.3.2 vEvent An item with the item type represents an event. This vocabulary does not support global identifiers for items The following are the type's defined property names . They are based on the vocabulary defined in Internet Calendaring and Scheduling Core Object Specification iCalendar ), where more information on how to interpret the values can be found. [RFC5545] Only the parts of the iCalendar vocabulary relating to events are used here; this vocabulary cannot express a complete iCalendar instance. attach Gives the address of an associated document for the event. The value must be an absolute URL Any number of properties with the name attach may be present within each item with the type categories Gives the name of a category or tag that the event could be classified as. The value must be text. Any number of properties with the name categories may be present within each item with the type class Gives the access classification of the information regarding the event. The value must be text with one of the following values: public private confidential This is merely advisory and cannot be considered a confidentiality measure. A single property with the name class may be present within each item with the type comment Gives a comment regarding the event. The value must be text. Any number of properties with the name comment may be present within each item with the type description Gives a detailed description of the event. The value must be text. A single property with the name description may be present within each item with the type geo Gives the geographical position of the event. The value must be text and must match the following syntax: Optionally, either a U+002B PLUS SIGN character (+) or a U+002D HYPHEN-MINUS character (-). One or more ASCII digits Optionally*, a U+002E FULL STOP character (.) followed by one or more ASCII digits A U+003B SEMICOLON character (;). Optionally, either a U+002B PLUS SIGN character (+) or a U+002D HYPHEN-MINUS character (-). One or more ASCII digits Optionally*, a U+002E FULL STOP character (.) followed by one or more ASCII digits The optional components marked with an asterisk (*) should be included, and should have six digits each. The value specifies latitude and longitude, in that order (i.e., "LAT LON" ordering), in decimal degrees. The longitude represents the location east and west of the prime meridian as a positive or negative real number, respectively. The latitude represents the location north and south of the equator as a positive or negative real number, respectively. A single property with the name geo may be present within each item with the type location Gives the location of the event. The value must be text. A single property with the name location may be present within each item with the type resources Gives a resource that will be needed for the event. The value must be text. Any number of properties with the name resources may be present within each item with the type status Gives the confirmation status of the event. The value must be text with one of the following values: tentative confirmed cancelled A single property with the name status may be present within each item with the type summary Gives a short summary of the event. The value must be text. User agents should replace U+000A LINE FEED (LF) characters in the value by U+0020 SPACE characters when using the value. A single property with the name summary may be present within each item with the type dtend Gives the date and time by which the event ends. If the property with the name dtend is present within an item with the type that has a property with the name dtstart whose value is a valid date string , then the value of the property with the name dtend must be text that is a valid date string also. Otherwise, the value of the property must be text that is a valid global date and time string In either case, the value be later in time than the value of the dtstart property of the same item The time given by the dtend property is not inclusive. For day-long events, therefore, the dtend property's value will be the day after the end of the event. A single property with the name dtend may be present within each item with the type , so long as that does not have a property with the name duration dtstart Gives the date and time at which the event starts. The value must be text that is either a valid date string or a valid global date and time string Exactly one property with the name dtstart must be present within each item with the type duration Gives the duration of the event. The value must be text that is a valid vevent duration string The duration represented is the sum of all the durations represented by integers in the value. A single property with the name duration may be present within each item with the type , so long as that does not have a property with the name dtend transp Gives whether the event is to be considered as consuming time on a calendar, for the purpose of free-busy time searches. The value must be text with one of the following values: opaque transparent A single property with the name transp may be present within each item with the type contact Gives the contact information for the event. The value must be text. Any number of properties with the name contact may be present within each item with the type url Gives a URL for the event. The value must be an absolute URL A single property with the name url may be present within each item with the type uid Gives a globally unique identifier corresponding to the event. The value must be text. A single property with the name uid may be present within each item with the type exdate Gives a date and time at which the event does not occur despite the recurrence rules. The value must be text that is either a valid date string or a valid global date and time string Any number of properties with the name exdate may be present within each item with the type rdate Gives a date and time at which the event recurs. The value must be text that is one of the following: valid date string valid global date and time string valid global date and time string followed by a U+002F SOLIDUS character (/) followed by a second valid global date and time string representing a later time. valid global date and time string followed by a U+002F SOLIDUS character (/) followed by a valid vevent duration string Any number of properties with the name rdate may be present within each item with the type rrule Gives a rule for finding dates and times at which the event occurs. The value must be text that matches the RECUR value type defined in iCalendar [RFC5545] A single property with the name rrule may be present within each item with the type created Gives the date and time at which the event information was first created in a calendaring system. The value must be text that is a valid global date and time string A single property with the name created may be present within each item with the type last-modified Gives the date and time at which the event information was last modified in a calendaring system. The value must be text that is a valid global date and time string A single property with the name last-modified may be present within each item with the type sequence Gives a revision number for the event information. The value must be text that is a valid non-negative integer A single property with the name sequence may be present within each item with the type A string is a valid vevent duration string if it matches the following pattern: A U+0050 LATIN CAPITAL LETTER P character (P). One of the following: valid non-negative integer followed by a U+0057 LATIN CAPITAL LETTER W character (W). The integer represents a duration of that number of weeks. At least one, and possible both in this order, of the following: valid non-negative integer followed by a U+0044 LATIN CAPITAL LETTER D character (D). The integer represents a duration of that number of days. A U+0054 LATIN CAPITAL LETTER T character (T) followed by any one of the following, or the first and second of the following in that order, or the second and third of the following in that order, or all three of the following in this order: valid non-negative integer followed by a U+0048 LATIN CAPITAL LETTER H character (H). The integer represents a duration of that number of hours. valid non-negative integer followed by a U+004D LATIN CAPITAL LETTER M character (M). The integer represents a duration of that number of minutes. valid non-negative integer followed by a U+0053 LATIN CAPITAL LETTER S character (S). The integer represents a duration of that number of seconds. 5.3.2.1 Conversion to iCalendar Given a list of nodes nodes in a Document , a user agent must run the following algorithm to extract any vEvent data represented by those nodes If none of the nodes in nodes are items with the type , then there is no vEvent data. Abort the algorithm, returning nothing. Let output be an empty string. Add an iCalendar line with the type " BEGIN " and the value " VCALENDAR " to output Add an iCalendar line with the type " PRODID " and the value equal to a user-agent-specific string representing the user agent to output Add an iCalendar line with the type " VERSION " and the value " 2.0 " to output For each node node in nodes that is an item with the type , run the following steps: Add an iCalendar line with the type " BEGIN " and the value " VEVENT " to output Add an iCalendar line with the type " DTSTAMP " and a value consisting of an iCalendar DATE-TIME string representing the current date and time, with the annotation " VALUE=DATE-TIME ", to output [RFC5545] For each element element that is a property of the item node : for each name name in element 's property names , run the appropriate set of substeps from the following list: If the property's value is an item Skip the property. If the property is dtend If the property is dtstart If the property is exdate If the property is rdate If the property is created If the property is last-modified Let value be the result of stripping all U+002D HYPHEN-MINUS (-) and U+003A COLON (:) characters from the property's value If the property's value is a valid date string then add an iCalendar line with the type name and the value value to output , with the annotation VALUE=DATE ". Otherwise, if the property's value is a valid global date and time string then add an iCalendar line with the type name and the value value to output , with the annotation " VALUE=DATE-TIME ". Otherwise skip the property. Otherwise Add an iCalendar line with the type name and the property's value to output Add an iCalendar line with the type " END " and the value " VEVENT " to output Add an iCalendar line with the type " END " and the value VCALENDAR " to output When the above algorithm says that the user agent is to add an iCalendar line consisting of a type type , a value value , and optionally an annotation, to a string output , it must run the following steps: Let line be an empty string. Append type converted to ASCII uppercase , to line If there is an annotation: Append a U+003B SEMICOLON character (;) to line Append the annotation to line Append a U+003A COLON character (:) to line Prefix every U+005C REVERSE SOLIDUS character (\) in value with another U+005C REVERSE SOLIDUS character (\). Prefix every U+002C COMMA character (,) in value with a U+005C REVERSE SOLIDUS character (\). Prefix every U+003B SEMICOLON character (;) in value with a U+005C REVERSE SOLIDUS character (\). Replace every U+000D CARRIAGE RETURN U+000A LINE FEED character pair (CRLF) in value with a U+005C REVERSE SOLIDUS character (\) followed by a U+006E LATIN SMALL LETTER N character (n). Replace every remaining U+000D CARRIAGE RETURN (CR) or U+000A LINE FEED (LF) character in value with a U+005C REVERSE SOLIDUS character (\) followed by a U+006E LATIN SMALL LETTER N character (n). Append value to line Let maximum length be 75. While line 's code point length is greater than maximum length Append the first maximum length code points of line to output Remove the first maximum length code points from line Append a U+000D CARRIAGE RETURN character (CR) to output Append a U+000A LINE FEED character (LF) to output Append a U+0020 SPACE character to output Let maximum length be 74. Append (what remains of) line to output Append a U+000D CARRIAGE RETURN character (CR) to output Append a U+000A LINE FEED character (LF) to output This algorithm can generate invalid iCalendar output, if the input does not conform to the rules described for the item type and defined property names 5.3.2.2 Examples This section is non-normative. Here is an example of a page that uses the vEvent vocabulary to mark up an event: body itemscope itemtype "http://microformats.org/profile/hcalendar#vevent" ... h1 itemprop "summary" Bluesday Tuesday: Money Road h1 ... time itemprop "dtstart" datetime "2009-05-05T19:00:00Z" May 5th @ 7pm time (until time itemprop "dtend" datetime "2009-05-05T21:00:00Z" 9pm time ... href "http://livebrum.co.uk/2009/05/05/bluesday-tuesday-money-road" rel "bookmark" itemprop "url" Link to this page ... Location: span itemprop "location" The RoadHouse span > ... >< input type button value "Add to Calendar" onclick "location = getCalendar(this)" > ... meta itemprop "description" content "via livebrum.co.uk" body The getCalendar() function is left as an exercise for the reader. The same page could offer some markup, such as the following, for copy-and-pasting into blogs: div itemscope itemtype "http://microformats.org/profile/hcalendar#vevent" I'm going to strong itemprop "summary" Bluesday Tuesday: Money Road strong time itemprop "dtstart" datetime "2009-05-05T19:00:00Z" May 5th at 7pm time to time itemprop "dtend" datetime "2009-05-05T21:00:00Z" 9pm time at span itemprop "location" The RoadHouse span >< href "http://livebrum.co.uk/2009/05/05/bluesday-tuesday-money-road" itemprop "url" See this event on livebrum.co.uk meta itemprop "description" content "via livebrum.co.uk" div 5.3.3 Licensing works An item with the item type represents a work (e.g. an article, an image, a video, a song, etc). This type is primarily intended to allow authors to include licensing information for works. The following are the type's defined property names work Identifies the work being described. The value must be an absolute URL Exactly one property with the name work must be present within each item with the type title Gives the name of the work. A single property with the name title may be present within each item with the type author Gives the name or contact information of one of the authors or creators of the work. The value must be either an item with the type , or text. Any number of properties with the name author may be present within each item with the type license Identifies one of the licenses under which the work is available. The value must be an absolute URL Any number of properties with the name license may be present within each item with the type 5.3.3.1 Examples This section is non-normative. This example shows an embedded image entitled My Pond , licensed under the Creative Commons Attribution-Share Alike 4.0 International License and the MIT license simultaneously. figure itemscope itemtype "http://n.whatwg.org/work" img itemprop "work" src "mypond.jpeg" figcaption >< cite itemprop "title" My Pond cite > >< small Licensed under the itemprop "license" href "https://creativecommons.org/licenses/by-sa/4.0/" Creative Commons Attribution-Share Alike 4.0 International License and the itemprop "license" href "http://www.opensource.org/licenses/mit-license.php" MIT license small figcaption figure 5.4 Converting HTML to other formats 5.4.1 JSON Given a list of nodes nodes in a Document , a user agent must run the following algorithm to extract the microdata from those nodes into a JSON form Let result be an empty object. Let items be an empty array. For each node in nodes , check if the element is a top-level microdata item , and if it is then get the object for that element and add it to items Add an entry to result called " items " whose value is the array items Return the result of serializing result to JSON in the shortest possible way (meaning no whitespace between tokens, no unnecessary zero digits in numbers, and only using Unicode escapes in strings for characters that do not have a dedicated escape sequence), and with a lowercase " " used, when appropriate, in the representation of any numbers. [JSON] This algorithm returns an object with a single property that is an array, instead of just returning an array, so that it is possible to extend the algorithm in the future if necessary. When the user agent is to get the object for an item item optionally with a list of elements memory , it must run the following substeps: Let result be an empty object. If no memory was passed to the algorithm, let memory be an empty list. Add item to memory If the item has any item types , add an entry to result called " type " whose value is an array listing the item types of item , in the order they were specified on the itemtype attribute. If the item has a global identifier , add an entry to result called " id " whose value is the global identifier of item Let properties be an empty object. For each element element that has one or more property names and is one of the properties of the item item , in the order those elements are given by the algorithm that returns the properties of an item , run the following substeps: Let value be the property value of element If value is an item , then: If value is in memory , then let value be the string " ERROR ". Otherwise, get the object for value , passing a copy of memory , and then replace value with the object returned from those steps. For each name name in element 's property names , run the following substeps: If there is no entry named name in properties then add an entry named name to properties whose value is an empty array. Append value to the entry named name in properties Add an entry to result called " properties " whose value is the object properties Return result For example, take this markup: html lang "en" title My Blog title article itemscope itemtype "http://schema.org/BlogPosting" header h1 itemprop "headline" Progress report h1 >< time itemprop "datePublished" datetime "2013-08-29" today time > link itemprop "url" href "?comments=0" header All in all, he's doing well with his swim lessons. The biggest thing was he had trouble putting his head in, but we got it down. section h1 Comments h1 article itemprop "comment" itemscope itemtype "http://schema.org/UserComments" id "c1" link itemprop "url" href "#c1" footer Posted by: span itemprop "creator" itemscope itemtype "http://schema.org/Person" span itemprop "name" Greg span span > >< time itemprop "commentTime" datetime "2013-08-29" 15 minutes ago time > footer Ha! article article itemprop "comment" itemscope itemtype "http://schema.org/UserComments" id "c2" link itemprop "url" href "#c2" footer Posted by: span itemprop "creator" itemscope itemtype "http://schema.org/Person" span itemprop "name" Charlotte span span > >< time itemprop "commentTime" datetime "2013-08-29" 5 minutes ago time > footer When you say "we got it down"... article section article It would be turned into the following JSON by the algorithm above (supposing that the page's URL was ): "items" "type" "http://schema.org/BlogPosting" ], "properties" "headline" "Progress report" ], "datePublished" "2013-08-29" ], "url" "https://blog.example.com/progress-report?comments=0" ], "comment" "type" "http://schema.org/UserComments" ], "properties" "url" "https://blog.example.com/progress-report#c1" ], "creator" "type" "http://schema.org/Person" ], "properties" "name" "Greg" ], "commentTime" "2013-08-29" }, "type" "http://schema.org/UserComments" ], "properties" "url" "https://blog.example.com/progress-report#c2" ], "creator" "type" "http://schema.org/Person" ], "properties" "name" "Charlotte" ], "commentTime" "2013-08-29" User interaction 6.1 The hidden attribute Global_attributes/hidden Support in all current engines. Firefox Yes Safari Yes Chrome Yes Opera Yes Edge Yes Edge (Legacy) 12+ Internet Explorer 11 Firefox Android Yes Safari iOS Yes Chrome Android Yes WebView Android 4+ Samsung Internet Yes Opera Android Yes All HTML elements may have the hidden content attribute set. The hidden attribute is a boolean attribute . When specified on an element, it indicates that the element is not yet, or is no longer, directly relevant to the page's current state, or that it is being used to declare content to be reused by other parts of the page as opposed to being directly accessed by the user. User agents should not render elements that have the hidden attribute specified. This requirement may be implemented indirectly through the style layer. For example, an HTML+CSS user agent could implement these requirements using the rules suggested in the Rendering section Because this attribute is typically implemented using CSS, it's also possible to override it using CSS. For instance, a rule that applies 'display: block' to all elements will cancel the effects of the hidden attribute. Authors therefore have to take care when writing their style sheets to make sure that the attribute is still styled as expected. In the following skeletal example, the attribute is used to hide the web game's main screen until the user logs in: h1 The Example Game h1 section id "login" h2 h2 form ... form script function () // switch screens document getElementById 'login' ). hidden true document getElementById 'game' ). hidden false script section section id "game" hidden ... section The hidden attribute must not be used to hide content that could legitimately be shown in another presentation. For example, it is incorrect to use hidden to hide panels in a tabbed dialog, because the tabbed interface is merely a kind of overflow presentation — one could equally well just show all the form controls in one big page with a scrollbar. It is similarly incorrect to use this attribute to hide content just from one presentation — if something is marked hidden , it is hidden from all presentations, including, for instance, screen readers. Elements that are not themselves hidden must not hyperlink to elements that are hidden . The for attributes of label and output elements that are not themselves hidden must similarly not refer to elements that are hidden . In both cases, such references would cause user confusion. Elements and scripts may, however, refer to elements that are hidden in other contexts. For example, it would be incorrect to use the href attribute to link to a section marked with the hidden attribute. If the content is not applicable or relevant, then there is no reason to link to it. It would be fine, however, to use the ARIA aria-describedby attribute to refer to descriptions that are themselves hidden . While hiding the descriptions implies that they are not useful alone, they could be written in such a way that they are useful in the specific context of being referenced from the elements that they describe. Similarly, a canvas element with the hidden attribute could be used by a scripted graphics engine as an off-screen buffer, and a form control could refer to a hidden form element using its form attribute. Elements in a section hidden by the hidden attribute are still active, e.g. scripts and form controls in such sections still execute and submit respectively. Only their presentation to the user changes. HTMLElement/hidden Support in all current engines. Firefox 1+ Safari 5.1+ Chrome 6+ Opera 11.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 11 Firefox Android 4+ Safari iOS 5+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 12+ The hidden IDL attribute must reflect the content attribute of the same name. 6.2 Inert subtrees This section does not define or create any content attribute named "inert". This section merely defines an abstract concept of inertness A node (in particular elements and text nodes) can be marked as inert . When a node is inert , then the user agent must act as if the node was absent for the purposes of targeting user interaction events, may ignore the node for the purposes of find-in-page , and may prevent the user from selecting text in that node. User agents should allow the user to override the restrictions on search and text selection, however. For example, consider a page that consists of just a single inert paragraph positioned in the middle of a body . If a user moves their pointing device from the body over to the inert paragraph and clicks on the paragraph, no mouseover event would be fired, and the mousemove and click events would be fired on the body element rather than the paragraph. When a node is inert, it generally cannot be focused. Inert nodes that are commands will also get disabled. While a browsing context container is marked as inert , its nested browsing context 's active document , and all nodes in that Document , must be marked as inert An element is expressly inert if it is inert and its node document is not inert Document document is blocked by a modal dialog subject if subject is the topmost dialog element in document 's top layer . While document is so blocked, every node that is connected to document , with the exception of the subject element and its shadow-including descendants , must be marked inert . (The elements excepted by this paragraph can additionally be marked inert through other means; being part of a modal dialog does not "protect" a node from being marked inert .) The dialog element's showModal() method causes this mechanism to trigger, by adding the dialog element to its node document 's top layer 6.3 Tracking user activation To prevent abuse of certain APIs that could be annoying to users (e.g., opening popups or vibrating phones), user agents allow these APIs only when the user is actively interacting with the web page or has interacted with the page at least once. This "active interaction" state is maintained through the mechanisms defined in this section. 6.3.1 Data model For the purpose of tracking user activation, each Window has a last activation timestamp . This is a number indicating the last time got an activation notification . It corresponds to a DOMHighResTimeStamp value except for two cases: positive infinity indicates that has never been activated, while negative infinity indicates that a user activation-gated API has consumed the last user activation of . The initial value is positive infinity. A user agent also defines a transient activation duration , which is a constant number indicating how long a user activation is available for certain user activation-gated APIs (e.g., for opening popups). The transient activation duration is expected be at most a few seconds, so that the user can possibly perceive the link between an interaction with the page and the page calling the activation-gated API. These two values imply two boolean user activation states for Sticky activation When the current high resolution time is greater than or equal to the last activation timestamp in is said to have sticky activation This is 's historical activation state, indicating whether the user has ever interacted in . It starts false, then changes to true (and never changes back to false) when gets the very first activation notification Transient activation When the current high resolution time is greater than or equal to the last activation timestamp in , and less than the last activation timestamp in plus the transient activation duration , then is said to have transient activation This is 's current activation state, indicating whether the user has interacted in recently. This starts with a false value, and remains true for a limited time after every activation notification gets. The transient activation state is considered expired if it becomes false because the transient activation duration time has elapsed since the last user activation. Note that it can become false even before the expiry time through an activation consumption 6.3.2 Processing model When a user interaction in a browsing context causes firing of an activation triggering input event in 's active document , the user agent must perform the following activation notification steps before dispatching the event: Let browsingContexts be a list consisting of: all ancestor browsing contexts of , and all the descendant browsing contexts of that have active documents from the same origin as that of Let windows be the list of Window objects constructed by taking the active window of each item in browsingContexts For each window in windows , set window 's last activation timestamp to the current high resolution time An activation triggering input event is any event whose isTrusted attribute is true and whose type is one of: change click contextmenu dblclick mouseup pointerup reset submit touchend The event set is inconsistent across major browsers. See issue #3849 Activation consuming APIs defined in this and other specifications can consume user activation by performing the following steps, given a Window If 's browsing context is null, then return. Let top be 's browsing context 's top-level browsing context Let browsingContexts be the list of the descendant browsing contexts of top 's active document Append top to browsingContexts Let windows be the list of Window objects constructed by taking the active window of each item in browsingContexts For each window in windows , if window 's last activation timestamp is not positive infinity, then set window 's last activation timestamp to negative infinity. The spec is not clear about how to traverse a tree of documents. See issue #5020 Note the asymmetry in the sets of browsing contexts in the page that are affected by an activation notification vs an activation consumption : an activation consumption changes (to false) the transient activation states for all browsing contexts in the page, but an activation notification changes (to true) the states for a subset of those browsing contexts. The exhaustive nature of consumption here is deliberate: it prevents malicious sites from making multiple calls to an activation consuming API from a single user activation (possibly by exploiting a deep hierarchy of iframe s). 6.3.3 APIs gated by user activation APIs that are dependent on user activation are classified into three different levels. The levels are as follows, sorted by their "strength of dependence" on user activation (from weakest to strongest): Sticky activation-gated APIs These APIs require the sticky activation state to be true, so they are blocked until the very first user activation. Transient activation-gated APIs These APIs require the transient activation state to be true, but they don't consume it, so multiple calls are allowed per user activation until the transient state expires Transient activation-consuming APIs These APIs require the transient activation state to be true, and they consume user activation in each call to prevent multiple calls per user activation. 6.4 Activation behavior of elements Certain elements in HTML have an activation behavior , which means that the user can activate them. This is always caused by a click event. The user agent should allow the user to manually trigger elements that have an activation behavior , for instance using keyboard or voice input, or through mouse clicks. When the user triggers an element with a defined activation behavior in a manner other than clicking it, the default action of the interaction event must be to fire a click event at the element. element click () HTMLElement/click Support in all current engines. Firefox 3+ Safari 6+ Chrome 9+ Opera 10.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 5.5+ Firefox Android 4+ Safari iOS 6+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11+ Acts as if the element was clicked. Each element has an associated click in progress flag , which is initially unset. The click() method must run the following steps: If this element is a form control that is disabled , then return. If this element's click in progress flag is set, then return. Set this element's click in progress flag Fire a synthetic pointer event named click at this element, with the not trusted flag set. Unset this element's click in progress flag 6.5 Focus 6.5.1 Introduction This section is non-normative. An HTML user interface typically consists of multiple interactive widgets, such as form controls, scrollable regions, links, dialog boxes, browser tabs, and so forth. These widgets form a hierarchy, with some (e.g. browser tabs, dialog boxes) containing others (e.g. links, form controls). When interacting with an interface using a keyboard, key input is channeled from the system, through the hierarchy of interactive widgets, to an active widget, which is said to be focused Consider an HTML application running in a browser tab running in a graphical environment. Suppose this application had a page with some text controls and links, and was currently showing a modal dialog, which itself had a text control and a button. The hierarchy of focusable widgets, in this scenario, would include the browser window, which would have, amongst its children, the browser tab containing the HTML application. The tab itself would have as its children the various links and text controls, as well as the dialog. The dialog itself would have as its children the text control and the button. If the widget with focus in this example was the text control in the dialog box, then key input would be channeled from the graphical system to ① the web browser, then to ② the tab, then to ③ the dialog, and finally to ④ the text control. Keyboard events are always targeted at this focused element. 6.5.2 Data model top-level browsing context has system focus when it can receive keyboard input channeled from the operating system. System focus is lost when a browser window loses focus, but might also be lost to other system widgets in the browser window such as a URL bar. The term focusable area is used to refer to regions of the interface that can further become the target of such keyboard input. Focusable areas can be elements, parts of elements, or other regions managed by the user agent. Each focusable area has a DOM anchor , which is a Node object that represents the position of the focusable area in the DOM. (When the focusable area is itself a Node , it is its own DOM anchor .) The DOM anchor is used in some APIs as a substitute for the focusable area when there is no other DOM object to represent the focusable area The following table describes what objects can be focusable areas . The cells in the left column describe objects that can be focusable areas ; the cells in the right column describe the DOM anchors for those elements. (The cells that span both columns are non-normative examples.) Focusable area DOM anchor Examples Elements that meet all the following criteria: the element's tabindex value is non-null, or the element is determined by the user agent to be focusable; the element is either not a shadow host , or has a shadow root whose delegates focus is false; the element is not actually disabled the element is not expressly inert the element is either being rendered or being used as relevant canvas fallback content The element itself. iframe type=text> , sometimes (depending on platform conventions). The shapes of area elements in an image map associated with an img element that is being rendered and is not expressly inert The img element. In the following example, the area element creates two shapes, one on each image. The DOM anchor of the first shape is the first img element, and the DOM anchor of the second shape is the second img element. map id wallmap >< area alt "Enter Door" coords "10,10,100,200" href "door.html" > map ... img src "images/innerwall.jpeg" alt "There is a white wall here, with a door." usemap "#wallmap" ... img src "images/outerwall.jpeg" alt "There is a red wall here, with a door." usemap "#wallmap" The user-agent provided subwidgets of elements that are being rendered and are not actually disabled or expressly inert The element for which the focusable area is a subwidget. The controls in the user interface for a video element, the up and down buttons in a spin-control version of , the part of a details element's rendering that enables the element to be opened or closed using keyboard input. The scrollable regions of elements that are being rendered and are not expressly inert The element for which the box that the scrollable region scrolls was created. The CSS 'overflow' property's 'scroll' value typically creates a scrollable region. The viewport of a Document that has a non-null browsing context and is not inert The Document for which the viewport was created. The contents of an iframe Any other element or part of an element determined by the user agent to be a focusable area, especially to aid with accessibility or to better match platform conventions. The element. A user agent could make all list item bullets sequentially focusable , so that a user can more easily navigate lists. Similarly, a user agent could make all elements with title attributes sequentially focusable , so that their advisory information can be accessed. browsing context container (e.g. an iframe ) is a focusable area , but key events routed to a browsing context container get immediately routed to its nested browsing context 's active document . Similarly, in sequential focus navigation a browsing context container essentially acts merely as a placeholder for its nested browsing context 's active document One focusable area in each Document is designated the focused area of the document . Which control is so designated changes over time, based on algorithms in this specification. The currently focused area of a top-level browsing context topLevelBC at any particular time is the focusable area -or-null returned by this algorithm: If topLevelBC does not have system focus , then return null. Let candidate be topLevelBC 's active document While candidate 's focused area is a browsing context container with a non-null nested browsing context : set candidate to the active document of that browsing context container 's nested browsing context If candidate 's focused area is non-null, set candidate to candidate 's focused area Return candidate The current focus chain of a top-level browsing context topLevelBC at any particular time is the focus chain of the currently focused area of topLevelBC , if topLevelBC is non-null, or an empty list otherwise. An element that is the DOM anchor of a focusable area is said to gain focus when that focusable area becomes the currently focused area of a top-level browsing context . When an element is the DOM anchor of a focusable area of the currently focused area of a top-level browsing context , it is focused The focus chain of a focusable area subject is the ordered list constructed as follows: Let output be an empty list Let currentObject be subject While true: Append currentObject to output If currentObject is an area element's shape, then append that area element to output Otherwise, if currentObject 's DOM anchor is an element that is not currentObject itself, then append currentObject 's DOM anchor to output If currentObject is a focusable area , then set currentObject to currentObject 's DOM anchor 's node document Otherwise, if currentObject is a Document whose browsing context is a child browsing context then set currentObject to currentObject 's browsing context 's container Otherwise, break Return output The chain starts with subject and (if subject is or can be the currently focused area of a top-level browsing context ) continues up the focus hierarchy up to the Document of the top-level browsing context All elements that are focusable areas are said to be focusable There are two special types of focusability for focusable areas focusable area is said to be sequentially focusable if it is included in its Document 's sequential focus navigation order and the user agent determines that it is sequentially focusable. focusable area is said to be click focusable if the user agent determines that it is click focusable. User agents should consider focusable areas with non-null tabindex values to be click focusable. Elements which are not focusable are not focusable areas , and thus not sequentially focusable and not click focusable Being focusable is a statement about whether an element can be focused programmatically, e.g. via the focus() method or autofocus attribute. In contrast, sequentially focusable and click focusable govern how the user agent responds to user interaction: respectively, to sequential focus navigation and as activation behavior The user agent might determine that an element is not sequentially focusable even if it is focusable and is included in its Document 's sequential focus navigation order , according to user preferences. For example, macOS users can set the user agent to skip non-form control elements, or can skip links when doing sequential focus navigation with just the Tab key (as opposed to using both the Option and Tab keys). Similarly, the user agent might determine that an element is not click focusable even if it is focusable . For example, in some user agents, clicking on a non-editable form control does not focus it, i.e. the user agent has determined that such controls are not click focusable. Thus, an element can be focusable , but neither sequentially focusable nor click focusable . For example, in some user agents, a non-editable form-control with a negative-integer tabindex value would not be focusable via user interaction, only via programmatic APIs. When a user activates click focusable focusable area , the user agent must run the focusing steps on the focusable area with focus trigger set to " click ". Note that focusing is not an activation behavior , i.e. calling the click() method on an element or dispatching a synthetic click event on it won't cause the element to get focused. A node is a focus navigation scope owner if it is a document , a shadow host or a slot Each focus navigation scope owner has a focus navigation scope , which is a list of elements. Its contents are determined as follows: Every element element has an associated focus navigation owner , which is either null or a focus navigation scope owner . It is determined by the following algorithm: If element 's parent is null, then return null. If element 's parent is a shadow host , then return element 's assigned slot If element 's parent is a shadow root , then return the parent's host If element 's parent is the document element , then return the parent's node document Return element 's parent's associated focus navigation owner Then, the contents of a given focus navigation scope owner owner 's focus navigation scope are all elements whose associated focus navigation owner is owner The order of elements within a focus navigation scope does not impact any of the algorithms in this specification. Ordering only becomes important for the tabindex-ordered focus navigation scope and flattened tabindex-ordered focus navigation scope concepts defined below. tabindex-ordered focus navigation scope is a list of focusable areas and focus navigation scope owners . Every focus navigation scope owner owner has tabindex-ordered focus navigation scope , whose contents are determined as follows: It contains all elements in owner 's focus navigation scope that are themselves focus navigation scope owners except the elements whose tabindex value is a negative integer. It contains all of the focusable areas whose DOM anchor is an element in owner 's focus navigation scope except the focusable areas whose tabindex value is a negative integer. The order within a tabindex-ordered focus navigation scope is determined by each element's tabindex value , as described in the section below. The rules there do not give a precise ordering, as they are composed mostly of "should" statements and relative orderings. flattened tabindex-ordered focus navigation scope is a list of focusable areas . Every focus navigation scope owner owner owns a distinct flattened tabindex-ordered focus navigation scope whose contents are determined by the following algorithm: Let result be a clone of owner 's tabindex-ordered focus navigation scope For each item of result If item is not a focus navigation scope owner , then continue If item is not a focusable area , then replace item with all of the items in item 's flattened tabindex-ordered focus navigation scope Otherwise, insert the contents of item 's flattened tabindex-ordered focus navigation scope after item 6.5.3 The tabindex attribute Global_attributes/tabindex Support in all current engines. Firefox Yes Safari Yes Chrome Yes Opera Yes Edge Yes Edge (Legacy) 12+ Internet Explorer Yes Firefox Android Yes Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes The tabindex content attribute allows authors to make an element and regions that have the element as its DOM anchor be focusable areas , allow or prevent them from being sequentially focusable , and determine their relative ordering for sequential focus navigation The name "tab index" comes from the common use of the Tab key to navigate through the focusable elements. The term "tabbing" refers to moving forward through sequentially focusable focusable areas The tabindex attribute, if specified, must have a value that is a valid integer . Positive numbers specify the relative position of the element's focusable areas in the sequential focus navigation order , and negative numbers indicate that the control is not sequentially focusable Developers should use caution when using values other than 0 or −1 for their tabindex attributes as this is complicated to do correctly. The following provides a non-normative summary of the behaviors of the possible tabindex attribute values. The below processing model gives the more precise rules. omitted (or non-integer values) The user agent will decide whether the element is focusable , and if it is, whether it is sequentially focusable or click focusable (or both). −1 (or other negative integer values) Causes the element to be focusable , and indicates that the author would prefer the element to be click focusable but not sequentially focusable . The user agent might ignore this preference for click and sequential focusability, e.g., for specific element types according to platform conventions, or for keyboard-only users. Causes the element to be focusable , and indicates that the author would prefer the element to be both click focusable and sequentially focusable . The user agent might ignore this preference for click and sequential focusability. positive integer values Behaves the same as 0, but in addition creates a relative ordering within a tabindex-ordered focus navigation scope , so that elements with higher tabindex attribute value come later. Note that the tabindex attribute cannot be used to make an element non-focusable. The only way a page author can do that is by disabling the element, or making it inert The tabindex value of an element is the value of its tabindex attribute, parsed using the rules for parsing integers . If parsing fails or the attribute is not specified, then the tabindex value is null. The tabindex value of a focusable area is the tabindex value of its DOM anchor The tabindex value of an element must be interpreted as follows: If the value is null The user agent should follow platform conventions to determine if the element should be considered as a focusable area and if so, whether the element and any focusable areas that have the element as their DOM anchor are sequentially focusable , and if so, what their relative position in their tabindex-ordered focus navigation scope is to be. If the element is a focus navigation scope owner , it must be included in its tabindex-ordered focus navigation scope even if it is not a focusable area The relative ordering within a tabindex-ordered focus navigation scope for elements and focusable areas that belong to the same focus navigation scope and whose tabindex value is null should be in shadow-including tree order Modulo platform conventions, it is suggested that the following elements should be considered as focusable areas and be sequentially focusable elements that have an href attribute button elements input elements whose type attribute are not in the Hidden state select elements textarea elements summary elements that are the first summary element child of a details element Elements with a draggable attribute set, if that would enable the user agent to allow the user to begin drag operations for those elements without the use of a pointing device Editing hosts Browsing context containers If the value is a negative integer The user agent must consider the element as a focusable area , but should omit the element from any tabindex-ordered focus navigation scope One valid reason to ignore the requirement that sequential focus navigation not allow the author to lead to the element would be if the user's only mechanism for moving the focus is sequential focus navigation. For instance, a keyboard-only user would be unable to click on a text control with a negative tabindex , so that user's user agent would be well justified in allowing the user to tab to the control regardless. If the value is a zero The user agent must allow the element to be considered as a focusable area and should allow the element and any focusable areas that have the element as their DOM anchor to be sequentially focusable The relative ordering within a tabindex-ordered focus navigation scope for elements and focusable areas that belong to the same focus navigation scope and whose tabindex value is zero should be in shadow-including tree order If the value is greater than zero The user agent must allow the element to be considered as a focusable area and should allow the element and any focusable areas that have the element as their DOM anchor to be sequentially focusable , and should place the element — referenced as candidate below — and the aforementioned focusable areas in the tabindex-ordered focus navigation scope where the element is a part of so that, relative to other elements and focusable areas that belong to the same focus navigation scope , they are: before any focusable area whose DOM anchor is an element whose tabindex attribute has been omitted or whose value, when parsed, returns an error, before any focusable area whose DOM anchor is an element whose tabindex attribute has a value equal to or less than zero, after any focusable area whose DOM anchor is an element whose tabindex attribute has a value greater than zero but less than the value of the tabindex attribute on candidate after any focusable area whose DOM anchor is an element whose tabindex attribute has a value equal to the value of the tabindex attribute on candidate but that is located earlier than candidate in shadow-including tree order before any focusable area whose DOM anchor is an element whose tabindex attribute has a value equal to the value of the tabindex attribute on candidate but that is located later than candidate in shadow-including tree order , and before any focusable area whose DOM anchor is an element whose tabindex attribute has a value greater than the value of the tabindex attribute on candidate HTMLOrForeignElement/tabIndex Support in all current engines. Firefox 1+ Safari 3.1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 18 Internet Explorer 🔰 5.5+ Firefox Android 4+ Safari iOS 2+ Chrome Android 18+ WebView Android 4.4+ Samsung Internet 1.0+ Opera Android 12.1+ The tabIndex IDL attribute must reflect the value of the tabindex content attribute. The default value is 0 if the element is an area button frame iframe input object select textarea , or SVG element, or is a summary element that is a summary for its parent details . The default value is −1 otherwise. The varying default value based on element type is a historical artifact. 6.5.4 Processing model To get the focusable area for a focus target that is either an element that is not a focusable area , or is a browsing context , given an optional string focus trigger , run the first matching set of steps from the following list: If focus target is an area element with one or more shapes that are focusable areas Return the shape corresponding to the first img element in tree order that uses the image map to which the area element belongs. If focus target is an element with one or more scrollable regions that are focusable areas Return the element's first scrollable region, according to a pre-order, depth-first traversal of the flat tree [CSSSCOPING] If focus target is the document element of its Document Return the Document 's viewport If focus target is a browsing context Return the browsing context 's active document If focus target is a browsing context container with a non-null nested browsing context Return the browsing context container 's nested browsing context 's active document If focus target is a shadow host whose shadow root 's delegates focus is true If focus target is a shadow-including inclusive ancestor of the currently focused area of a top-level browsing context 's DOM anchor then return null. Otherwise: If focus trigger is " click ", then let possible focus delegates be the list of all click focusable focusable areas whose DOM anchor is a descendant of focus target in the flat tree Otherwise, let possible focus delegates be the list of all focusable areas whose DOM anchor is a descendant of focus target in the flat tree Return the first focusable area in tree order of their DOM anchors in possible focus delegates , or null if possible focus delegates is empty. For sequential focusability , the handling of shadow hosts and delegates focus is done when constructing the sequential focus navigation order . That is, the focusing steps will never be called on such shadow hosts as part of sequential focus navigation. Otherwise Return null. The focusing steps for an object new focus target that is either a focusable area , or an element that is not a focusable area , or a browsing context , are as follows. They can optionally be run with a fallback target and a string focus trigger If new focus target is not a focusable area , then set new focus target to the result of getting the focusable area for new focus target , given focus trigger if it was passed. If new focus target is null, then: If no fallback target was specified, then return. Otherwise, set new focus target to the fallback target If new focus target is a browsing context container with non-null nested browsing context , then set new focus target to the nested browsing context 's active document If new focus target is a focusable area and its DOM anchor is inert , then return. If new focus target is the currently focused area of a top-level browsing context , then return. Let old chain be the current focus chain of the top-level browsing context in which new focus target finds itself. Let new chain be the focus chain of new focus target Run the focus update steps with old chain new chain , and new focus target respectively. User agents must immediately run the focusing steps for a focusable area or browsing context candidate whenever the user attempts to move the focus to candidate The unfocusing steps for an object old focus target that is either a focusable area or an element that is not a focusable area are as follows: If old focus target is inert , then return. If old focus target is an area element and one of its shapes is the currently focused area of a top-level browsing context , or, if old focus target is an element with one or more scrollable regions, and one of them is the currently focused area of a top-level browsing context , then let old focus target be that currently focused area of a top-level browsing context Let old chain be the current focus chain of the top-level browsing context in which old focus target finds itself. If old focus target is not one of the entries in old chain , then return. If old focus target is not a focusable area , then return. Let topDocument be old chain 's last entry. If topDocument 's browsing context has system focus , then run the focusing steps for topDocument 's viewport Otherwise, apply any relevant platform-specific conventions for removing system focus from topDocument 's browsing context , and run the focus update steps with old chain , an empty list, and null respectively. When the currently focused area of a top-level browsing context is somehow unfocused without another element being explicitly focused in its stead, the user agent must immediately run the unfocusing steps for that object. The unfocusing steps do not always result in the focus changing, even when applied to the currently focused area of a top-level browsing context . For example, if the currently focused area of a top-level browsing context is a viewport , then it will usually keep its focus regardless until another focusable area is explicitly focused with the focusing steps Focus fixup rule : When the designated focused area of the document is removed from that Document in some way (e.g. it stops being a focusable area , it is removed from the DOM, it becomes expressly inert , etc.), designate the Document 's viewport to be the new focused area of the document For example, this might happen because an element is removed from its Document , or has a hidden attribute added. It might also happen to an input element when the element gets disabled In a Document whose focused area is a button element, removing, disabling, or hiding that button would cause the page's new focused area to be the viewport of the Document . This would, in turn, be reflected through the activeElement API as the body element The focus update steps , given an old chain , a new chain , and a new focus target respectively, are as follows: If the last entry in old chain and the last entry in new chain are the same, pop the last entry from old chain and the last entry from new chain and redo this step. For each entry entry in old chain , in order, run these substeps: If entry is an input element, and the change event applies to the element, and the element does not have a defined activation behavior , and the user has changed the element's value or its list of selected files while the control was focused without committing that change (such that it is different to what it was when the control was first focused), then fire an event named change at the element, with the bubbles attribute initialized to true. If entry is an element, let blur event target be entry If entry is a Document object, let blur event target be that Document object's relevant global object Otherwise, let blur event target be null. If entry is the last entry in old chain , and entry is an Element , and the last entry in new chain is also an Element , then let related blur target be the last entry in new chain . Otherwise, let related blur target be null. If blur event target is not null, fire a focus event named blur at blur event target , with related blur target as the related target. In some cases, e.g. if entry is an area element's shape, a scrollable region, or a viewport , no event is fired. Apply any relevant platform-specific conventions for focusing new focus target (For example, some platforms select the contents of a text control when that control is focused.) For each entry entry in new chain , in reverse order, run these substeps: If entry is a focusable area : designate entry as the focused area of the document If entry is an element, let focus event target be entry If entry is a Document object, let focus event target be that Document object's relevant global object Otherwise, let focus event target be null. If entry is the last entry in new chain , and entry is an Element , and the last entry in old chain is also an Element , then let related focus target be the last entry in old chain . Otherwise, let related focus target be null. If focus event target is not null, fire a focus event named focus at focus event target , with related focus target as the related target. In some cases, e.g. if entry is an area element's shape, a scrollable region, or a viewport , no event is fired. To fire a focus event named at an element with a given related target fire an event named at , using FocusEvent , with the relatedTarget attribute initialized to the view attribute initialized to 's node document 's relevant global object , and the composed flag set. When a key event is to be routed in a top-level browsing context , the user agent must run the following steps: Let target area be the currently focused area of the top-level browsing context Assert: target area is not null, since key events are only routed to top-level browsing contexts that have system focus If target area is a focusable area , let target node be target area 's DOM anchor . Otherwise, target area is a dialog ; let target node be target area If target node is a Document that has a body element , then let target node be the body element of that Document Otherwise, if target node is a Document object that has a non-null document element , then let target node be that document element If target node is not inert , then: It is possible for the currently focused area of a top-level browsing context to be inert , for example if a modal dialog is shown , and then that dialog element is made inert . It is likely to be the result of a logic error in the application, though. Let canHandle be the result of dispatching the key event at target node If canHandle is true, then let target area handle the key event. This might include firing a click event at target node The has focus steps , given a Document object target are as follows: If target 's browsing context 's top-level browsing context does not have system focus , then return false. Let candidate be target 's top-level browsing context 's active document While true: If candidate is target , then return true. If the focused area of candidate is a browsing context container with a non-null nested browsing context , then set candidate to the active document of that browsing context container 's nested browsing context Otherwise, return false. 6.5.5 Sequential focus navigation Each Document has a sequential focus navigation order , which orders some or all of the focusable areas in the Document relative to each other. Its contents and ordering are given by the flattened tabindex-ordered focus navigation scope of the Document Per the rules defining the flattened tabindex-ordered focus navigation scope , the ordering is not necessarily related to the tree order of the Document If a focusable area is omitted from the sequential focus navigation order of its Document , then it is unreachable via sequential focus There can also be a sequential focus navigation starting point . It is initially unset. The user agent may set it when the user indicates that it should be moved. For example, the user agent could set it to the position of the user's click if the user clicks on the document contents. User agents are required to set the sequential focus navigation starting point to the target element when navigating to a fragment When the user requests that focus move from the currently focused area of a top-level browsing context to the next or previous focusable area (e.g. as the default action of pressing the tab key), or when the user requests that focus sequentially move to a top-level browsing context in the first place (e.g. from the browser's location bar), the user agent must use the following algorithm: Let starting point be the currently focused area of a top-level browsing context , if the user requested to move focus sequentially from there, or else the top-level browsing context itself, if the user instead requested to move focus from outside the top-level browsing context If there is a sequential focus navigation starting point defined and it is inside starting point , then let starting point be the sequential focus navigation starting point instead. Let direction be forward if the user requested the next control, and backward if the user requested the previous control. Typically, pressing tab requests the next control, and pressing shift tab requests the previous control. Loop : Let selection mechanism be sequential if the starting point is a browsing context or if starting point is in its Document 's sequential focus navigation order Otherwise, starting point is not in its Document 's sequential focus navigation order ; let selection mechanism be DOM Let candidate be the result of running the sequential navigation search algorithm with starting point direction , and selection mechanism as the arguments. If candidate is not null, then run the focusing steps for candidate and return. Otherwise, unset the sequential focus navigation starting point If starting point is the top-level browsing context , or a focusable area in the top-level browsing context , the user agent should transfer focus to its own controls appropriately (if any), honouring direction , and then return. For example, if direction is backward , then the last sequentially focusable control before the browser's rendering area would be the control to focus. If the user agent has no sequentially focusable controls — a kiosk-mode browser, for instance — then the user agent may instead restart these steps with the starting point being the top-level browsing context itself. Otherwise, starting point is a focusable area in a child browsing context . Set starting point to that child browsing context 's container and return to the step labeled loop The sequential navigation search algorithm consists of the following steps. This algorithm takes three arguments: starting point direction and selection mechanism Pick the appropriate cell from the following table, and follow the instructions in that cell. The appropriate cell is the one that is from the column whose header describes direction and from the first row whose header describes starting point and selection mechanism direction is forward direction is backward starting point is a browsing context Let candidate be the first suitable sequentially focusable area in starting point 's active document , if any; or else null Let candidate be the last suitable sequentially focusable area in starting point 's active document , if any; or else null selection mechanism is DOM Let candidate be the first suitable sequentially focusable area in the home document following starting point , if any; or else null Let candidate be the last suitable sequentially focusable area in the home document preceding starting point , if any; or else null selection mechanism is sequential Let candidate be the first suitable sequentially focusable area in the home sequential focus navigation order following starting point , if any; or else null Let candidate be the last suitable sequentially focusable area in the home sequential focus navigation order preceding starting point , if any; or else null suitable sequentially focusable area is a focusable area whose DOM anchor is not inert and is sequentially focusable The home document is the Document to which starting point belongs. The home sequential focus navigation order is the sequential focus navigation order to which starting point belongs. The home sequential focus navigation order is the document 's sequential focus navigation order , but is only used when the starting point is in that sequential focus navigation order (when it's not, selection mechanism will be DOM ). If candidate is a browsing context container with a non-null nested browsing context , then let new candidate be the result of running the sequential navigation search algorithm with candidate 's nested browsing context as the first argument, direction as the second, and sequential as the third. If new candidate is null, then let starting point be candidate , and return to the top of this algorithm. Otherwise, let candidate be new candidate Return candidate 6.5.6 Focus management APIs dictionary FocusOptions boolean preventScroll false }; documentOrShadowRoot activeElement Document/activeElement Support in all current engines. Firefox 3+ Safari 4+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 6+ Firefox Android 4+ Safari iOS 3.2+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ ShadowRoot/activeElement Support in all current engines. Firefox 63+ Safari 10.1+ Chrome 53+ Opera 40+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 63+ Safari iOS 10.3+ Chrome Android 53+ WebView Android 53+ Samsung Internet 6.0+ Opera Android 41+ Returns the deepest element in the document through which or to which key events are being routed. This is, roughly speaking, the focused element in the document. For the purposes of this API, when a child browsing context is focused, its container is focused in the parent browsing context . For example, if the user moves the focus to a text control in an iframe , the iframe is the element returned by the activeElement API in the iframe 's node document Similarly, when the focused element is in a different node tree than documentOrShadowRoot , the element returned will be the host that's located in the same node tree as documentOrShadowRoot if documentOrShadowRoot is a shadow-including inclusive ancestor of the focused element, and null if not. document hasFocus () Document/hasFocus Support in all current engines. Firefox 3+ Safari 4+ Chrome 1+ Opera 15+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 5.5+ Firefox Android 4+ Safari iOS 3.2+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 14+ Returns true if key events are being routed through or to the document; otherwise, returns false. Roughly speaking, this corresponds to the document, or a document nested inside this one, being focused. window focus () Window/focus Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ Moves the focus to the window's browsing context , if any. element focus ([ { preventScroll : true } ]) HTMLOrForeignElement/focus Support in all current engines. Firefox 1.5+ Safari 3+ Chrome 1+ Opera 8+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 5.5+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 4.4+ Samsung Internet 1.0+ Opera Android 10.1+ HTMLOrForeignElement/focus Support in all current engines. Firefox 51+ Safari 1.3+ Chrome 1+ Opera 15+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 51+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 14+ Moves the focus to the element. If the element is a browsing context container , moves the focus to its nested browsing context instead. By default, this method also scrolls the element into view. Providing the preventScroll option and setting it to true prevents this behavior. element blur () HTMLOrForeignElement/blur Support in all current engines. Firefox 1.5+ Safari 3+ Chrome 1+ Opera 8+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 5.5+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 4.4+ Samsung Internet 1.0+ Opera Android 10.1+ Moves the focus to the viewport . Use of this method is discouraged; if you want to focus the viewport , call the focus() method on the Document 's document element Do not use this method to hide the focus ring if you find the focus ring unsightly. Instead, use the :focus-visible pseudo-class to override the 'outline' property, and provide a different way to show what element is focused. Be aware that if an alternative focusing style isn't made available, the page will be significantly less usable for people who primarily navigate pages using a keyboard, or those with reduced vision who use focus outlines to help them navigate the page. For example, to hide the outline from textarea elements and instead use a yellow background to indicate focus, you could use: textarea:focus-visible outline none background yellow color black The activeElement attribute's getter must run these steps: Let candidate be the DOM anchor of the focused area of this DocumentOrShadowRoot 's node document Set candidate to the result of retargeting candidate against this DocumentOrShadowRoot If candidate 's root is not this DocumentOrShadowRoot then return null. If candidate is not a Document object, then return candidate If candidate has a body element , then return that body element If candidate 's document element is non-null, then return that document element Return null. The hasFocus() method on the Document object, when invoked, must return the result of running the has focus steps with the Document object as the argument. The focus() method, when invoked, must run these steps: Let current be this Window object's browsing context If current is null, then return. Run the focusing steps with current If current is a top-level browsing context , user agents are encouraged to trigger some sort of notification to indicate to the user that the page is attempting to gain focus. Window/blur Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ The blur() method, when invoked, provides a hint to the user agent that the script believes the user probably is not currently interested in the contents of this Window object's browsing context , if non-null, but that the contents might become interesting again in the future. User agents are encouraged to ignore calls to this blur() method entirely. Historically, the focus() and blur() methods actually affected the system-level focus of the system widget (e.g., tab or window) that contained the browsing context , but hostile sites widely abuse this behavior to the user's detriment. The focus( options method on elements, when invoked, must run the following steps: If the element is marked as locked for focus , then return. Mark the element as locked for focus Run the focusing steps for the element. If the value of the preventScroll dictionary member of options is false, then scroll the element into view with scroll behavior " auto ", block flow direction position set to an implementation-defined value, and inline base direction position set to an implementation-defined value. Unmark the element as locked for focus The blur() method, when invoked, should run the unfocusing steps for the element on which the method was called. User agents may selectively or uniformly ignore calls to this method for usability reasons. For example, if the blur() method is unwisely being used to remove the focus ring for aesthetics reasons, the page would become unusable by keyboard users. Ignoring calls to this method would thus allow keyboard users to interact with the page. 6.5.7 The autofocus attribute Attributes#attr-autofocus Support in all current engines. Firefox 4+ Safari 5+ Chrome 5+ Opera 9.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android The autofocus content attribute allows the author to indicate that an element is to be focused as soon as the page is loaded or as soon as the dialog within which it finds itself is shown, allowing the user to just start typing without having to manually focus the main element. The autofocus attribute is a boolean attribute An element's nearest ancestor autofocus scoping root element is the element itself if the element is a dialog element, or else is the element's nearest ancestor dialog element, if any, or else is the element's last inclusive ancestor element. There must not be two elements with the same nearest ancestor autofocus scoping root element that both have the autofocus attribute specified. Each Document has an autofocus candidates list initially empty. Each Document has an autofocus processed flag boolean, initially false. When an element with the autofocus attribute specified is inserted into a document , run the following steps: If the user has indicated (for example, by starting to type in a form control) that they do not wish focus to be changed, then optionally return. Let target be the element's node document If target 's browsing context is null, then return. If target 's active sandboxing flag set has the sandboxed automatic features browsing context flag , then return. For each ancestorBC of target 's browsing context 's ancestor browsing contexts : if ancestorBC 's active document 's origin is not same origin with target 's origin , then return. Let topDocument be the active document of target 's browsing context 's top-level browsing context If topDocument 's autofocus processed flag is false, then remove the element from topDocument 's autofocus candidates , and append the element to topDocument 's autofocus candidates We do not check if an element is a focusable area before storing it in the autofocus candidates list, because even if it is not a focusable area when it is inserted, it could become one by the time flush autofocus candidates sees it. To flush autofocus candidates for a document topDocument , run these steps: If topDocument 's autofocus processed flag is true, then return. Let candidates be topDocument 's autofocus candidates If candidates is empty , then return. If topDocument 's focused area is not topDocument itself, or topDocument has non-null target element , then: Empty candidates Set topDocument 's autofocus processed flag to true. Return. While candidates is not empty Let element be candidates [0]. Let doc be element 's node document If doc is not fully active , then remove element from candidates , and continue If doc 's browsing context 's top-level browsing context is not same as topDocument 's browsing context , then remove element from candidates , and continue If doc 's script-blocking style sheet counter is greater than 0, then return. In this case, element is the currently-best candidate, but doc is not ready for autofocusing. We'll try again next time flush autofocus candidates is called. Remove element from candidates Let inclusiveAncestorDocuments be a list consisting of doc , plus the active documents of each of doc 's browsing context 's ancestor browsing contexts If any Document in inclusiveAncestorDocuments has non-null target element , then continue Let target be element If target is not a focusable area , then set target to the result of getting the focusable area for target Autofocus candidates can contain elements which are not focusable areas . In addition to the special cases handled in the get the focusable area algorithm, this can happen because a non- focusable area element with an autofocus attribute was inserted into a document and it never became focusable, or because the element was focusable but its status changed while it was stored in autofocus candidates If target is not null, then: Empty candidates Set topDocument 's autofocus processed flag to true. Run the focusing steps for target This handles the automatic focusing during document load. The show() and showModal() methods of dialog elements also processes the autofocus attribute. Focusing the element does not imply that the user agent has to focus the browser window if it has lost focus. HTMLSelectElement/autofocus Support in all current engines. Firefox 4+ Safari 4+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 3.2+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ The autofocus IDL attribute must reflect the content attribute of the same name. In the following snippet, the text control would be focused when the document was loaded. input maxlength "256" name "q" value "" autofocus input type "submit" value "Search" The autofocus attribute applies to all elements, not just to form controls. This allows examples such as the following: div contenteditable autofocus Edit strong me! strong >< div 6.6 Assigning keyboard shortcuts 6.6.1 Introduction This section is non-normative. Each element that can be activated or focused can be assigned a single key combination to activate it, using the accesskey attribute. The exact shortcut is determined by the user agent, based on information about the user's keyboard, what keyboard shortcuts already exist on the platform, and what other shortcuts have been specified on the page, using the information provided in the accesskey attribute as a guide. In order to ensure that a relevant keyboard shortcut is available on a wide variety of input devices, the author can provide a number of alternatives in the accesskey attribute. Each alternative consists of a single character, such as a letter or digit. User agents can provide users with a list of the keyboard shortcuts, but authors are encouraged to do so also. The accessKeyLabel IDL attribute returns a string representing the actual key combination assigned by the user agent. In this example, an author has provided a button that can be invoked using a shortcut key. To support full keyboards, the author has provided "C" as a possible key. To support devices equipped only with numeric keypads, the author has provided "1" as another possibly key. input type button value Collect onclick "collect()" accesskey "C 1" id To tell the user what the shortcut key is, the author has this script here opted to explicitly add the key combination to the button's label: function addShortcutKeyLabel button if button accessKeyLabel != '' button value += ' (' button accessKeyLabel ')' addShortcutKeyLabel document getElementById 'c' )); Browsers on different platforms will show different labels, even for the same key combination, based on the convention prevalent on that platform. For example, if the key combination is the Control key, the Shift key, and the letter C, a Windows browser might display Ctrl+Shift+C ", whereas a Mac browser might display " ^⇧C ", while an Emacs browser might just display " C-C ". Similarly, if the key combination is the Alt key and the Escape key, Windows might use " Alt+Esc ", Mac might use ⌥⎋ ", and an Emacs browser might use " M-ESC " or ESC ESC ". In general, therefore, it is unwise to attempt to parse the value returned from the accessKeyLabel IDL attribute. 6.6.2 The accesskey attribute Global_attributes/accesskey Support in all current engines. Firefox Yes Safari Yes Chrome Yes Opera Yes Edge Yes Edge (Legacy) 12+ Internet Explorer Yes Firefox Android Yes Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes All HTML elements may have the accesskey content attribute set. The accesskey attribute's value is used by the user agent as a guide for creating a keyboard shortcut that activates or focuses the element. If specified, the value must be an ordered set of unique space-separated tokens none of which are identical to another token and each of which must be exactly one code point in length. In the following example, a variety of links are given with access keys so that keyboard users familiar with the site can more quickly navigate to the relevant pages: nav title "Consortium Activities" accesskey "A" href "/Consortium/activities" Activities title "Technical Reports and Recommendations" accesskey "T" href "/TR/" Technical Reports title "Alphabetical Site Index" accesskey "S" href "/Consortium/siteindex" Site Index title "About This Site" accesskey "B" href "/Consortium/" About Consortium title "Contact Consortium" accesskey "C" href "/Consortium/contact" Contact nav In the following example, the search field is given two possible access keys, "s" and "0" (in that order). A user agent on a device with a full keyboard might pick Ctrl Alt as the shortcut key, while a user agent on a small device with just a numeric keypad might pick just the plain unadorned key form action "/search" label Search: input type "search" name "q" accesskey "s 0" > label input type "submit" form In the following example, a button has possible access keys described. A script then tries to update the button's label to advertise the key combination the user agent selected. input type submit accesskey "N @ 1" value "Compose" ... script function labelButton button if button accessKeyLabel button value += ' (' button accessKeyLabel ')' var inputs document getElementsByTagName 'input' ); for var inputs length += if inputs ]. type == "submit" labelButton inputs ]); script On one user agent, the button's label might become " Compose (⌘N) ". On another, it might become " Compose (Alt+⇧+1) ". If the user agent doesn't assign a key, it will be just " Compose ". The exact string depends on what the assigned access key is, and on how the user agent represents that key combination. 6.6.3 Processing model An element's assigned access key is a key combination derived from the element's accesskey content attribute. Initially, an element must not have an assigned access key Whenever an element's accesskey attribute is set, changed, or removed, the user agent must update the element's assigned access key by running the following steps: If the element has no accesskey attribute, then skip to the fallback step below. Otherwise, split the attribute's value on ASCII whitespace , and let keys be the resulting tokens. For each value in keys in turn, in the order the tokens appeared in the attribute's value, run the following substeps: If the value is not a string exactly one code point in length, then skip the remainder of these steps for this value. If the value does not correspond to a key on the system's keyboard, then skip the remainder of these steps for this value. If the user agent can find a mix of zero or more modifier keys that, combined with the key that corresponds to the value given in the attribute, can be used as the access key, then the user agent may assign that combination of keys as the element's assigned access key and return. Fallback : Optionally, the user agent may assign a key combination of its choosing as the element's assigned access key and then return. If this step is reached, the element has no assigned access key Once a user agent has selected and assigned an access key for an element, the user agent should not change the element's assigned access key unless the accesskey content attribute is changed or the element is moved to another Document When the user presses the key combination corresponding to the assigned access key for an element, if the element defines a command , the command's Hidden State facet is false (visible), the command's Disabled State facet is also false (enabled), the element is in a document that has a non-null browsing context , and neither the element nor any of its ancestors has a hidden attribute specified, then the user agent must trigger the Action of the command. User agents might expose elements that have an accesskey attribute in other ways as well, e.g. in a menu displayed in response to a specific key combination. HTMLElement/accessKey Support in all current engines. Firefox 5+ Safari 6+ Chrome 17+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 5.5+ Firefox Android 5+ Safari iOS 6+ Chrome Android 18+ WebView Android 4.4+ Samsung Internet 1.0+ Opera Android 12.1+ The accessKey IDL attribute must reflect the accesskey content attribute. HTMLElement/accessKeyLabel Firefox 8+ Safari 14+ Chrome No Opera No Edge No Edge (Legacy) No Internet Explorer No Firefox Android 8+ Safari iOS 14+ Chrome Android No WebView Android No Samsung Internet No Opera Android No The accessKeyLabel IDL attribute must return a string that represents the element's assigned access key , if any. If the element does not have one, then the IDL attribute must return the empty string. 6.7 Editing 6.7.1 Making document regions editable: The contenteditable content attribute HTMLElement/contentEditable Support in all current engines. Firefox 3+ Safari 3+ Chrome 1+ Opera 9+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 5.5+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 4.4+ Samsung Internet 1.0+ Opera Android 10.1+ interface mixin ElementContentEditable CEReactions attribute DOMString contentEditable CEReactions attribute DOMString enterKeyHint readonly attribute boolean isContentEditable CEReactions attribute DOMString inputMode }; Global_attributes/contenteditable Support in all current engines. Firefox 3+ Safari Yes Chrome Yes Opera 9+ Edge Yes Edge (Legacy) 12+ Internet Explorer 5.5+ Firefox Android 4+ Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes The contenteditable content attribute is an enumerated attribute whose keywords are the empty string, true , and false . The empty string and the true keyword map to the true state. The false keyword maps to the false state. In addition, there is a third state, the inherit state, which is the missing value default and the invalid value default The true state indicates that the element is editable. The inherit state indicates that the element is editable if its parent is. The false state indicates that the element is not editable. For example, consider a page that has a form and a textarea to publish a new article, where the user is expected to write the article using HTML: form method POST fieldset legend New article legend textarea name article < p>Hello world. < /p> textarea fieldset >< button Publish button > form When scripting is enabled, the textarea element could be replaced with a rich text control instead, using the contenteditable attribute: form method POST fieldset legend New article legend textarea id textarea name article < p>Hello world. < /p> textarea div id div style "white-space: pre-wrap" hidden >< Hello world. > div script let textarea document getElementById "textarea" ); let div document getElementById "div" ); textarea hidden true div hidden false div contentEditable "true" div oninput => textarea value div innerHTML }; script fieldset >< button Publish button > form Features to enable, e.g., inserting links, can be implemented using the document.execCommand() API, or using Selection APIs and other DOM APIs. [EXECCOMMAND] [SELECTION] [DOM] The contenteditable attribute can also be used to great effect: html lang en title Live CSS editing! title style style white-space:pre contenteditable html margin .2 em font-size em color lime background purple head title style display block body display none style element contentEditable [ = value Returns " true ", " false ", or " inherit ", based on the state of the contenteditable attribute. Can be set, to change that state. Throws a SyntaxError DOMException if the new value isn't one of those strings. element isContentEditable HTMLElement/isContentEditable Support in all current engines. Firefox 4+ Safari 3+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 5.5+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 4.4+ Samsung Internet 1.0+ Opera Android 12.1+ Returns true if the element is editable; otherwise, returns false. The contentEditable IDL attribute, on getting, must return the string " true " if the content attribute is set to the true state, " false " if the content attribute is set to the false state, and " inherit " otherwise. On setting, if the new value is an ASCII case-insensitive match for the string " inherit " then the content attribute must be removed, if the new value is an ASCII case-insensitive match for the string " true " then the content attribute must be set to the string true ", if the new value is an ASCII case-insensitive match for the string " false " then the content attribute must be set to the string false ", and otherwise the attribute setter must throw a SyntaxError DOMException The isContentEditable IDL attribute, on getting, must return true if the element is either an editing host or editable , and false otherwise. 6.7.2 Making entire documents editable: the designMode getter and setter document designMode [ = value Document/designMode Support in all current engines. Firefox 1+ Safari 1.2+ Chrome 1+ Opera 9+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 10.1+ Returns " on " if the document is editable, and " off " if it isn't. Can be set, to change the document's current state. This focuses the document and resets the selection in that document. Document objects have an associated design mode enabled , which is a boolean. It is initially false. The designMode getter steps are to return " on " if this 's design mode enabled is true; otherwise " off ". The designMode setter steps are: Let value be the given value, converted to ASCII lowercase If value is " on " and this 's design mode enabled is false, then: Set this 's design mode enabled to true. Reset this 's active range 's start and end boundary points to be at the start of this Run the focusing steps for this 's document element , if non-null. If value is " off ", then set this 's design mode enabled to false. 6.7.3 Best practices for in-page editors Authors are encouraged to set the 'white-space' property on editing hosts and on markup that was originally created through these editing mechanisms to the value 'pre-wrap'. Default HTML whitespace handling is not well suited to WYSIWYG editing, and line wrapping will not work correctly in some corner cases if 'white-space' is left at its default value. As an example of problems that occur if the default 'normal' value is used instead, consider the case of the user typing " yellow␣␣ball ", with two spaces (here represented by "␣") between the words. With the editing rules in place for the default value of 'white-space' ('normal'), the resulting markup will either consist of yellow ball " or " yellow ball "; i.e., there will be a non-breaking space between the two words in addition to the regular space. This is necessary because the 'normal' value for 'white-space' requires adjacent regular spaces to be collapsed together. In the former case, " yellow⍽ " might wrap to the next line ("⍽" being used here to represent a non-breaking space) even though " yellow " alone might fit at the end of the line; in the latter case, " ⍽ball ", if wrapped to the start of the line, would have visible indentation from the non-breaking space. When 'white-space' is set to 'pre-wrap', however, the editing rules will instead simply put two regular spaces between the words, and should the two words be split at the end of a line, the spaces would be neatly removed from the rendering. 6.7.4 Editing APIs An editing host is either an HTML element with its contenteditable attribute in the true state, or a child HTML element of a Document whose design mode enabled is true. The definition of the terms active range editing host of , and editable , the user interface requirements of elements that are editing hosts or editable , the execCommand() queryCommandEnabled() queryCommandIndeterm() queryCommandState() queryCommandSupported() , and queryCommandValue() methods, text selections, and the delete the selection algorithm are defined in execCommand [EXECCOMMAND] 6.7.5 Spelling and grammar checking User agents can support the checking of spelling and grammar of editable text, either in form controls (such as the value of textarea elements), or in elements in an editing host (e.g. using contenteditable ). For each element, user agents must establish a default behavior , either through defaults or through preferences expressed by the user. There are three possible default behaviors for each element: true-by-default The element will be checked for spelling and grammar if its contents are editable and spellchecking is not explicitly disabled through the spellcheck attribute. false-by-default The element will never be checked for spelling and grammar unless spellchecking is explicitly enabled through the spellcheck attribute. inherit-by-default The element's default behavior is the same as its parent element's. Elements that have no parent element cannot have this as their default behavior. Global_attributes/spellcheck Support in all current engines. Firefox Yes Safari Yes Chrome 9+ Opera Yes Edge 79+ Edge (Legacy) 12+ Internet Explorer 11 Firefox Android 57+ Safari iOS 9.3+ Chrome Android 47+ WebView Android 47+ Samsung Internet 5.0+ Opera Android 37+ The spellcheck attribute is an enumerated attribute whose keywords are the empty string, true and false . The empty string and the true keyword map to the true state. The false keyword maps to the false state. In addition, there is a third state, the default state, which is the missing value default and the invalid value default The true state indicates that the element is to have its spelling and grammar checked. The default state indicates that the element is to act according to a default behavior, possibly based on the parent element's own spellcheck state, as defined below. The false state indicates that the element is not to be checked. element spellcheck [ = value Returns true if the element is to have its spelling and grammar checked; otherwise, returns false. Can be set, to override the default and set the spellcheck content attribute. The spellcheck IDL attribute, on getting, must return true if the element's spellcheck content attribute is in the true state, or if the element's spellcheck content attribute is in the default state and the element's default behavior is true-by-default , or if the element's spellcheck content attribute is in the default state and the element's default behavior is inherit-by-default and the element's parent element's spellcheck IDL attribute would return true; otherwise, if none of those conditions applies, then the attribute must instead return false. The spellcheck IDL attribute is not affected by user preferences that override the spellcheck content attribute, and therefore might not reflect the actual spellchecking state. On setting, if the new value is true, then the element's spellcheck content attribute must be set to the literal string true ", otherwise it must be set to the literal string " false ". User agents must only consider the following pieces of text as checkable for the purposes of this feature: The value of input elements whose type attributes are in the Text URL , or Email states and that are mutable (i.e. that do not have the readonly attribute specified and that are not disabled ). The value of textarea elements that do not have a readonly attribute and that are not disabled Text in Text nodes that are children of editing hosts or editable elements. Text in attributes of editable elements. For text that is part of a Text node, the element with which the text is associated is the element that is the immediate parent of the first character of the word, sentence, or other piece of text. For text in attributes, it is the attribute's element. For the values of input and textarea elements, it is the element itself. To determine if a word, sentence, or other piece of text in an applicable element (as defined above) is to have spelling- and grammar-checking enabled, the UA must use the following algorithm: If the user has disabled the checking for this text, then the checking is disabled. Otherwise, if the user has forced the checking for this text to always be enabled, then the checking is enabled. Otherwise, if the element with which the text is associated has a spellcheck content attribute, then: if that attribute is in the true state, then checking is enabled; otherwise, if that attribute is in the false state, then checking is disabled. Otherwise, if there is an ancestor element with a spellcheck content attribute that is not in the default state, then: if the nearest such ancestor's spellcheck content attribute is in the true state, then checking is enabled; otherwise, checking is disabled. Otherwise, if the element's default behavior is true-by-default , then checking is enabled. Otherwise, if the element's default behavior is false-by-default , then checking is disabled. Otherwise, if the element's parent element has its checking enabled, then checking is enabled. Otherwise, checking is disabled. If the checking is enabled for a word/sentence/text, the user agent should indicate spelling and grammar errors in that text. User agents should take into account the other semantics given in the document when suggesting spelling and grammar corrections. User agents may use the language of the element to determine what spelling and grammar rules to use, or may use the user's preferred language settings. UAs should use input element attributes such as pattern to ensure that the resulting value is valid, where possible. If checking is disabled, the user agent should not indicate spelling or grammar errors for that text. The element with ID "a" in the following example would be the one used to determine if the word "Hello" is checked for spelling errors. In this example, it would not be. div contenteditable "true" span spellcheck "false" id "a" Hell span >< em o! em div The element with ID "b" in the following example would have checking enabled (the leading space character in the attribute's value on the input element causes the attribute to be ignored, so the ancestor's value is used instead, regardless of the default). spellcheck "true" label Name: input spellcheck " false" id "b" > label This specification does not define the user interface for spelling and grammar checkers. A user agent could offer on-demand checking, could perform continuous checking while the checking is enabled, or could use other interfaces. 6.7.6 Autocapitalization Some methods of entering text, for example virtual keyboards on mobile devices, and also voice input, often assist users by automatically capitalizing the first letter of sentences (when composing text in a language with this convention). A virtual keyboard that implements autocapitalization might automatically switch to showing uppercase letters (but allow the user to toggle it back to lowercase) when a letter that should be autocapitalized is about to be typed. Other types of input, for example voice input, may perform autocapitalization in a way that does not give users an option to intervene first. The autocapitalize attribute allows authors to control such behavior. The autocapitalize attribute, as typically implemented, does not affect behavior when typing on a physical keyboard. (For this reason, as well as the ability for users to override the autocapitalization behavior in some cases or edit the text after initial input, the attribute must not be relied on for any sort of input validation.) The autocapitalize attribute can be used on an editing host to control autocapitalization behavior for the hosted editable region, on an input or textarea element to control the behavior for inputting text into that element, or on a form element to control the default behavior for all autocapitalize-inheriting elements associated with the form element. The autocapitalize attribute never causes autocapitalization to be enabled for input elements whose type attribute is in one of the URL Email , or Password states. (This behavior is included in the used autocapitalization hint algorithm below.) The autocapitalization processing model is based on selecting among five autocapitalization hints , defined as follows: default The user agent and input method should use make their own determination of whether or not to enable autocapitalization. none No autocapitalization should be applied (all letters should default to lowercase). sentences The first letter of each sentence should default to a capital letter; all other letters should default to lowercase. words The first letter of each word should default to a capital letter; all other letters should default to lowercase. characters All letters should default to uppercase. Global_attributes/autocapitalize Support in all current engines. Firefox 🔰 83+ Safari No Chrome 43+ Opera Edge 79+ Edge (Legacy) No Internet Explorer Firefox Android 🔰 83+ Safari iOS 5+ Chrome Android 43+ WebView Android 43+ Samsung Internet Opera Android The autocapitalize attribute is an enumerated attribute whose states are the possible autocapitalization hints . The autocapitalization hint specified by the attribute's state combines with other considerations to form the used autocapitalization hint , which informs the behavior of the user agent. The keywords for this attribute and their state mappings are as follows: Keyword State off none none on sentences sentences words words characters characters The invalid value default is the sentences state. The missing value default is the default state. element autocapitalize [ = value Returns the current autocapitalization state for the element, or an empty string if it hasn't been set. Note that for input and textarea elements that inherit their state from a form element, this will return the autocapitalization state of the form element, but for an element in an editable region, this will not return the autocapitalization state of the editing host (unless this element is, in fact, the editing host ). Can be set, to set the autocapitalize content attribute (and thereby change the autocapitalization behavior for the element). To compute the own autocapitalization hint of an element element , run the following steps: If the autocapitalize content attribute is present on element , and its value is not the empty string, return the state of the attribute. If element is an autocapitalize-inheriting element and has a non-null form owner , return the own autocapitalization hint of element 's form owner Return default The autocapitalize getter steps are to: Let state be the own autocapitalization hint of this If state is default , then return the empty string. If state is none , then return " none ". If state is sentences , then return sentences ". Return the keyword value corresponding to state The autocapitalize setter steps are to set the autocapitalize content attribute to the given value. User agents that support customizable autocapitalization behavior for a text input method and wish to allow web developers to control this functionality should, during text input into an element, compute the used autocapitalization hint for the element. This will be an autocapitalization hint that describes the recommended autocapitalization behavior for text input into the element. User agents or input methods may choose to ignore or override the used autocapitalization hint in certain circumstances. The used autocapitalization hint for an element element is computed using the following algorithm: If element is an input element whose type attribute is in one of the URL Email , or Password states, then return default If element is an input element or a textarea element, then return element 's own autocapitalization hint If element is an editing host or an editable element, then return the own autocapitalization hint of the editing host of element Assert: this step is never reached, since text input only occurs in elements that meet one of the above criteria. 6.7.7 Input modalities: the inputmode attribute User agents can support the inputmode attribute on form controls (such as the value of textarea elements), or in elements in an editing host (e.g., using contenteditable ). Global_attributes/inputmode Support in all current engines. Firefox 🔰 23+ Safari No Chrome 66+ Opera 53+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 79+ Safari iOS 12.2+ Chrome Android 66+ WebView Android 66+ Samsung Internet 9.0+ Opera Android 47+ The inputmode content attribute is an enumerated attribute that specifies what kind of input mechanism would be most helpful for users entering content. Keyword Description none The user agent should not display a virtual keyboard. This keyword is useful for content that renders its own keyboard control. text The user agent should display a virtual keyboard capable of text input in the user's locale. tel The user agent should display a virtual keyboard capable of telephone number input. This should including keys for the digits 0 to 9, the "#" character, and the "*" character. In some locales, this can also include alphabetic mnemonic labels (e.g., in the US, the key labeled "2" is historically also labeled with the letters A, B, and C). url The user agent should display a virtual keyboard capable of text input in the user's locale, with keys for aiding in the input of URLs , such as that for the "/" and "." characters and for quick input of strings commonly found in domain names such as "www." or ".com". email The user agent should display a virtual keyboard capable of text input in the user's locale, with keys for aiding in the input of email addresses, such as that for the "@" character and the "." character. numeric The user agent should display a virtual keyboard capable of numeric input. This keyword is useful for PIN entry. decimal The user agent should display a virtual keyboard capable of fractional numeric input. Numeric keys and the format separator for the locale should be shown. The user agent should display a virtual keyboard optimized for search. The inputMode IDL attribute must reflect the inputmode content attribute, limited to only known values When inputmode is unspecified (or is in a state not supported by the user agent), the user agent should determine the default virtual keyboard to be shown. Contextual information such as the input type or pattern attributes should be used to determine which type of virtual keyboard should be presented to the user. 6.7.8 Input modalities: the enterkeyhint attribute User agents can support the enterkeyhint attribute on form controls (such as the value of textarea elements), or in elements in an editing host (e.g., using contenteditable ). Global_attributes/enterkeyhint Support in all current engines. Firefox 🔰 79+ Safari 13.1+ Chrome 77+ Opera 66+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 🔰 79+ Safari iOS 13.4+ Chrome Android 77+ WebView Android 77+ Samsung Internet 12.0+ Opera Android 57+ The enterkeyhint content attribute is an enumerated attribute that specifies what action label (or icon) to present for the enter key on virtual keyboards. This allows authors to customize the presentation of the enter key in order to make it more helpful for users. Keyword Description enter The user agent should present a cue for the operation 'enter', typically inserting a new line. done The user agent should present a cue for the operation 'done', typically meaning there is nothing more to input and the input method editor (IME) will be closed. go The user agent should present a cue for the operation 'go', typically meaning to take the user to the target of the text they typed. next The user agent should present a cue for the operation 'next', typically taking the user to the next field that will accept text. previous The user agent should present a cue for the operation 'previous', typically taking the user to the previous field that will accept text. The user agent should present a cue for the operation 'search', typically taking the user to the results of searching for the text they have typed. send The user agent should present a cue for the operation 'send', typically delivering the text to its target. HTMLElement/enterKeyHint Support in all current engines. Firefox 🔰 79+ Safari 13.1+ Chrome 77+ Opera 64+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 🔰 79+ Safari iOS 13.4+ Chrome Android 77+ WebView Android 77+ Samsung Internet 12.0+ Opera Android 55+ The enterKeyHint IDL attribute must reflect the enterkeyhint content attribute, limited to only known values When enterkeyhint is unspecified (or is in a state not supported by the user agent), the user agent should determine the default action label (or icon) to present. Contextual information such as the inputmode type , or pattern attributes should be used to determine which action label (or icon) to present on the virtual keyboard. 6.8 Find-in-page 6.8.1 Introduction This section defines find-in-page — a common user-agent mechanism which allows users to search through the contents of the page for particular information. Access to find-in-page feature is provided via a find-in-page interface . This is a user-agent provided user interface, which allows the user to specify input and the parameters of the search. This interface can appear as a result of a shortcut or a menu selection. A combination of text input and settings in the find-in-page interface represents the user query . This typically includes the text that the user wants to search for, as well as optional settings (e.g., the ability to restrict the search to whole words only). The user-agent processes page contents for a given query , and identifies zero or more matches , which are content ranges that satisfy the user query One of the matches is identified to the user as the active match . It is highlighted and scrolled into view. The user can navigate through the matches by advancing the active match using the find-in-page interface Issue #3539 tracks standardizing how find-in-page underlies the currently-unspecified window.find() API. 6.8.2 Interaction with selection The find-in-page process is invoked in the context of a document, and may have an effect on the selection of that document. Specifically, the range that defines the active match can dictate the current selection. These selection updates, however, can happen at different times during the find-in-page process (e.g. upon the find-in-page interface dismissal or upon a change in the active match range). 6.9 Drag and drop HTML_Drag_and_Drop_API Support in all current engines. Firefox 3.5+ Safari 3.1+ Chrome 4+ Opera 12+ Edge 79+ Edge (Legacy) 18 Internet Explorer 5.5+ Firefox Android 4+ Safari iOS 2+ Chrome Android 18+ WebView Android 4.4+ Samsung Internet 1.5+ Opera Android 14+ This section defines an event-based drag-and-drop mechanism. This specification does not define exactly what a drag-and-drop operation actually is. On a visual medium with a pointing device, a drag operation could be the default action of a mousedown event that is followed by a series of mousemove events, and the drop could be triggered by the mouse being released. When using an input modality other than a pointing device, users would probably have to explicitly indicate their intention to perform a drag-and-drop operation, stating what they wish to drag and where they wish to drop it, respectively. However it is implemented, drag-and-drop operations must have a starting point (e.g. where the mouse was clicked, or the start of the selection or element that was selected for the drag), may have any number of intermediate steps (elements that the mouse moves over during a drag, or elements that the user picks as possible drop points as they cycle through possibilities), and must either have an end point (the element above which the mouse button was released, or the element that was finally selected), or be canceled. The end point must be the last element selected as a possible drop point before the drop occurs (so if the operation is not canceled, there must be at least one element in the middle step). 6.9.1 Introduction This section is non-normative. To make an element draggable, give the element a draggable attribute, and set an event listener for dragstart that stores the data being dragged. The event handler typically needs to check that it's not a text selection that is being dragged, and then needs to store data into the DataTransfer object and set the allowed effects (copy, move, link, or some combination). For example: What fruits do you like? ol ondragstart "dragStartHandler(event)" li draggable "true" data-value "fruit-apple" Apples li li draggable "true" data-value "fruit-orange" Oranges li li draggable "true" data-value "fruit-pear" Pears li ol script var internalDNDType 'text/x-example' // set this to something specific to your site function dragStartHandler event if event target instanceof HTMLLIElement // use the element's data-value="" attribute as the value to be moving: event dataTransfer setData internalDNDType event target dataset value ); event dataTransfer effectAllowed 'move' // only allow moves else event preventDefault (); // don't allow selection to be dragged script To accept a drop, the drop target has to listen to the following events: The dragenter event handler reports whether or not the drop target is potentially willing to accept the drop, by canceling the event. The dragover event handler specifies what feedback will be shown to the user, by setting the dropEffect attribute of the DataTransfer associated with the event. This event also needs to be canceled. The drop event handler has a final chance to accept or reject the drop. If the drop is accepted, the event handler must perform the drop operation on the target. This event needs to be canceled, so that the dropEffect attribute's value can be used by the source. Otherwise, the drop operation is rejected. For example: Drop your favorite fruits below: ol ondragenter "dragEnterHandler(event)" ondragover "dragOverHandler(event)" ondrop "dropHandler(event)" ol script var internalDNDType 'text/x-example' // set this to something specific to your site function dragEnterHandler event var items event dataTransfer items for var items length ++ var item items ]; if item kind == 'string' && item type == internalDNDType event preventDefault (); return function dragOverHandler event event dataTransfer dropEffect 'move' event preventDefault (); function dropHandler event var li document createElement 'li' ); var data event dataTransfer getData internalDNDType ); if data == 'fruit-apple' li textContent 'Apples' else if data == 'fruit-orange' li textContent 'Oranges' else if data == 'fruit-pear' li textContent 'Pears' else li textContent 'Unknown Fruit' event target appendChild li ); script To remove the original element (the one that was dragged) from the display, the dragend event can be used. For our example here, that means updating the original markup to handle that event: What fruits do you like? ol ondragstart "dragStartHandler(event)" ondragend "dragEndHandler(event)" ...as before... ol script function dragStartHandler event // ...as before... function dragEndHandler event if event dataTransfer dropEffect == 'move' // remove the dragged element event target parentNode removeChild event target ); script 6.9.2 The drag data store The data that underlies a drag-and-drop operation, known as the drag data store consists of the following information: drag data store item list , which is a list of items representing the dragged data, each consisting of the following information: The drag data item kind The kind of data: Text Text. File Binary data with a filename. The drag data item type string A Unicode string giving the type or format of the data, generally given by a MIME type . Some values that are not MIME types are special-cased for legacy reasons. The API does not enforce the use of MIME types ; other values can be used as well. In all cases, however, the values are all converted to ASCII lowercase by the API. There is a limit of one text item per item type string The actual data A Unicode or binary string, in some cases with a filename (itself a Unicode string), as per the drag data item kind The drag data store item list is ordered in the order that the items were added to the list; most recently added last. The following information, used to generate the UI feedback during the drag: User-agent-defined default feedback information, known as the drag data store default feedback Optionally, a bitmap image and the coordinate of a point within that image, known as the drag data store bitmap and drag data store hot spot coordinate drag data store mode , which is one of the following: Read/write mode For the dragstart event. New data can be added to the drag data store Read-only mode For the drop event. The list of items representing dragged data can be read, including the data. No new data can be added. Protected mode For all other events. The formats and kinds in the drag data store list of items representing dragged data can be enumerated, but the data itself is unavailable and no new data can be added. drag data store allowed effects state , which is a string. When a drag data store is created , it must be initialized such that its drag data store item list is empty, it has no drag data store default feedback , it has no drag data store bitmap and drag data store hot spot coordinate , its drag data store mode is protected mode , and its drag data store allowed effects state is the string " uninitialized ". 6.9.3 The DataTransfer interface DataTransfer objects are used to expose the drag data store that underlies a drag-and-drop operation. DataTransfer Support in all current engines. Firefox 3.5+ Safari 3.1+ Chrome 3+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 2+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 12+ Exposed Window interface DataTransfer constructor (); attribute DOMString dropEffect attribute DOMString effectAllowed
SameObject readonly attribute DataTransferItemList items undefined setDragImage Element image long long );
/* old interface */ readonly attribute FrozenArray DOMString types DOMString getData DOMString format ); undefined setData DOMString format DOMString data ); undefined clearData optional DOMString format ); SameObject readonly attribute FileList files }; dataTransfer = new DataTransfer () DataTransfer/DataTransfer Support in all current engines. Firefox 62+ Safari 14.1+ Chrome 60+ Opera 47+ Edge 79+ Edge (Legacy) 17+ Internet Explorer No Firefox Android 62+ Safari iOS 14.5+ Chrome Android 60+ WebView Android 60+ Samsung Internet 8.0+ Opera Android 44+ Creates a new DataTransfer object with an empty drag data store dataTransfer dropEffect [ = value DataTransfer/dropEffect Support in all current engines. Firefox 3.5+ Safari Yes Chrome Yes Opera Yes Edge Yes Edge (Legacy) 12+ Internet Explorer Firefox Android 4+ Safari iOS No Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes Returns the kind of operation that is currently selected. If the kind of operation isn't one of those that is allowed by the effectAllowed attribute, then the operation will fail. Can be set, to change the selected operation. The possible values are " none ", " copy ", " link ", and " move ". dataTransfer effectAllowed [ = value DataTransfer/effectAllowed Support in all current engines. Firefox 3.5+ Safari Yes Chrome Yes Opera Yes Edge Yes Edge (Legacy) 12+ Internet Explorer Firefox Android 4+ Safari iOS No Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes Returns the kinds of operations that are to be allowed. Can be set (during the dragstart event), to change the allowed operations. The possible values are " none ", copy ", " copyLink ", " copyMove ", " link ", " linkMove ", " move ", " all ", and " uninitialized ", dataTransfer items DataTransfer/items Support in all current engines. Firefox 50+ Safari 11.1+ Chrome 4+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android 52+ Safari iOS 11.3+ Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes Returns a DataTransferItemList object, with the drag data. dataTransfer setDragImage element DataTransfer/setDragImage Support in all current engines. Firefox 3.5+ Safari Yes Chrome Yes Opera Yes Edge Yes Edge (Legacy) 18 Internet Explorer Firefox Android 4+ Safari iOS No Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes Uses the given element to update the drag feedback, replacing any previously specified feedback. dataTransfer types DataTransfer/types Support in all current engines. Firefox 3.5+ Safari Yes Chrome Yes Opera Yes Edge Yes Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS No Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes Returns a frozen array listing the formats that were set in the dragstart event. In addition, if any files are being dragged, then one of the types will be the string " Files ". data dataTransfer getData format DataTransfer/getData Support in all current engines. Firefox 3.5+ Safari Yes Chrome Yes Opera Yes Edge Yes Edge (Legacy) 12+ Internet Explorer Firefox Android 4+ Safari iOS No Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes Returns the specified data. If there is no such data, returns the empty string. dataTransfer setData format data DataTransfer/setData Support in all current engines. Firefox 10+ Safari 5+ Chrome 3+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android 10+ Safari iOS 5+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 12+ Adds the specified data. dataTransfer clearData ( [ format ] ) DataTransfer/clearData Support in all current engines. Firefox 3.5+ Safari Yes Chrome Yes Opera Yes Edge Yes Edge (Legacy) 12+ Internet Explorer Firefox Android 4+ Safari iOS No Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes Removes the data of the specified formats. Removes all data if the argument is omitted. dataTransfer files DataTransfer/files Support in all current engines. Firefox 3.6+ Safari Yes Chrome Yes Opera Yes Edge Yes Edge (Legacy) 12+ Internet Explorer Firefox Android 4+ Safari iOS No Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes Returns a FileList of the files being dragged, if any. DataTransfer objects that are created as part of drag-and-drop events are only valid while those events are being fired. DataTransfer object is associated with a drag data store while it is valid. DataTransfer object has an associated types array , which is a FrozenArray , initially empty. When the contents of the DataTransfer object's drag data store item list change, or when the DataTransfer object becomes no longer associated with a drag data store , run the following steps: Let be an empty sequence. If the DataTransfer object is still associated with a drag data store , then: For each item in the DataTransfer object's drag data store item list whose kind is text , add an entry to consisting of the item's type string If there are any items in the DataTransfer object's drag data store item list whose kind is File , then add an entry to consisting of the string " Files ". (This value can be distinguished from the other values because it is not lowercase.) Set the DataTransfer object's types array to the result of creating a frozen array from The DataTransfer() constructor, when invoked, must return a newly created DataTransfer object initialized as follows: Set the drag data store 's item list to be an empty list. Set the drag data store 's mode to read/write mode Set the dropEffect and effectAllowed to "none". The dropEffect attribute controls the drag-and-drop feedback that the user is given during a drag-and-drop operation. When the DataTransfer object is created, the dropEffect attribute is set to a string value. On getting, it must return its current value. On setting, if the new value is one of " none ", " copy ", " link ", or " move ", then the attribute's current value must be set to the new value. Other values must be ignored. The effectAllowed attribute is used in the drag-and-drop processing model to initialize the dropEffect attribute during the dragenter and dragover events. When the DataTransfer object is created, the effectAllowed attribute is set to a string value. On getting, it must return its current value. On setting, if drag data store 's mode is the read/write mode and the new value is one of " none ", " copy ", " copyLink ", " copyMove ", " link ", " linkMove ", " move ", " all ", or " uninitialized ", then the attribute's current value must be set to the new value. Otherwise it must be left unchanged. The items attribute must return a DataTransferItemList object associated with the DataTransfer object. The setDragImage( element method must run the following steps: If the DataTransfer object is no longer associated with a drag data store , return. Nothing happens. If the drag data store 's mode is not the read/write mode , return. Nothing happens. If element is an img element, then set the drag data store bitmap to the element's image (at its intrinsic size ); otherwise, set the drag data store bitmap to an image generated from the given element (the exact mechanism for doing so is not currently specified). Set the drag data store hot spot coordinate to the given coordinate. The types attribute must return this DataTransfer object's types array The getData( format method must run the following steps: If the DataTransfer object is no longer associated with a drag data store , then return the empty string. If the drag data store 's mode is the protected mode , then return the empty string. Let format be the first argument, converted to ASCII lowercase Let convert-to-URL be false. If format equals " text ", change it to " text/plain ". If format equals " url ", change it to " text/uri-list " and set convert-to-URL to true. If there is no item in the drag data store item list whose kind is text and whose type string is equal to format , return the empty string. Let result be the data of the item in the drag data store item list whose kind is Plain Unicode string and whose type string is equal to format If convert-to-URL is true, then parse result as appropriate for text/uri-list data, and then set result to the first URL from the list, if any, or the empty string otherwise. [RFC2483] Return result The setData( format data method must run the following steps: If the DataTransfer object is no longer associated with a drag data store , return. Nothing happens. If the drag data store 's mode is not the read/write mode , return. Nothing happens. Let format be the first argument, converted to ASCII lowercase If format equals " text ", change it to " text/plain ". If format equals " url ", change it to " text/uri-list ". Remove the item in the drag data store item list whose kind is text and whose type string is equal to format , if there is one. Add an item to the drag data store item list whose kind is text , whose type string is equal to format , and whose data is the string given by the method's second argument. The clearData() method must run the following steps: If the DataTransfer object is no longer associated with a drag data store , return. Nothing happens. If the drag data store 's mode is not the read/write mode , return. Nothing happens. If the method was called with no arguments, remove each item in the drag data store item list whose kind is Plain Unicode string , and return. Let format be the first argument, converted to ASCII lowercase If format equals " text ", change it to " text/plain ". If format equals " url ", change it to " text/uri-list ". Remove the item in the drag data store item list whose kind is text and whose type string is equal to format , if there is one. The clearData() method does not affect whether any files were included in the drag, so the types attribute's list might still not be empty after calling clearData() (it would still contain the Files " string if any files were included in the drag). The files attribute must return a live FileList sequence consisting of File objects representing the files found by the following steps. Furthermore, for a given FileList object and a given underlying file, the same File object must be used each time. Start with an empty list If the DataTransfer object is no longer associated with a drag data store , the FileList is empty. Return the empty list If the drag data store 's mode is the protected mode , Return the empty list For each item in the drag data store item list whose kind is File , add the item's data (the file, in particular its name and contents, as well as its type ) to the list The files found by these steps are those in the list This version of the API does not expose the types of the files during the drag. 6.9.3.1 The DataTransferItemList interface Each DataTransfer object is associated with a DataTransferItemList object. DataTransferItemList Support in all current engines. Firefox 50+ Safari 6+ Chrome 13+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android 50+ Safari iOS 6+ Chrome Android 18+ WebView Android 4.4+ Samsung Internet 1.0+ Opera Android No Exposed Window interface DataTransferItemList readonly attribute unsigned long length getter DataTransferItem unsigned long index ); DataTransferItem add DOMString data DOMString type ); DataTransferItem add File data ); undefined remove unsigned long index ); undefined clear (); }; items length DataTransferItemList/length Support in all current engines. Firefox 50+ Safari 6+ Chrome 13+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android 50+ Safari iOS 6+ Chrome Android 18+ WebView Android 4.4+ Samsung Internet 1.0+ Opera Android No Returns the number of items in the drag data store items index Returns the DataTransferItem object representing the index th entry in the drag data store items remove index DataTransferItemList/remove Support in all current engines. Firefox 50+ Safari 6+ Chrome 31+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android 50+ Safari iOS 6+ Chrome Android 31+ WebView Android 4.4.3+ Samsung Internet 2.0+ Opera Android No Removes the index th entry in the drag data store items clear () DataTransferItemList/clear Support in all current engines. Firefox 50+ Safari 6+ Chrome 13+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android 50+ Safari iOS 6+ Chrome Android 18+ WebView Android 4.4+ Samsung Internet 1.0+ Opera Android No Removes all the entries in the drag data store items add data DataTransferItemList/add Support in all current engines. Firefox 50+ Safari 6+ Chrome 13+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android 50+ Safari iOS 6+ Chrome Android 18+ WebView Android 4.4+ Samsung Internet 1.0+ Opera Android No items add data type Adds a new entry for the given data to the drag data store . If the data is plain text then a type string has to be provided also. While the DataTransferItemList object's DataTransfer object is associated with a drag data store , the DataTransferItemList object's mode is the same as the drag data store mode . When the DataTransferItemList object's DataTransfer object is not associated with a drag data store , the DataTransferItemList object's mode is the disabled mode . The drag data store referenced in this section (which is used only when the DataTransferItemList object is not in the disabled mode ) is the drag data store with which the DataTransferItemList object's DataTransfer object is associated. The length attribute must return zero if the object is in the disabled mode ; otherwise it must return the number of items in the drag data store item list When a DataTransferItemList object is not in the disabled mode , its supported property indices are the numbers in the range 0 .. -1
where is the number of items in the drag data store item list To determine the value of an indexed property of a DataTransferItemList object, the user agent must return a DataTransferItem object representing the th item in the drag data store . The same object must be returned each time a particular item is obtained from this DataTransferItemList object. The DataTransferItem object must be associated with the same DataTransfer object as the DataTransferItemList object when it is first created. The add() method must run the following steps: If the DataTransferItemList object is not in the read/write mode , return null. Jump to the appropriate set of steps from the following list: If the first argument to the method is a string If there is already an item in the drag data store item list whose kind is text and whose type string is equal to the value of the method's second argument, converted to ASCII lowercase , then throw a NotSupportedError DOMException Otherwise, add an item to the drag data store item list whose kind is text , whose type string is equal to the value of the method's second argument, converted to ASCII lowercase , and whose data is the string given by the method's first argument. If the first argument to the method is a File Add an item to the drag data store item list whose kind is File , whose type string is the type of the File converted to ASCII lowercase , and whose data is the same as the File 's data. Determine the value of the indexed property corresponding to the newly added item, and return that value (a newly created DataTransferItem object). The remove() method, when invoked with the argument , must run these steps: If the DataTransferItemList object is not in the read/write mode , throw an InvalidStateError DOMException Remove the th item from the drag data store The clear() method, if the DataTransferItemList object is in the read/write mode must remove all the items from the drag data store . Otherwise, it must do nothing. 6.9.3.2 The DataTransferItem interface Each DataTransferItem object is associated with a DataTransfer object. DataTransferItem Support in all current engines. Firefox 50+ Safari 5.1+ Chrome 11+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android 50+ Safari iOS 5+ Chrome Android 18+ WebView Android 4+ Samsung Internet 1.0+ Opera Android No Exposed Window interface DataTransferItem readonly attribute DOMString kind readonly attribute DOMString type undefined getAsString FunctionStringCallback _callback ); File getAsFile (); }; callback FunctionStringCallback undefined DOMString data ); item kind DataTransferItem/kind Support in all current engines. Firefox 50+ Safari 5.1+ Chrome 11+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android 50+ Safari iOS 5+ Chrome Android 18+ WebView Android 4+ Samsung Internet 1.0+ Opera Android No Returns the drag data item kind , one of: "string", "file". item type DataTransferItem/type Support in all current engines. Firefox 50+ Safari 5.1+ Chrome 11+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android 50+ Safari iOS 5+ Chrome Android 18+ WebView Android 4+ Samsung Internet 1.0+ Opera Android No Returns the drag data item type string item getAsString callback DataTransferItem/getAsString Support in all current engines. Firefox 50+ Safari 5.1+ Chrome 11+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android 50+ Safari iOS 5+ Chrome Android 18+ WebView Android 4+ Samsung Internet 1.0+ Opera Android No Invokes the callback with the string data as the argument, if the drag data item kind is text file item getAsFile () DataTransferItem/getAsFile Support in all current engines. Firefox 50+ Safari 5.1+ Chrome 11+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android 50+ Safari iOS 5+ Chrome Android 18+ WebView Android 4+ Samsung Internet 1.0+ Opera Android No Returns a File object, if the drag data item kind is File While the DataTransferItem object's DataTransfer object is associated with a drag data store and that drag data store 's drag data store item list still contains the item that the DataTransferItem object represents, the DataTransferItem object's mode is the same as the drag data store mode . When the DataTransferItem object's DataTransfer object is not associated with a drag data store , or if the item that the DataTransferItem object represents has been removed from the relevant drag data store item list , the DataTransferItem object's mode is the disabled mode . The drag data store referenced in this section (which is used only when the DataTransferItem object is not in the disabled mode ) is the drag data store with which the DataTransferItem object's DataTransfer object is associated. The kind attribute must return the empty string if the DataTransferItem object is in the disabled mode ; otherwise it must return the string given in the cell from the second column of the following table from the row whose cell in the first column contains the drag data item kind of the item represented by the DataTransferItem object: Kind String Text string File file The type attribute must return the empty string if the DataTransferItem object is in the disabled mode ; otherwise it must return the drag data item type string of the item represented by the DataTransferItem object. The getAsString( callback method must run the following steps: If the callback is null, return. If the DataTransferItem object is not in the read/write mode or the read-only mode return. The callback is never invoked. If the drag data item kind is not text , then return. The callback is never invoked. Otherwise, queue a task to invoke callback , passing the actual data of the item represented by the DataTransferItem object as the argument. The getAsFile() method must run the following steps: If the DataTransferItem object is not in the read/write mode or the read-only mode then return null. If the drag data item kind is not File , then return null. Return a new File object representing the actual data of the item represented by the DataTransferItem object. 6.9.4 The DragEvent interface DragEvent/DragEvent Support in all current engines. Firefox 3.5+ Safari 3.1+ Chrome 46+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android Yes Safari iOS No Chrome Android No WebView Android No Samsung Internet No Opera Android No DragEvent Support in all current engines. Firefox 3.5+ Safari 3.1+ Chrome 3+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 4+ Safari iOS No Chrome Android No WebView Android No Samsung Internet No Opera Android No The drag-and-drop processing model involves several events. They all use the DragEvent interface. Exposed Window interface DragEvent MouseEvent constructor DOMString type optional DragEventInit eventInitDict = {}); readonly attribute DataTransfer dataTransfer }; dictionary DragEventInit MouseEventInit DataTransfer dataTransfer null }; event dataTransfer DragEvent/dataTransfer Support in all current engines. Firefox 3.5+ Safari 3.1+ Chrome 46+ Opera Yes Edge 79+ Edge (Legacy) 12+ Internet Explorer 🔰 10+ Firefox Android Yes Safari iOS No Chrome Android No WebView Android No Samsung Internet No Opera Android No Returns the DataTransfer object for the event. Although, for consistency with other event interfaces, the DragEvent interface has a constructor, it is not particularly useful. In particular, there's no way to create a useful DataTransfer object from script, as DataTransfer objects have a processing and security model that is coordinated by the browser during drag-and-drops. The dataTransfer attribute of the DragEvent interface must return the value it was initialized to. It represents the context information for the event. When a user agent is required to fire a DND event named at an element, using a particular drag data store , and optionally with a specific related target , the user agent must run the following steps: Let dataDragStoreWasChanged be false. If no specific related target was provided, set related target to null. Let window be the relevant global object of the Document object of the specified target element. If is dragstart , then set the drag data store mode to the read/write mode and set dataDragStoreWasChanged to true. If is drop , set the drag data store mode to the read-only mode Let dataTransfer be a newly created DataTransfer object associated with the given drag data store Set the effectAllowed attribute to the drag data store 's drag data store allowed effects state Set the dropEffect attribute to " none " if is dragstart drag , or dragleave ; to the value corresponding to the current drag operation if is drop or dragend ; and to a value based on the effectAllowed attribute's value and the drag-and-drop source, as given by the following table, otherwise (i.e. if is dragenter or dragover ): effectAllowed dropEffect none none copy copy copyLink copy ", or, if appropriate , " link copyMove copy ", or, if appropriate , " move all copy ", or, if appropriate , either " link " or " move link link linkMove link ", or, if appropriate , " move move move uninitialized " when what is being dragged is a selection from a text control move ", or, if appropriate , either " copy " or " link uninitialized " when what is being dragged is a selection copy ", or, if appropriate , either " link " or " move uninitialized " when what is being dragged is an element with an href attribute link ", or, if appropriate , either " copy " or " move Any other case copy ", or, if appropriate , either " link " or " move Where the table above provides possibly appropriate alternatives , user agents may instead use the listed alternative values if platform conventions dictate that the user has requested those alternate effects. For example, Windows platform conventions are such that dragging while holding the "alt" key indicates a preference for linking the data, rather than moving or copying it. Therefore, on a Windows system, if " link " is an option according to the table above while the "alt" key is depressed, the user agent could select that instead of copy " or " move ". Let event be the result of creating an event using DragEvent Initialize event 's type attribute to , its bubbles attribute to true, its view attribute to window , its relatedTarget attribute to related target , and its dataTransfer attribute to dataTransfer If is not dragleave or dragend , then initialize event 's cancelable attribute to true. Initialize event 's mouse and key attributes initialized according to the state of the input devices as they would be for user interaction events. If there is no relevant pointing device, then initialize event 's screenX screenY clientX clientY , and button attributes to 0. Dispatch event at the specified target element. Set the drag data store allowed effects state to the current value of dataTransfer 's effectAllowed attribute. (It can only have changed value if is dragstart .) If dataDragStoreWasChanged is true, then set the drag data store mode back to the protected mode Break the association between dataTransfer and the drag data store 6.9.5 Processing model When the user attempts to begin a drag operation, the user agent must run the following steps. User agents must act as if these steps were run even if the drag actually started in another document or application and the user agent was not aware that the drag was occurring until it intersected with a document under the user agent's purview. Determine what is being dragged, as follows: If the drag operation was invoked on a selection, then it is the selection that is being dragged. Otherwise, if the drag operation was invoked on a Document , it is the first element, going up the ancestor chain, starting at the node that the user tried to drag, that has the IDL attribute draggable set to true. If there is no such element, then nothing is being dragged; return, the drag-and-drop operation is never started. Otherwise, the drag operation was invoked outside the user agent's purview. What is being dragged is defined by the document or application where the drag was started. img elements and elements with an href attribute have their draggable attribute set to true by default. Create a drag data store . All the DND events fired subsequently by the steps in this section must use this drag data store Establish which DOM node is the source node , as follows: If it is a selection that is being dragged, then the source node is the Text node that the user started the drag on (typically the Text node that the user originally clicked). If the user did not specify a particular node, for example if the user just told the user agent to begin a drag of "the selection", then the source node is the first Text node containing a part of the selection. Otherwise, if it is an element that is being dragged, then the source node is the element that is being dragged. Otherwise, the source node is part of another document or application. When this specification requires that an event be dispatched at the source node in this case, the user agent must instead follow the platform-specific conventions relevant to that situation. Multiple events are fired on the source node during the course of the drag-and-drop operation. Determine the list of dragged nodes , as follows: If it is a selection that is being dragged, then the list of dragged nodes contains, in tree order , every node that is partially or completely included in the selection (including all their ancestors). Otherwise, the list of dragged nodes contains only the source node if any. If it is a selection that is being dragged, then add an item to the drag data store item list , with its properties set as follows: The drag data item type string text/plain The drag data item kind Text The actual data The text of the selection Otherwise, if any files are being dragged, then add one item per file to the drag data store item list , with their properties set as follows: The drag data item type string The MIME type of the file, if known, or " application/octet-stream " otherwise. The drag data item kind File The actual data The file's contents and name. Dragging files can currently only happen from outside a browsing context , for example from a file system manager application. If the drag initiated outside of the application, the user agent must add items to the drag data store item list as appropriate for the data being dragged, honoring platform conventions where appropriate; however, if the platform conventions do not use MIME types to label dragged data, the user agent must make a best-effort attempt to map the types to MIME types, and, in any case, all the drag data item type strings must be converted to ASCII lowercase User agents may also add one or more items representing the selection or dragged element(s) in other forms, e.g. as HTML. If the list of dragged nodes is not empty, then extract the microdata from those nodes into a JSON form , and add one item to the drag data store item list , with its properties set as follows: The drag data item type string application/microdata+json The drag data item kind Text The actual data The resulting JSON string. Run the following substeps: Let urls be an empty list of absolute URLs For each node in the list of dragged nodes If the node is an element with an href attribute Add to urls the result of parsing the element's href content attribute relative to the element's node document If the node is an img element with a src attribute Add to urls the result of parsing the element's src content attribute relative to the element's node document If urls is still empty, then return. Let url string be the result of concatenating the strings in urls in the order they were added, separated by a U+000D CARRIAGE RETURN U+000A LINE FEED character pair (CRLF). Add one item to the drag data store item list , with its properties set as follows: The drag data item type string text/uri-list The drag data item kind Text The actual data url string Update the drag data store default feedback as appropriate for the user agent (if the user is dragging the selection, then the selection would likely be the basis for this feedback; if the user is dragging an element, then that element's rendering would be used; if the drag began outside the user agent, then the platform conventions for determining the drag feedback should be used). Fire a DND event named dragstart at the source node If the event is canceled, then the drag-and-drop operation should not occur; return. Since events with no event listeners registered are, almost by definition, never canceled, drag-and-drop is always available to the user if the author does not specifically prevent it. Initiate the drag-and-drop operation in a manner consistent with platform conventions, and as described below. The drag-and-drop feedback must be generated from the first of the following sources that is available: The drag data store bitmap , if any. In this case, the drag data store hot spot coordinate should be used as hints for where to put the cursor relative to the resulting image. The values are expressed as distances in CSS pixels from the left side and from the top side of the image respectively. [CSS] The drag data store default feedback From the moment that the user agent is to initiate the drag-and-drop operation until the end of the drag-and-drop operation, device input events (e.g. mouse and keyboard events) must be suppressed. During the drag operation, the element directly indicated by the user as the drop target is called the immediate user selection . (Only elements can be selected by the user; other nodes must not be made available as drop targets.) However, the immediate user selection is not necessarily the current target element , which is the element currently selected for the drop part of the drag-and-drop operation. The immediate user selection changes as the user selects different elements (either by pointing at them with a pointing device, or by selecting them in some other way). The current target element changes when the immediate user selection changes, based on the results of event listeners in the document, as described below. Both the current target element and the immediate user selection can be null, which means no target element is selected. They can also both be elements in other (DOM-based) documents, or other (non-web) programs altogether. (For example, a user could drag text to a word-processor.) The current target element is initially null. In addition, there is also a current drag operation , which can take on the values none ", " copy ", " link ", and " move ". Initially, it has the value none ". It is updated by the user agent as described in the steps below. User agents must, as soon as the drag operation is initiated and every 350ms (±200ms) thereafter for as long as the drag operation is ongoing, queue a task to perform the following steps in sequence: If the user agent is still performing the previous iteration of the sequence (if any) when the next iteration becomes due, return for this iteration (effectively "skipping missed frames" of the drag-and-drop operation). Fire a DND event named drag at the source node . If this event is canceled, the user agent must set the current drag operation to " none " (no drag operation). If the drag event was not canceled and the user has not ended the drag-and-drop operation, check the state of the drag-and-drop operation, as follows: If the user is indicating a different immediate user selection than during the last iteration (or if this is the first iteration), and if this immediate user selection is not the same as the current target element , then update the current target element as follows: If the new immediate user selection is null Set the current target element to null also. If the new immediate user selection is in a non-DOM document or application Set the current target element to the immediate user selection Otherwise Fire a DND event named dragenter at the immediate user selection If the event is canceled, then set the current target element to the immediate user selection Otherwise, run the appropriate step from the following list: If the immediate user selection is a text control (e.g., textarea , or an input element whose type attribute is in the Text state) or an editing host or editable element, and the drag data store item list has an item with the drag data item type string text/plain " and the drag data item kind text Set the current target element to the immediate user selection anyway. If the immediate user selection is the body element Leave the current target element unchanged. Otherwise Fire a DND event named dragenter at the body element , if there is one, or at the Document object, if not. Then, set the current target element to the body element , regardless of whether that event was canceled or not. If the previous step caused the current target element to change, and if the previous target element was not null or a part of a non-DOM document, then fire a DND event named dragleave at the previous target element, with the new current target element as the specific related target If the current target element is a DOM element, then fire a DND event named dragover at this current target element If the dragover event is not canceled, run the appropriate step from the following list: If the current target element is a text control (e.g., textarea , or an input element whose type attribute is in the Text state) or an editing host or editable element, and the drag data store item list has an item with the drag data item type string text/plain " and the drag data item kind text Set the current drag operation to either " copy " or " move ", as appropriate given the platform conventions. Otherwise Reset the current drag operation to " none ". Otherwise (if the dragover event is canceled), set the current drag operation based on the values of the effectAllowed and dropEffect attributes of the DragEvent object's dataTransfer object as they stood after the event dispatch finished, as per the following table: effectAllowed dropEffect Drag operation uninitialized ", " copy ", " copyLink ", " copyMove ", or " all copy copy uninitialized ", " link ", " copyLink ", " linkMove ", or " all link link uninitialized ", " move ", " copyMove ", " linkMove ", or " all move move Any other case none Otherwise, if the current target element is not a DOM element, use platform-specific mechanisms to determine what drag operation is being performed (none, copy, link, or move), and set the current drag operation accordingly. Update the drag feedback (e.g. the mouse cursor) to match the current drag operation , as follows: Drag operation Feedback copy Data will be copied if dropped here. link Data will be linked if dropped here. move Data will be moved if dropped here. none No operation allowed, dropping here will cancel the drag-and-drop operation. Otherwise, if the user ended the drag-and-drop operation (e.g. by releasing the mouse button in a mouse-driven drag-and-drop interface), or if the drag event was canceled, then this will be the last iteration. Run the following steps, then stop the drag-and-drop operation: If the current drag operation is " none " (no drag operation), or, if the user ended the drag-and-drop operation by canceling it (e.g. by hitting the Escape key), or if the current target element is null, then the drag operation failed. Run these substeps: Let dropped be false. If the current target element is a DOM element, fire a DND event named dragleave at it; otherwise, if it is not null, use platform-specific conventions for drag cancelation. Set the current drag operation to " none ". Otherwise, the drag operation might be a success; run these substeps: Let dropped be true. If the current target element is a DOM element, fire a DND event named drop at it; otherwise, use platform-specific conventions for indicating a drop. If the event is canceled, set the current drag operation to the value of the dropEffect attribute of the DragEvent object's dataTransfer object as it stood after the event dispatch finished. Otherwise, the event is not canceled; perform the event's default action, which depends on the exact target as follows: If the current target element is a text control (e.g., textarea , or an input element whose type attribute is in the Text state) or an editing host or editable element, and the drag data store item list has an item with the drag data item type string text/plain " and the drag data item kind text Insert the actual data of the first item in the drag data store item list to have a drag data item type string of " text/plain " and a drag data item kind that is text into the text control or editing host or editable element in a manner consistent with platform-specific conventions (e.g. inserting it at the current mouse cursor position, or inserting it at the end of the field). Otherwise Reset the current drag operation to " none ". Fire a DND event named dragend at the source node Run the appropriate steps from the following list as the default action of the dragend event: If dropped is true, the current target element is a text control (see below), the current drag operation is " move ", and the source of the drag-and-drop operation is a selection in the DOM that is entirely contained within an editing host Delete the selection If dropped is true, the current target element is a text control (see below), the current drag operation is " move ", and the source of the drag-and-drop operation is a selection in a text control The user agent should delete the dragged selection from the relevant text control. If dropped is false or if the current drag operation is " none The drag was canceled. If the platform conventions dictate that this be represented to the user (e.g. by animating the dragged selection going back to the source of the drag-and-drop operation), then do so. Otherwise The event has no default action. For the purposes of this step, a text control is a textarea element or an input element whose type attribute is in one of the Text Tel URL Email Password , or Number states. User agents are encouraged to consider how to react to drags near the edge of scrollable regions. For example, if a user drags a link to the bottom of the viewport on a long page, it might make sense to scroll the page so that the user can drop the link lower on the page. This model is independent of which Document object the nodes involved are from; the events are fired as described above and the rest of the processing model runs as described above, irrespective of how many documents are involved in the operation. 6.9.6 Events summary This section is non-normative. The following events are involved in the drag-and-drop model. Event name Target Cancelable? Drag data store mode dropEffect Default Action dragstart Document/dragstart_event Support in all current engines. Firefox 3.5+ Safari 3.1+ Chrome 4+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android No Safari iOS 11+ Chrome Android No WebView Android No Samsung Internet No Opera Android No Source node ✓ Cancelable Read/write mode none Initiate the drag-and-drop operation drag Document/drag_event Firefox 🔰 3.5+ Safari 3.1+ Chrome 4+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android No Safari iOS 11+ Chrome Android No WebView Android No Samsung Internet No Opera Android No Source node ✓ Cancelable Protected mode none Continue the drag-and-drop operation dragenter Document/dragenter_event Support in all current engines. Firefox 3.5+ Safari 3.1+ Chrome 4+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android No Safari iOS 11+ Chrome Android No WebView Android No Samsung Internet No Opera Android No Immediate user selection or the body element ✓ Cancelable Protected mode Based on effectAllowed value Reject immediate user selection as potential target element dragleave Document/dragleave_event Support in all current engines. Firefox 3.5+ Safari 3.1+ Chrome 4+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android No Safari iOS 11+ Chrome Android No WebView Android No Samsung Internet No Opera Android No Previous target element Protected mode none None dragover Document/dragover_event Support in all current engines. Firefox 3.5+ Safari 3.1+ Chrome 4+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android No Safari iOS 11+ Chrome Android No WebView Android No Samsung Internet No Opera Android No Current target element ✓ Cancelable Protected mode Based on effectAllowed value Reset the current drag operation to "none" drop Document/drop_event Support in all current engines. Firefox 3.5+ Safari 3.1+ Chrome 4+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android No Safari iOS 11+ Chrome Android No WebView Android No Samsung Internet No Opera Android No Current target element ✓ Cancelable Read-only mode Current drag operation Varies dragend Document/dragend_event Firefox 🔰 3.5+ Safari 3.1+ Chrome 4+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android No Safari iOS 11+ Chrome Android No WebView Android No Samsung Internet No Opera Android No Source node Protected mode Current drag operation Varies Not shown in the above table: all these events bubble, are composed, and the effectAllowed attribute always has the value it had after the dragstart event, defaulting to " uninitialized " in the dragstart event. 6.9.7 The draggable attribute Global_attributes/draggable Support in all current engines. Firefox 2+ Safari Yes Chrome Yes Opera 12+ Edge Yes Edge (Legacy) 12+ Internet Explorer Yes Firefox Android 4+ Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes All HTML elements may have the draggable content attribute set. The draggable attribute is an enumerated attribute . It has three states. The first state is true and it has the keyword true The second state is false and it has the keyword false . The third state is auto ; it has no keywords but it is the missing value default and the invalid value default The true state means the element is draggable; the false state means that it is not. The auto state uses the default behavior of the user agent. An element with a draggable attribute should also have a title attribute that names the element for the purpose of non-visual interactions. element draggable [ = value Returns true if the element is draggable; otherwise, returns false. Can be set, to override the default and set the draggable content attribute. The draggable IDL attribute, whose value depends on the content attribute's in the way described below, controls whether or not the element is draggable. Generally, only text selections are draggable, but elements whose draggable IDL attribute is true become draggable as well. If an element's draggable content attribute has the state true , the draggable IDL attribute must return true. Otherwise, if the element's draggable content attribute has the state false , the draggable IDL attribute must return false. Otherwise, the element's draggable content attribute has the state auto . If the element is an img element, an object element that represents an image, or an element with an href content attribute, the draggable IDL attribute must return true; otherwise, the draggable IDL attribute must return false. If the draggable IDL attribute is set to the value false, the draggable content attribute must be set to the literal value " false ". If the draggable IDL attribute is set to the value true, the draggable content attribute must be set to the literal value " true ". 6.9.8 Security risks in the drag-and-drop model User agents must not make the data added to the DataTransfer object during the dragstart event available to scripts until the drop event, because otherwise, if a user were to drag sensitive information from one document to a second document, crossing a hostile third document in the process, the hostile document could intercept the data. For the same reason, user agents must consider a drop to be successful only if the user specifically ended the drag operation — if any scripts end the drag operation, it must be considered unsuccessful (canceled) and the drop event must not be fired. User agents should take care to not start drag-and-drop operations in response to script actions. For example, in a mouse-and-window environment, if a script moves a window while the user has their mouse button depressed, the UA would not consider that to start a drag. This is important because otherwise UAs could cause data to be dragged from sensitive sources and dropped into hostile documents without the user's consent. User agents should filter potentially active (scripted) content (e.g. HTML) when it is dragged and when it is dropped, using a safelist of known-safe features. Similarly, relative URLs should be turned into absolute URLs to avoid references changing in unexpected ways. This specification does not specify how this is performed. Consider a hostile page providing some content and getting the user to select and drag and drop (or indeed, copy and paste) that content to a victim page's contenteditable region. If the browser does not ensure that only safe content is dragged, potentially unsafe content such as scripts and event handlers in the selection, once dropped (or pasted) into the victim site, get the privileges of the victim site. This would thus enable a cross-site scripting attack. Loading web pages This section describes features that apply most directly to web browsers. Having said that, except where specified otherwise, the requirements defined in this section do apply to all user agents, whether they are web browsers or not. 7.1 Browsing contexts browsing context is an environment in which Document objects are presented to the user. A tab or window in a web browser typically contains a browsing context , as does an iframe or frame s in a frameset browsing context has a corresponding WindowProxy object. browsing context has an opener browsing context , which is null or a browsing context . It is initially null. browsing context has a disowned boolean. It is initially false. browsing context has an is closing boolean. It is initially false. The following example illustrates the various possibilities of a browsing context It can be disowned is closing , neither, or both. // Neither disowned nor is closing: const popup1 window open (); // Disowned, but not is closing: const popup2 window open (); popup2 opener null // Not disowned, but is closing: const popup3 window open (); popup3 close (); // Disowned, is closing: const popup4 window open (); popup4 opener null popup4 close (); browsing context has a session history , which lists the Document objects that the browsing context has presented, is presenting, or will present. A Document 's browsing context is the browsing context whose session history contains the Document , if any such browsing context exists and has not been discarded , and null otherwise. Document does not necessarily have a non-null browsing context . In particular, data mining tools are likely to never instantiate browsing contexts. A Document created using an API such as createDocument() never has a non-null browsing context . And the Document originally created for an iframe element, which has since been removed from the document , has no associated browsing context, since that browsing context was discarded browsing context 's active window is its WindowProxy object's [[Window]] internal slot value. A browsing context 's active document is its active window 's associated Document In general, there is a 1-to-1 mapping from the Window object to the Document object, as long as the Document object has a non-null browsing context . There is one exception. A Window can be reused for the presentation of a second Document in the same browsing context , such that the mapping is then 1-to-2. This occurs when a browsing context is navigated from the initial about:blank Document to another, with historyHandling set to " replace ". browsing context has a virtual browsing context group ID integer. It is initially 0. This is used by cross-origin opener policy reporting , to keep track of the browsing context group switches that would have happened if the report-only policy had been enforced. browsing context has an initial URL , which is a URL or null. It is initially null. browsing context has an opener origin at creation , which is an origin or null. It is initially null. 7.1.1 Creating browsing contexts To set the active document of a browsing context browsingContext to a Document object document , run these steps: Let window be document 's relevant global object Set browsingContext 's active window to window Set window 's associated Document to document Set window 's relevant settings object 's execution ready flag browsing context has an associated creator origin (null or returns an origin ), creator URL (null or returns a URL ), and creator base URL (null or returns a URL ). These are all initially null. To determine the origin , given browsing context browsingContext URL url sandboxing flag set sandboxFlags , and two origins invocationOrigin and activeDocumentNavigationOrigin If sandboxFlags has its sandboxed origin browsing context flag set, then return a new opaque origin If url is null, then return a new opaque origin If activeDocumentNavigationOrigin is not null, and url 's scheme is " javascript ", then return activeDocumentNavigationOrigin If invocationOrigin is non-null and url is about:blank then return invocationOrigin The result here is that two documents end up with the same underlying origin , meaning that document.domain affects both. If url is about:srcdoc , then return the origin of browsingContext 's container document Return url 's origin To create a new browsing context , given null or a Document object creator , null or an element embedder and a browsing context group group , run these steps: Let browsingContext be a new browsing context If creator is non-null, then set browsingContext 's creator origin to return creator 's origin browsingContext 's creator URL to return creator 's URL browsingContext 's creator base URL to return creator 's base URL , and browsingContext 's virtual browsing context group ID to creator 's top-level browsing context 's virtual browsing context group ID Let sandboxFlags be the result of determining the creation sandboxing flags given browsingContext and embedder Let origin be the result of determining the origin given browsingContext about:blank sandboxFlags browsingContext 's creator origin , and null. Let permissionsPolicy be the result of creating a permissions policy given browsingContext and origin [PERMISSIONSPOLICY] This needs to use embedder Let agent be the result of obtaining a similar-origin window agent given origin group , and false. Let realm execution context be the result of creating a new JavaScript realm given agent and the following customizations: For the global object, create a new Window object. For the global this binding, use browsingContext 's WindowProxy object. Let topLevelCreationURL be about:blank if embedder is null; otherwise embedder 's relevant settings object 's top-level creation URL Let topLevelOrigin be origin if embedder is null; otherwise embedder 's relevant settings object 's top-level origin Set up a window environment settings object with about:blank realm execution context , null, topLevelCreationURL , and topLevelOrigin Let coop be a new cross-origin opener policy If creator is non-null and creator 's origin is same origin with creator 's relevant settings object 's top-level origin , then set coop to creator 's browsing context 's top-level browsing context 's active document 's cross-origin opener policy Let document be a new Document , marked as an HTML document in quirks mode , whose content type is " text/html ", origin is origin active sandboxing flag set is sandboxFlags permissions policy is permissionsPolicy cross-origin opener policy is coop , and which is ready for post-load tasks Assert: document 's URL and document 's relevant settings object 's creation URL are about:blank Set document 's is initial about:blank to true. Ensure that document has a single child html node, which itself has two empty child nodes: a head element, and a body element. Set the active document of browsingContext to document If browsingContext 's creator URL is non-null, then set document 's referrer to the serialization of it. If creator is non-null, then set document 's referrer policy to creator 's referrer policy If creator is non-null, then set document 's embedder policy to creator 's embedder policy If creator is non-null, then set document 's policy container to a clone of creator 's policy container Append a new session history entry to browsingContext 's session history whose URL is about:blank and document is document Completely finish loading document Return browsingContext To create a new top-level browsing context Let group be the result of creating a new browsing context group Return group 's browsing context set [0]. This creates a top-level browsing context To create a new auxiliary browsing context , given a browsing context opener Let group be opener 's top-level browsing context 's group Assert: group is non-null, as navigating invokes this directly. Let browsingContext be the result of creating a new browsing context with opener 's active document , null, and group Append browsingContext to group Set browsingContext 's opener browsing context to opener Set browsingContext 's virtual browsing context group ID to opener 's top-level browsing context 's virtual browsing context group ID Set browsingContext 's opener origin at creation to opener 's active document 's origin Legacy-clone a browsing session storage shed with opener 's browsing session and browsingContext 's browsing session [STORAGE] Return browsingContext This creates a top-level browsing context that is also an auxiliary browsing context To create a new nested browsing context given an element element Let group be element 's node document 's browsing context 's top-level browsing context 's group Let browsingContext be the result of creating a new browsing context with element 's node document element , and group Set element 's nested browsing context to browsingContext If element has a name attribute, then set browsingContext 's name to the value of this attribute. 7.1.2 Related browsing contexts Certain elements (for example, iframe elements) can instantiate further browsing contexts . These elements are called browsing context containers Each browsing context container has a nested browsing context which is either a browsing context or null. It is initially null. The container of a browsing context bc is the browsing context container whose nested browsing context is bc , or null if there is no such element. Each browsing context bc has a container document , which is the result of running these steps: If bc 's container is null, then return null. Return bc 's container 's node document This is equal to bc 's container 's shadow-including root as bc 's container has to be connected browsing context child is said to be a child browsing context of another browsing context parent , if child 's container document is non-null and child 's container document 's browsing context is parent browsing context child is a document-tree child browsing context of parent if child is a child browsing context and child 's container is in a document tree browsing context child may have a parent browsing context . This is the unique browsing context that has child as a child browsing context , if any such browsing context exists. Otherwise, the browsing context has no parent browsing context browsing context is said to be an ancestor of a browsing context if there exists a browsing context A' that is a child browsing context of and that is itself an ancestor of , or if the browsing context is the parent browsing context of browsing context that has no parent browsing context is the top-level browsing context for itself and all of the browsing contexts for which it is an ancestor browsing context top-level browsing context has an associated group (null or a browsing context group ). It is initially null. It is possible to create new browsing contexts that are related to a top-level browsing context while their container is null. Such browsing contexts are called auxiliary browsing contexts . Auxiliary browsing contexts are always top-level browsing contexts The transitive closure of parent browsing contexts for a browsing context that is a child browsing context gives the list of ancestor browsing contexts The list of the descendant browsing contexts of a Document is the (ordered) list returned by the following algorithm: Let list be an empty list For each browsing context container container , whose nested browsing context is non-null and whose shadow-including root is , in shadow-including tree order Let nestedBC be container 's nested browsing context Append nestedBC to list Extend list with the list of the descendant browsing contexts of nestedBC 's active document Return list Document is said to be fully active when 's browsing context is non-null, 's browsing context 's active document is , and either 's browsing context is a top-level browsing context or 's browsing context 's container document is fully active Because they are associated with an element, child browsing contexts are always tied to a specific Document in their parent browsing context . User agents must not allow the user to interact with child browsing contexts of elements that are in Document that are not themselves fully active The following example illustrates the differences between active and fully active Document objects. Here a.html is loaded into a browser window, b-1.html starts out loaded into an iframe as shown, and b-2.html and c.html are omitted (they can simply be an empty document). html lang "en" title Browsing context A title iframe src "b-1.html" > iframe button onclick "frames[0].location.href = 'b-2.html'" Click me button html lang "en" title Browsing context B title iframe src "c.html" > iframe At this point, the documents given by a.html b-1.html , and c.html are all the active documents of their respective browsing contexts . They are also all fully active After clicking on the button , and thus loading a new Document from b-2.html into browsing context B, we have the following results: The a.html Document remains both the active document of browsing context A, and fully active The b-1.html Document is now not the active document of browsing context B. As such it is also not fully active The new b-2.html Document is now the active document of browsing context B, and is also fully active The c.html Document is still the active document of browsing context C. However, since C's container document is the b-1.html Document , which is itself not fully active , this means the c.html Document is now not fully active (even though it is active ). For more explorations of the complexities involved here, especially as it impacts the session history , see A Model of Navigation History [NAVMODEL] child browsing context can be put into a delaying load events mode . This is used when it is navigated , to delay the load event of its container before the new Document is created. The document family of a browsing context consists of the union of all the Document objects in that browsing context 's session history and the document families of all those Document objects. The document family of a Document object consists of the union of all the document families of the browsing contexts in the list of the descendant browsing contexts of the Document object. The content document of a browsing context container container is the result of the following algorithm: If container 's nested browsing context is null, then return null. Let context be container 's nested browsing context Let document be context 's active document If document 's origin and container 's node document 's origin are not same origin-domain , then return null. Return document 7.1.2.1 Navigating related browsing contexts in the DOM window top Window/top Support in all current engines. Firefox 1+ Safari 3+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ Returns the WindowProxy for the top-level browsing context window opener [ = value Window/opener Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 3+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 10.1+ Returns the WindowProxy for the opener browsing context Returns null if there isn't one or if it has been set to null. Can be set to null. window parent Window/parent Support in all current engines. Firefox 1+ Safari 1.3+ Chrome 1+ Opera 3+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 10.1+ Returns the WindowProxy for the parent browsing context window frameElement Window/frameElement Support in all current engines. Firefox 1+ Safari 3+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 5.5+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ Returns the Element for the browsing context container Returns null if there isn't one, and in cross-origin situations. The top attribute's getter must run these steps: If this Window object's browsing context is null, then return null. Return this Window object's browsing context 's top-level browsing context 's WindowProxy object. The opener attribute's getter must run these steps: Let current be this Window object's browsing context If current is null, then return null. If current 's disowned is true, then return null. If current 's opener browsing context is null, then return null. Return current 's opener browsing context 's WindowProxy object. The opener attribute's setter must run these steps: If the given value is null and this Window object's browsing context is non-null, then set this Window object's browsing context 's disowned to true. If the given value is non-null, then return ? OrdinaryDefineOwnProperty (this Window object, " opener ", { [[Value]]: the given value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }). If a browsing context 's disowned is true, its window.opener attribute is null. That prevents scripts in the browsing context from changing any properties of its opener browsing context 's Window object (i.e., the Window object from which the browsing context was created). Otherwise, if a browsing context 's disowned is false, then scripts in that browsing context can use window.opener to change properties of its opener browsing context 's Window object. For example, a script running in the browsing context can change the value of window.opener.location , causing the opener browsing context to navigate to a completely different document. The parent attribute's getter must run these steps: Let current be this Window object's browsing context If current is null, then return null. If current is a child browsing context of another browsing context parent , then return parent 's WindowProxy object. Assert: current is a top-level browsing context Return current 's WindowProxy object. The frameElement attribute's getter must run these steps: Let current be this Window object's browsing context If current is null, then return null. Let container be current 's container If container is null, then return null. If container 's node document 's origin is not same origin-domain with the current settings object 's origin , then return null. Return container An example of when these IDL attributes can return null is as follows: iframe > iframe script "use strict" const element document querySelector "iframe" ); const iframeWindow element contentWindow element remove (); console assert iframeWindow top === null ); console assert iframeWindow parent === null ); console assert iframeWindow frameElement === null ); script Here the browsing context corresponding to iframeWindow was discarded when element was removed from the document. 7.1.3 Security browsing context is familiar with a second browsing context if one of the following conditions is true: Either the origin of the active document of is the same as the origin of the active document of , or The browsing context is a child browsing context and its top-level browsing context is , or The browsing context is an auxiliary browsing context and is familiar with 's opener browsing context , or The browsing context is not a top-level browsing context but there exists an ancestor browsing context of whose active document has the same origin as the active document of (possibly in fact being itself). browsing context is allowed to navigate second browsing context if the following algorithm returns true: If is not the same browsing context as , and is not one of the ancestor browsing contexts of , and is not a top-level browsing context , and 's active document 's active sandboxing flag set has its sandboxed navigation browsing context flag set, then return false. Otherwise, if is a top-level browsing context , and is one of the ancestor browsing contexts of then: If 's active window has transient activation and 's active document 's active sandboxing flag set has its sandboxed top-level navigation with user activation browsing context flag set, then return false. Otherwise, if 's active window does not have transient activation and 's active document 's active sandboxing flag set has its sandboxed top-level navigation without user activation browsing context flag set, then return false. Otherwise, if is a top-level browsing context , and is neither nor one of the ancestor browsing contexts of , and 's Document 's active sandboxing flag set has its sandboxed navigation browsing context flag set, and is not the one permitted sandboxed navigator of , then return false. Return true. An element has a browsing context scope origin if its Document 's browsing context is a top-level browsing context or if all of its Document 's ancestor browsing contexts all have active documents whose origins are the same origin as the element's node document 's origin . If an element has a browsing context scope origin , then its value is the origin of the element's node document 7.1.4 Groupings of browsing contexts A user agent holds a browsing context group set (a set of browsing context groups ). browsing context group holds a browsing context set (a set of top-level browsing contexts ). top-level browsing context is added to the group when the group is created . All subsequent top-level browsing contexts added to the group will be auxiliary browsing contexts browsing context group has an associated agent cluster map (a weak map of agent cluster keys to agent clusters ). User agents are responsible for collecting agent clusters when it is deemed that nothing can access them anymore. browsing context group has an associated historical agent cluster key map , which is a map of origins to agent cluster keys . This map is used to ensure the consistency of the origin-keyed agent clusters feature by recording what agent cluster keys were previously used for a given origin. The historical agent cluster key map only ever gains entries over the lifetime of the browsing context group. browsing context group has a cross-origin isolation mode , which is a cross-origin isolation mode . It is initially " none ". cross-origin isolation mode is one of three possible values: " none ", " logical ", or " concrete ". logical " and " concrete " are similar. They are both used for browsing context groups where: every top-level Document has ` Cross-Origin-Opener-Policy same-origin `, and every Document has ` Cross-Origin-Embedder-Policy require-corp `. On some platforms, it is difficult to provide the security properties required to grant safe access to the APIs gated by the cross-origin isolated capability . As a result, only " concrete " can grant access that capability. logical " is used on platform not supporting this capability, where various restrictions imposed by cross-origin isolation will still apply, but the capability is not granted. To create a new browsing context group , run these steps: Let group be a new browsing context group Append group to the user agent's browsing context group set Let browsingContext be the result of creating a new browsing context with null, null, and group Append browsingContext to group Return group To append top-level browsing context browsingContext to a browsing context group group , run these steps: Append browsingContext to group 's browsing context set Set browsingContext 's group to group To remove top-level browsing context browsingContext , run these steps: Assert: browsingContext 's group is non-null, because a browsing context only gets discarded once. Let group be browsingContext 's group Set browsingContext 's group to null. Remove browsingContext from group 's browsing context set If group 's browsing context set is empty , then remove group from the user agent's browsing context group set Append and remove are primitive operations that help define the lifetime of a browsing context group . They are called from creating a new browsing context group creating a new auxiliary browsing context , and discarding a browsing context The HTML Standard used to define " unit of related browsing contexts " and " unit of related similar-origin browsing contexts ". These have been removed as they were not adequate. 7.1.5 Browsing context names Browsing contexts can have a browsing context name . Unless stated otherwise, it is the empty string. valid browsing context name is any string with at least one character that does not start with a U+005F LOW LINE character. (Names starting with an underscore are reserved for special keywords.) valid browsing context name or keyword is any string that is either a valid browsing context name or that is an ASCII case-insensitive match for one of: _blank _self _parent , or _top These values have different meanings based on whether the page is sandboxed or not, as summarized in the following (non-normative) table. In this table, "current" means the browsing context that the link or script is in, "parent" means the parent browsing context of the one the link or script is in, "top" means the top-level browsing context of the one the link or script is in, "new" means a new top-level browsing context or auxiliary browsing context is to be created, subject to various user preferences and user agent policies, "none" means that nothing will happen, and "maybe new" means the same as "new" if the " allow-popups " keyword is also specified on the sandbox attribute (or if the user overrode the sandboxing), and the same as "none" otherwise. Keyword Ordinary effect Effect in an iframe with... sandbox="" sandbox="allow-top-navigation" none specified, for links and form submissions current current current empty string current current current _blank new maybe new maybe new _self current current current _parent if there isn't a parent current current current _parent if parent is also top parent/top none parent/top _parent if there is one and it's not top parent none none _top if top is current current current current _top if top is not current top none top name that doesn't exist new maybe new maybe new name that exists and is a descendant specified descendant specified descendant specified descendant name that exists and is current current current current name that exists and is an ancestor that is top specified ancestor none specified ancestor/top name that exists and is an ancestor that is not top specified ancestor none none other name that exists with common top specified none none name that exists with different top, if familiar and one permitted sandboxed navigator specified specified specified name that exists with different top, if familiar but not one permitted sandboxed navigator specified none none name that exists with different top, not familiar new maybe new maybe new Most of the restrictions on sandboxed browsing contexts are applied by other algorithms, e.g. the algorithm, not the rules for choosing a browsing context given below. The rules for choosing a browsing context , given a browsing context name name , a browsing context current , and a boolean noopener are as follows: Let chosen be null. Let windowType be " existing or none ". Let sandboxingFlagSet be current 's active document 's active sandboxing flag set If name is the empty string or an ASCII case-insensitive match for _self ", then set chosen to current Otherwise, if name is an ASCII case-insensitive match for " _parent ", set chosen to current 's parent browsing context , if any, and current otherwise. Otherwise, if name is an ASCII case-insensitive match for " _top ", set chosen to current 's top-level browsing context , if any, and current otherwise. Otherwise, if name is not an ASCII case-insensitive match for " _blank ", there exists a browsing context whose name is the same as name current is familiar with that browsing context, and the user agent determines that the two browsing contexts are related enough that it is ok if they reach each other, set chosen to that browsing context. If there are multiple matching browsing contexts, the user agent should set chosen to one in some arbitrary consistent manner, such as the most recently opened, most recently focused, or more closely related. This will be made more precise in issue #313 Otherwise, a new browsing context is being requested, and what happens depends on the user agent's configuration and abilities — it is determined by the rules given for the first applicable option from the following list: If current 's active window does not have transient activation and the user agent has been configured to not show popups (i.e., the user agent has a "popup blocker" enabled) The user agent may inform the user that a popup has been blocked. If sandboxingFlagSet has the sandboxed auxiliary navigation browsing context flag set The user agent may report to a developer console that a popup has been blocked. If the user agent has been configured such that in this instance it will create a new browsing context Set windowType to " new and unrestricted ". If current 's top-level browsing context 's active document 's cross-origin opener policy 's value is " same-origin " or " same-origin-plus-COEP ", then: Let currentDocument be current 's active document If currentDocument 's origin is not same origin with currentDocument 's relevant settings object 's top-level origin , then set noopener to true, name to " _blank ", and windowType to " new with no opener ". In the presence of a cross-origin opener policy , nested documents that are cross-origin with their top-level browsing context's active document always set noopener to true. If noopener is true, then set chosen to the result of creating a new top-level browsing context Otherwise: Set chosen to the result of creating a new auxiliary browsing context with current If sandboxingFlagSet 's sandboxed navigation browsing context flag is set, then current must be set as chosen 's one permitted sandboxed navigator If sandboxingFlagSet 's sandbox propagates to auxiliary browsing contexts flag is set, then all the flags that are set in sandboxingFlagSet must be set in chosen 's popup sandboxing flag set If name is not an ASCII case-insensitive match for " _blank ", then set chosen 's name to name If the newly created browsing context is immediately navigated , then the navigation will be done with historyHandling set to " replace ". If the user agent has been configured such that in this instance it will reuse current Set chosen to current If the user agent has been configured such that in this instance it will not find a browsing context Do nothing. User agents are encouraged to provide a way for users to configure the user agent to always reuse current Return chosen and windowType 7.2 Security infrastructure for Window WindowProxy , and Location objects Although typically objects cannot be accessed across origins , the web platform would not be true to itself if it did not have some legacy exceptions to that rule that the web depends upon. 7.2.1 Integration with IDL When perform a security check is invoked, with a platformObject identifier , and type , run these steps: If platformObject is not a Window or Location object, then return. For each of ! CrossOriginProperties platformObject ): If SameValue .[[Property]], identifier ) is true, then: If type is " method " and has neither [[NeedsGet]] nor [[NeedsSet]], then return. Otherwise, if type is " getter " and .[[NeedsGet]] is true, then return. Otherwise, if type is " setter " and .[[NeedsSet]] is true, then return. If ! IsPlatformObjectSameOrigin platformObject ) is false, then throw a SecurityError DOMException 7.2.2 Shared internal slot: [[CrossOriginPropertyDescriptorMap]] Window and Location objects both have a [[CrossOriginPropertyDescriptorMap]] internal slot, whose value is initially an empty map. The [[CrossOriginPropertyDescriptorMap]] internal slot contains a map with entries whose keys are ( currentGlobal objectGlobal propertyKey )-tuples and values are property descriptors, as a memoization of what is visible to scripts when currentGlobal inspects a Window or Location object from objectGlobal . It is filled lazily by CrossOriginGetOwnPropertyHelper , which consults it on future lookups. User agents should allow a value held in the map to be garbage collected along with its corresponding key when nothing holds a reference to any part of the value. That is, as long as garbage collection is not observable. For example, with const href = Object.getOwnPropertyDescriptor(crossOriginLocation, "href").set the value and its corresponding key in the map cannot be garbage collected as that would be observable. User agents may have an optimization whereby they remove key-value pairs from the map when document.domain is set. This is not observable as document.domain cannot revisit an earlier value. For example, setting document.domain to " example.com " on www.example.com means user agents can remove all key-value pairs from the map where part of the key is www.example.com, as that can never be part of the origin again and therefore the corresponding value could never be retrieved from the map. 7.2.3 Shared abstract operations 7.2.3.1 CrossOriginProperties Assert: is a Location or Window object. If is a Location object, then return « { [[Property]]: " href ", [[NeedsGet]]: false, [[NeedsSet]]: true }, { [[Property]]: " replace " } ». Return « { [[Property]]: " window ", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: " self ", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: " location ", [[NeedsGet]]: true, [[NeedsSet]]: true }, { [[Property]]: " close " }, { [[Property]]: " closed ", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: " focus " }, { [[Property]]: " blur " }, { [[Property]]: " frames ", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: " length ", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: " top ", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: " opener ", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: " parent ", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: " postMessage " } ». Indexed properties do not need to be safelisted in this algorithm, as they are handled directly by the WindowProxy object. A JavaScript property name is a cross-origin accessible window property name if it is " window ", " self ", " location ", " close ", " closed ", focus ", " blur ", " frames ", length ", " top ", " opener ", parent ", " postMessage ", or an array index property name 7.2.3.2 CrossOriginPropertyFallback If is " then ", @@toStringTag @@hasInstance , or @@isConcatSpreadable , then return PropertyDescriptor [[Value]]: undefined, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }. Throw a SecurityError DOMException 7.2.3.3 IsPlatformObjectSameOrigin Return true if the current settings object 's origin is same origin-domain with 's relevant settings object 's origin , and false otherwise. Here the current settings object roughly corresponds to the "caller", because this check occurs before the execution context for the getter/setter/method in question makes its way onto the JavaScript execution context stack . For example, in the code w.document , this step is invoked before the document getter is reached as part of the [[Get]] algorithm for the WindowProxy 7.2.3.4 CrossOriginGetOwnPropertyHelper If this abstract operation returns undefined and there is no custom behavior, the caller needs to throw a SecurityError DOMException . In practice this is handled by the caller calling CrossOriginPropertyFallback Let crossOriginKey be a tuple consisting of the current settings object 's relevant settings object , and For each of ! CrossOriginProperties ): If SameValue .[[Property]], ) is true, then: If the value of the [[CrossOriginPropertyDescriptorMap]] internal slot of contains an entry whose key is crossOriginKey , then return that entry's value. Let originalDesc be OrdinaryGetOwnProperty ). Let crossOriginDesc be undefined. If .[[NeedsGet]] and .[[NeedsSet]] are absent, then: Let value be originalDesc .[[Value]]. If ! IsCallable value ) is true, then set value to an anonymous built-in function, created in the current Realm Record , that performs the same steps as the IDL operation on object Set crossOriginDesc to PropertyDescriptor [[Value]]: value [[Enumerable]]: false, [[Writable]]: false, [[Configurable]]: true }. Otherwise: Let crossOriginGet be undefined. If .[[NeedsGet]] is true, then set crossOriginGet to an anonymous built-in function, created in the current Realm Record , that performs the same steps as the getter of the IDL attribute on object Let crossOriginSet be undefined. If .[[NeedsSet]] is true, then set crossOriginSet to an anonymous built-in function, created in the current Realm Record , that performs the same steps as the setter of the IDL attribute on object Set crossOriginDesc to PropertyDescriptor [[Get]]: crossOriginGet [[Set]]: crossOriginSet [[Enumerable]]: false, [[Configurable]]: true }. Create an entry in the value of the [[CrossOriginPropertyDescriptorMap]] internal slot of with key crossOriginKey and value crossOriginDesc Return crossOriginDesc Return undefined. The reason that the property descriptors produced here are configurable is to preserve the invariants of the essential internal methods required by the JavaScript specification. In particular, since the value of the property can change as a consequence of navigation, it is required that the property be configurable. (However, see tc39/ecma262 issue #672 and references to it elsewhere in this specification for cases where we are not able to preserve these invariants, for compatibility with existing web content.) [JAVASCRIPT] The reason the property descriptors are non-enumerable, despite this mismatching the same-origin behavior, is for compatibility with existing web content. See issue #3183 for details. 7.2.3.5 CrossOriginGet Receiver Let desc be ? .[[GetOwnProperty]]( ). Assert: desc is not undefined. If ! IsDataDescriptor desc ) is true, then return desc .[[Value]]. Assert: IsAccessorDescriptor desc ) is true. Let getter be desc .[[Get]]. If getter is undefined, then throw a SecurityError DOMException Return ? Call getter Receiver ). 7.2.3.6 CrossOriginSet Receiver Let desc be ? .[[GetOwnProperty]]( ). Assert: desc is not undefined. If desc .[[Set]] is present and its value is not undefined, then: Perform ? Call setter Receiver »). Return true. Throw a SecurityError DOMException 7.2.3.7 CrossOriginOwnPropertyKeys Let keys be a new empty List For each of ! CrossOriginProperties ), append .[[Property]] to keys Return the concatenation of keys and « " then ", @@toStringTag @@hasInstance @@isConcatSpreadable ». 7.3 The Window object Window Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 3+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 10.1+ Global Window Exposed Window LegacyUnenumerableNamedProperties interface Window EventTarget // the current browsing context LegacyUnforgeable readonly attribute WindowProxy window Replaceable readonly attribute WindowProxy self LegacyUnforgeable readonly attribute Document document attribute DOMString name PutForwards href LegacyUnforgeable readonly attribute Location location readonly attribute History history readonly attribute CustomElementRegistry customElements Replaceable readonly attribute BarProp locationbar Replaceable readonly attribute BarProp menubar Replaceable readonly attribute BarProp personalbar Replaceable readonly attribute BarProp scrollbars Replaceable readonly attribute BarProp statusbar Replaceable readonly attribute BarProp toolbar attribute DOMString status undefined close (); readonly attribute boolean closed undefined stop (); undefined focus (); undefined blur ();
// other browsing contexts Replaceable readonly attribute WindowProxy frames Replaceable readonly attribute unsigned long length LegacyUnforgeable readonly attribute WindowProxy top attribute any opener Replaceable readonly attribute WindowProxy parent readonly attribute Element frameElement WindowProxy open optional USVString url = "", optional DOMString target = "_blank", optional LegacyNullToEmptyString DOMString features = ""); getter object DOMString name ); // Since this is the global object, the IDL named getter adds a NamedPropertiesObject exotic // object on the prototype chain. Indeed, this does not make the global object an exotic object. // Indexed access is taken care of by the WindowProxy exotic object.
// the user agent readonly attribute Navigator navigator readonly attribute boolean originAgentCluster
// user prompts undefined alert (); undefined alert DOMString message ); boolean confirm optional DOMString message = ""); DOMString prompt optional DOMString message = "", optional DOMString default = ""); undefined (); undefined postMessage any message USVString targetOrigin optional sequence object transfer = []); undefined postMessage any message optional WindowPostMessageOptions options = {});
// also has obsolete members }; Window includes GlobalEventHandlers Window includes WindowEventHandlers dictionary WindowPostMessageOptions PostMessageOptions USVString targetOrigin = "/"; }; window window Window/window Support in all current engines. Firefox 1+ Safari 3+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ window frames Window/frames Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ window self Window/self Support in all current engines. Firefox 1+ Safari 3+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ These attributes all return window window document Window/document Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ Returns the Document associated with window document defaultView Document/defaultView Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ Returns the Window object of the active document The Window object has an associated Document , which is a Document object. It is set when the Window object is created, and only ever changed during from the initial about:blank Document The Window object's browsing context is the Window object's associated Document 's browsing context It is either null or a browsing context The window frames , and self attributes' getters must return this Window object's relevant Realm .[[GlobalEnv]]'s EnvironmentRecord 's [[GlobalThisValue]]. The document IDL attribute, on getting, must return this Window object's associated Document The Document object associated with a Window object can change in exactly one case: when the navigate algorithm creates a new Document object for the first page loaded in a browsing context . In that specific case, the Window object of the initial about:blank page is reused and gets a new Document object. The defaultView attribute's getter, when invoked, must run these steps: If this Document object's browsing context is null, then return null. Return this Document object's browsing context 's WindowProxy object. HTMLDocument Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ For historical reasons, Window objects must also have a writable, configurable, non-enumerable property named HTMLDocument whose value is the Document interface object 7.3.1 APIs for creating and navigating browsing contexts by name window window open ( [ url [, target [, features ] ] ] ) Window/open Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 3+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 10.1+ Opens a window to show url (defaults to about:blank ), and returns it. The target argument gives the name of the new window. If a window exists with that name already, it is reused. The features argument can be used to influence the rendering of the new window. window name [ = value Window/name Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ Returns the name of the window. Can be set, to change the name. window close () Window/close Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 3+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 10.1+ Closes the window. window closed Returns true if the window has been closed, false otherwise. window stop () Window/stop Support in all current engines. Firefox 1+ Safari 3+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 14+ Internet Explorer No Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ Cancels the document load. The window open steps , given a string url , a string target and a string features , are as follows: If the event loop 's termination nesting level is nonzero, return null. Let source browsing context be the entry global object 's browsing context If target is the empty string, then set target to " _blank ". Let tokenizedFeatures be the result of tokenizing features Let noopener and noreferrer be false. If tokenizedFeatures [" noopener "] exists , then: Set noopener to the result of parsing tokenizedFeatures [" noopener "] as a boolean feature Remove tokenizedFeatures [" noopener "]. If tokenizedFeatures [" noreferrer "] exists , then: Set noreferrer to the result of parsing tokenizedFeatures [" noreferrer "] as a boolean feature Remove tokenizedFeatures [" noreferrer "]. If noreferrer is true, then set noopener to true. Let target browsing context and windowType be the result of applying the rules for choosing a browsing context given target source browsing context , and noopener If there is a user agent that supports control-clicking a link to open it in a new tab, and the user control-clicks on an element whose onclick handler uses the window.open() API to open a page in an iframe element, the user agent could override the selection of the target browsing context to instead target a new tab. Let new be true if windowType is either " new and unrestricted " or " new with no opener ", and false otherwise. If target browsing context is null, then return null. If new is true, then set up browsing context features for target browsing context given tokenizedFeatures [CSSOMVIEW] Let urlRecord be the URL about:blank ". If url is not the empty string or new is true, then: If url is not the empty string, then parse url relative to the entry settings object , and set urlRecord to the resulting URL record , if any. If the parse a URL algorithm failed, then throw a SyntaxError DOMException Let request be a new request whose URL is urlRecord If noreferrer is true, then set request 's referrer to " noreferrer ". Let window be target browsing context 's active window If urlRecord is " about:blank " and new is true, then queue a global task on the networking task source given window to fire an event named load at window , with the legacy target override flag set. Otherwise: Let historyHandling be " replace " if new is true; otherwise " default ". Navigate target browsing context to request , with exceptionsEnabled set to true, historyHandling set to historyHandling , and the source browsing context set to source browsing context If noopener is true or windowType is " new with no opener ", then return null. Otherwise, if new is false, set target browsing context 's opener browsing context to source browsing context If new is true this is done as part of creating a new auxiliary browsing context Return target browsing context 's WindowProxy object. The open( url target features method on Window objects provides a mechanism for navigating an existing browsing context or opening and navigating an auxiliary browsing context When the method is invoked, the user agent must run the window open steps with url target , and features To tokenize the features argument Let tokenizedFeatures be a new ordered map Let position point at the first code point of features While position is not past the end of features Let name be the empty string. Let value be the empty string. Collect a sequence of code points that are feature separators from features given position . This skips past leading separators before the name. Collect a sequence of code points that are not feature separators from features given position . Set name to the collected characters, converted to ASCII lowercase Set name to the result of normalizing the feature name name While position is not past the end of features and the code point at position in features is not U+003D (=): If the code point at position in features is U+002C (,), or if it is not a feature separator , then break Advance position by 1. This skips to the first U+003D (=) but does not skip past a U+002C (,) or a non-separator. If the code point at position in features is a feature separator While position is not past the end of features and the code point at position in features is a feature separator If the code point at position in features is U+002C (,), then break Advance position by 1. This skips to the first non-separator but does not skip past a U+002C (,). Collect a sequence of code points that are not feature separators code points from features given position . Set value to the collected code points, converted to ASCII lowercase If name is not the empty string, then set tokenizedFeatures name ] to value Return tokenizedFeatures A code point is a feature separator if it is ASCII whitespace , U+003D (=), or U+002C (,). For legacy reasons, there are some aliases of some feature names. To normalize a feature name name , switch on name screenx Return " left ". screeny Return " top ". innerwidth Return " width ". innerheight Return " height ". Anything else Return name To parse a boolean feature given a string value If value is the empty string, then return true. If value is yes ", then return true. Let parsed be the result of parsing value as an integer If parsed is an error, then set it to 0. Return false if parsed is 0, and true otherwise. The name attribute's getter must run these steps: If this Window object's browsing context is null, then return the empty string. Return this Window object's browsing context 's name The name attribute's setter must run these steps: If this Window object's browsing context is null, then return. Set this Window object's browsing context 's name to the given value. The name gets reset when the browsing context is navigated to another origin The close() method must run these steps: Let current be this Window object's browsing context If current is null or its is closing is true, then return. If all the following are true current is script-closable the incumbent global object 's browsing context is familiar with current the incumbent global object 's browsing context is allowed to navigate current then: Set current 's is closing to true. Queue a task on the DOM manipulation task source to close current browsing context is script-closable if it is an auxiliary browsing context that was created by a script (as opposed to by an action of the user), or if it is a top-level browsing context whose session history contains only one Document The closed attribute's getter must return true if this Window object's browsing context is null or its is closing is true, and false otherwise. The stop() method must stop document loading given this Window object's associated Document 7.3.2 Accessing other browsing contexts window length Window/length Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ Returns the number of document-tree child browsing contexts window index Returns the indicated document-tree child browsing context The number of document-tree child browsing contexts of a Window object is the result of running these steps: If 's browsing context is null, then return 0. Return the number of document-tree child browsing contexts of 's browsing context The length IDL attribute's getter must return the number of document-tree child browsing contexts of this Window object. Indexed access to document-tree child browsing contexts is defined through the [[GetOwnProperty]] internal method of the WindowProxy object. 7.3.3 Named access on the Window object window name Returns the indicated element or collection of elements. As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, as new features are added to the web platform, for example. Instead of this, use document.getElementById() or document.querySelector() The document-tree child browsing context name property set of a Window object window is the return value of running these steps: If window 's browsing context is null, then return the empty list. Let childBrowsingContexts be all document-tree child browsing contexts of window 's browsing context whose browsing context name is not the empty string, in order, and including only the first document-tree child browsing context with a given name if multiple document-tree child browsing contexts have the same one. Remove each browsing context from childBrowsingContexts whose active document 's origin is not same origin with window 's relevant settings object 's origin and whose browsing context name does not match the name of its container 's name content attribute value. Return the browsing context names of childBrowsingContexts , in the same order. This means that in the following example, hosted on , assuming sets window.name to " spices ", evaluating window.spices after everything has loaded will yield undefined: iframe src > iframe iframe name spices > iframe The Window object supports named properties . The supported property names of a Window object window at any moment consist of the following, in tree order according to the element that contributed them, ignoring later duplicates: window 's document-tree child browsing context name property set the value of the name content attribute for all embed form img , and object elements that have a non-empty name content attribute and are in a document tree with window 's associated Document as their root ; and the value of the id content attribute for all HTML elements that have a non-empty id content attribute and are in a document tree with window 's associated Document as their root To determine the value of a named property name in a Window object window , the user agent must return the value obtained using the following steps: Let objects be the list of named objects of window with the name name There will be at least one such object, by definition. If objects contains a browsing context , then return the WindowProxy object of the nested browsing context of the first browsing context container in tree order whose nested browsing context is in objects Otherwise, if objects has only one element, return that element. Otherwise return an HTMLCollection rooted at window 's associated Document , whose filter matches only named objects of window with the name name . (By definition, these will all be elements.) Named objects of Window object window with the name name , for the purposes of the above algorithm, consist of the following: document-tree child browsing contexts of window 's associated Document whose name is name embed form img , or object elements that have a name content attribute whose value is name and are in a document tree with window 's associated Document as their root ; and HTML elements that have an id content attribute whose value is name and are in a document tree with window 's associated Document as their root 7.3.4 Discarding browsing contexts To discard Document document Set document 's salvageable state to false. Run any unloading document cleanup steps for document that are defined by this specification and other applicable specifications Abort document Remove any tasks associated with document in any task source , without running those tasks. Discard all the child browsing contexts of document For each session history entry entry whose document is equal to document , set entry 's document to null. Set document 's browsing context to null. Remove document from the owner set of each WorkerGlobalScope object whose set contains document For each workletGlobalScope in document 's worklet global scopes terminate workletGlobalScope To discard browsing context browsingContext , run these steps: Discard all Document objects for all the entries in browsingContext 's session history If browsingContext is a top-level browsing context , then remove browsingContext User agents may discard top-level browsing contexts at any time (typically, in response to user requests, e.g., when a user force-closes a window containing one or more top-level browsing contexts ). Other browsing contexts must be discarded once their WindowProxy object is eligible for garbage collection, in addition to the other places where this specification requires them to be discarded. 7.3.5 Closing browsing contexts To close a browsing context browsingContext , run these steps: Prompt to unload browsingContext 's active document If the user refused to allow the document to be unloaded , then return. Unload browsingContext 's active document Remove browsingContext from the user interface (e.g., close or hide its tab in a tabbed browser). Discard browsingContext User agents should offer users the ability to arbitrarily close any top-level browsing context 7.3.6 Browser interface elements To allow web pages to integrate with web browsers, certain web browser interface elements are exposed in a limited way to scripts in web pages. Each interface element is represented by a BarProp object: Exposed Window interface BarProp readonly attribute boolean visible }; window locationbar visible Window/locationbar Support in all current engines. Firefox 1+ Safari 3+ Chrome 1+ Opera 15+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 14+ Returns true if the location bar is visible; otherwise, returns false. window menubar visible Window/menubar Support in all current engines. Firefox 1+ Safari 3+ Chrome 1+ Opera 15+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 14+ Returns true if the menu bar is visible; otherwise, returns false. window personalbar visible Window/personalbar Support in all current engines. Firefox 1+ Safari 3+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ Returns true if the personal bar is visible; otherwise, returns false. window scrollbars visible Window/scrollbars Support in all current engines. Firefox 1+ Safari 3+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ Returns true if the scrollbars are visible; otherwise, returns false. window statusbar visible Window/statusbar Support in all current engines. Firefox 1+ Safari 3+ Chrome 1+ Opera 15+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 14+ Returns true if the status bar is visible; otherwise, returns false. window toolbar visible Window/toolbar Support in all current engines. Firefox 1+ Safari 3+ Chrome 1+ Opera 15+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 14+ Returns true if the toolbar is visible; otherwise, returns false. The visible attribute's getter must run these steps: If this BarProp object's relevant global object 's browsing context is null, then return false. If the user agent does not have a user interface element that the object represents, as described below, then return true. Return true or a value determined by the user agent to most accurately represent the visibility state of the user interface element that the object represents, as described below. The following BarProp objects must exist for each Window object: The location bar BarProp object Represents the user interface element that contains a control that displays the URL of the active document , or some similar interface concept. The menu bar BarProp object Represents the user interface element that contains a list of commands in menu form, or some similar interface concept. The personal bar BarProp object Represents the user interface element that contains links to the user's favorite pages, or some similar interface concept. The scrollbar BarProp object Represents the user interface element that contains a scrolling mechanism, or some similar interface concept. The status bar BarProp object Represents a user interface element found immediately below or after the document, as appropriate for the user's media, which typically provides information about ongoing network activity or information about elements that the user's pointing device is current indicating. If the user agent has no such user interface element, then the object may act as if the corresponding user interface element was absent (i.e. its visible attribute may return false). The toolbar BarProp object Represents the user interface element found immediately above or before the document, as appropriate for the user's media, which typically provides session history traversal controls (back and forward buttons, reload buttons, etc). If the user agent has no such user interface element, then the object may act as if the corresponding user interface element was absent (i.e. its visible attribute may return false). The locationbar attribute must return the location bar BarProp object The menubar attribute must return the menu bar BarProp object The personalbar attribute must return the personal bar BarProp object The scrollbars attribute must return the scrollbar BarProp object The statusbar attribute must return the status bar BarProp object The toolbar attribute must return the toolbar BarProp object For historical reasons, the status attribute on the Window object must, on getting, return the last string it was set to, and on setting, must set itself to the new value. When the Window object is created, the attribute must be set to the empty string. It does not do anything else. 7.3.7 Script settings for Window objects To set up a window environment settings object , given a URL creationURL , a JavaScript execution context execution context null or an environment reservedEnvironment , a URL topLevelCreationURL , and an origin topLevelOrigin , run these steps: Let realm be the value of execution context 's Realm component. Let window be realm 's global object Let settings object be a new environment settings object whose algorithms are defined as follows: The realm execution context Return execution context The module map Return the module map of window 's associated Document The responsible document Return window 's associated Document The API URL character encoding Return the current character encoding of window 's associated Document The API base URL Return the current base URL of window 's associated Document The origin Return the origin of window 's associated Document The policy container Return the policy container of window 's associated Document The referrer policy Let document be window 's associated Document While document is an iframe srcdoc document and document 's referrer policy is the empty string, set document to document 's browsing context 's container document Return document 's referrer policy The embedder policy Return window 's associated Document 's embedder policy The cross-origin isolated capability Return true if both of the following hold, and false otherwise: realm 's agent cluster 's cross-origin-isolation mode is " concrete ", and window 's associated Document is allowed to use the " cross-origin-isolated " feature. If reservedEnvironment is non-null, then: Set settings object 's id to reservedEnvironment 's id target browsing context to reservedEnvironment 's target browsing context , and active service worker to reservedEnvironment 's active service worker Set reservedEnvironment 's id to the empty string. The identity of the reserved environment is considered to be fully transferred to the created environment settings object . The reserved environment is not searchable by the environment ’s id from this point on. Otherwise, set settings object 's id to a new unique opaque string, settings object 's target browsing context to null, and settings object 's active service worker to null. Set settings object 's creation URL to creationURL settings object 's top-level creation URL to topLevelCreationURL , and settings object 's top-level origin to topLevelOrigin Set realm 's [[HostDefined]] field to settings object 7.4 The WindowProxy exotic object WindowProxy is an exotic object that wraps a Window ordinary object, indirecting most operations through to the wrapped object. Each browsing context has an associated WindowProxy object. When the browsing context is navigated , the Window object wrapped by the browsing context 's associated WindowProxy object is changed. The WindowProxy exotic object must use the ordinary internal methods except where it is explicitly specified otherwise below. There is no WindowProxy interface object Every WindowProxy object has a [[Window]] internal slot representing the wrapped Window object. Although WindowProxy is named as a "proxy", it does not do polymorphic dispatch on its target's internal methods as a real proxy would, due to a desire to reuse machinery between WindowProxy and Location objects. As long as the Window object remains an ordinary object this is unobservable and can be implemented either way. 7.4.1 [[GetPrototypeOf]] ( ) Let be the value of the [[Window]] internal slot of this If ! IsPlatformObjectSameOrigin ) is true, then return ! OrdinaryGetPrototypeOf ). Return null. 7.4.2 [[SetPrototypeOf]] ( Return ! SetImmutablePrototype this ). 7.4.3 [[IsExtensible]] ( ) Return true. 7.4.4 [[PreventExtensions]] ( ) Return false. 7.4.5 [[GetOwnProperty]] ( Let be the value of the [[Window]] internal slot of this If is an array index property name , then: Let index be ! ToUint32 ). Let maxProperties be the number of document-tree child browsing contexts of Let value be undefined. If maxProperties is greater than 0 and index is less than maxProperties , then set value to the WindowProxy object of the index th document-tree child browsing context of 's browsing context , sorted in the order that their browsing context container elements were most recently inserted into 's associated Document , the WindowProxy object of the most recently inserted browsing context container 's nested browsing context being last. If value is undefined, then: If ! IsPlatformObjectSameOrigin ) is true, then return undefined. Throw a SecurityError DOMException Return PropertyDescriptor [[Value]]: value [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: true }. If ! IsPlatformObjectSameOrigin ) is true, then return ! OrdinaryGetOwnProperty ). This is a willful violation of the JavaScript specification's invariants of the essential internal methods to maintain compatibility with existing web content. See tc39/ecma262 issue #672 for more information. [JAVASCRIPT] Let property be ! CrossOriginGetOwnPropertyHelper ). If property is not undefined, then return property If property is undefined and is in 's document-tree child browsing context name property set , then: Let value be the WindowProxy object of the named object of with the name Return PropertyDescriptor [[Value]]: value [[Enumerable]]: false, [[Writable]]: false, [[Configurable]]: true }. The reason the property descriptors are non-enumerable, despite this mismatching the same-origin behavior, is for compatibility with existing web content. See issue #3183 for details. Return ? CrossOriginPropertyFallback ). 7.4.6 [[DefineOwnProperty]] ( Desc Let be the value of the [[Window]] internal slot of this If ! IsPlatformObjectSameOrigin ) is true, then: If is an array index property name , return false. Return ? OrdinaryDefineOwnProperty Desc ). This is a willful violation of the JavaScript specification's invariants of the essential internal methods to maintain compatibility with existing web content. See tc39/ecma262 issue #672 for more information. [JAVASCRIPT] Throw a SecurityError DOMException 7.4.7 [[Get]] ( Receiver Let be the value of the [[Window]] internal slot of this Check if an access between two browsing contexts should be reported , given the current global object 's browsing context 's browsing context , and the current settings object If ! IsPlatformObjectSameOrigin ) is true, then return ? OrdinaryGet this Receiver ). Return ? CrossOriginGet this Receiver ). this is passed rather than as OrdinaryGet and CrossOriginGet will invoke the [[GetOwnProperty]] internal method. 7.4.8 [[Set]] ( Receiver Let be the value of the [[Window]] internal slot of this Check if an access between two browsing contexts should be reported , given the current global object 's browsing context 's browsing context and the current settings object If ! IsPlatformObjectSameOrigin ) is true, then return ? OrdinarySet this Receiver ). Return ? CrossOriginSet this Receiver ). this is passed rather than as OrdinarySet and CrossOriginSet will invoke the [[GetOwnProperty]] internal method. OrdinarySet will also invoke the [[DefineOwnProperty]] internal method. 7.4.9 [[Delete]] ( Let be the value of the [[Window]] internal slot of this If ! IsPlatformObjectSameOrigin ) is true, then: If is an array index property name , then: Let desc be ! this .[[GetOwnProperty]]( ). If desc is undefined, then return true. Return false. Return ? OrdinaryDelete ). Throw a SecurityError DOMException 7.4.10 [[OwnPropertyKeys]] ( ) Let be the value of the [[Window]] internal slot of this Let keys be a new empty List Let maxProperties be the number of document-tree child browsing contexts of Let index be 0. Repeat while index maxProperties Add ! ToString index ) as the last element of keys Increment index by 1. If ! IsPlatformObjectSameOrigin ) is true, then return the concatenation of keys and ! OrdinaryOwnPropertyKeys ). Return the concatenation of keys and ! CrossOriginOwnPropertyKeys ). 7.5 Origin Origins are the fundamental currency of the web's security model. Two actors in the web platform that share an origin are assumed to trust each other and to have the same authority. Actors with differing origins are considered potentially hostile versus each other, and are isolated from each other to varying degrees. For example, if Example Bank's web site, hosted at bank.example.com , tries to examine the DOM of Example Charity's web site, hosted at charity.example.org , a SecurityError DOMException will be raised. An origin is one of the following: An opaque origin An internal value, with no serialization it can be recreated from (it is serialized as null " per serialization of an origin ), for which the only meaningful operation is testing for equality. tuple origin tuple consists of: scheme (a scheme ). host (a host ). port (a port ). domain (null or a domain ). Null unless stated otherwise. Origins can be shared, e.g., among multiple Document objects. Furthermore, origins are generally immutable. Only the domain of a tuple origin can be changed, and only through the document.domain API. The effective domain of an origin origin is computed as follows: If origin is an opaque origin , then return null. If origin 's domain is non-null, then return origin 's domain Return origin 's host The serialization of an origin is the string obtained by applying the following algorithm to the given origin origin If origin is an opaque origin , then return " null ". Otherwise, let result be origin 's scheme Append " :// " to result Append origin 's host serialized , to result If origin 's port is non-null, append a U+003A COLON character (:), and origin 's port serialized to result Return result The serialization of (" https ", " xn--maraa-rta.example ", null, null) is " ". There used to also be a Unicode serialization of an origin . However, it was never widely adopted. Two origins and , are said to be same origin if the following algorithm returns true: If and are the same opaque origin , then return true. If and are both tuple origins and their schemes hosts , and port are identical, then return true. Return false. Two origins and , are said to be same origin-domain if the following algorithm returns true: If and are the same opaque origin , then return true. If and are both tuple origins , run these substeps: If and 's schemes are identical, and their domains are identical and non-null, then return true. Otherwise, if and are same origin and their domains are identical and null, then return true. Return false. same origin same origin-domain (" https ", " example.org ", null, null) (" https ", " example.org ", null, null) (" https ", " example.org ", 314, null) (" https ", " example.org ", 420, null) (" https ", " example.org ", 314, " example.org ") (" https ", " example.org ", 420, " example.org ") (" https ", " example.org ", null, null) (" https ", " example.org ", null, " example.org ") (" https ", " example.org ", null, " example.org ") (" http ", " example.org ", null, " example.org ") 7.5.1 Sites scheme-and-host is a tuple of a scheme and a host site is an opaque origin or a scheme-and-host To obtain a site , given an origin origin , run these steps: If origin is an opaque origin , then return origin If origin 's host 's registrable domain is null, then return ( origin 's scheme origin 's host ). Return ( origin 's scheme origin 's host 's registrable domain ). Two origins and , are said to be schemelessly same site if the following algorithm returns true: If and are the same opaque origin , then return true. If and are both tuple origins , then: Let hostA be 's host , and let hostB be 's host If hostA equals hostB and hostA 's registrable domain is null, then return true. If hostA 's registrable domain equals hostB 's registrable domain and is non-null, then return true. Return false. Two origins and , are said to be same site if both of the following statements are true: and are schemelessly same site and are either both opaque origins , or both tuple origins with the same scheme Unlike the same origin and same origin-domain concepts, for schemelessly same site and same site , the port and domain components are ignored. For the reasons explained in URL , the same site and schemelessly same site concepts should be avoided when possible, in favor of same origin checks. Given that wildlife.museum museum , and com are public suffixes and that example.com is not: schemelessly same site same site (" https ", " example.com ") (" https ", " sub.example.com ") (" https ", " example.com ") (" https ", " sub.other.example.com ") (" https ", " example.com ") (" http ", " non-secure.example.com ") (" https ", " r.wildlife.museum ") (" https ", " sub.r.wildlife.museum ") (" https ", " r.wildlife.museum ") (" https ", " sub.other.r.wildlife.museum ") (" https ", " r.wildlife.museum ") (" https ", " other.wildlife.museum ") (" https ", " r.wildlife.museum ") (" https ", " wildlife.museum ") (" https ", " wildlife.museum ") (" https ", " wildlife.museum ") (Here we have omitted the port and domain components since they are not considered.) 7.5.2 Relaxing the same-origin restriction Document/domain Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ document domain [ = domain Returns the current domain used for security checks. Can be set to a value that removes subdomains, to change the origin 's domain to allow pages on other subdomains of the same domain (if they do the same thing) to access each other. This enables pages on different hosts of a domain to synchronously access each other's DOMs. In sandboxed iframe s, Document s with opaque origins Document s without a browsing context , and when the " document-domain " feature is disabled, the setter will throw a SecurityError exception. In cases where crossOriginIsolated or originAgentCluster return true, the setter will do nothing. Avoid using the document.domain setter. It undermines the security protections provided by the same-origin policy. This is especially acute when using shared hosting; for example, if an untrusted third party is able to host an HTTP server at the same IP address but on a different port, then the same-origin protection that normally protects two different sites on the same host will fail, as the ports are ignored when comparing origins after the document.domain setter has been used. Because of these security pitfalls, this feature is in the process of being removed from the web platform. (This is a long process that takes many years.) Instead, use postMessage() or MessageChannel objects to communicate across origins in a safe manner. The domain getter steps are: Let effectiveDomain be this 's origin 's effective domain If effectiveDomain is null, then return the empty string. Return effectiveDomain serialized The domain setter steps are: If this 's browsing context is null, then throw a SecurityError DOMException If this 's active sandboxing flag set has its sandboxed document.domain browsing context flag set, then throw a SecurityError DOMException If this is not allowed to use the " document-domain " feature, then throw a SecurityError DOMException Let effectiveDomain be this 's origin 's effective domain If effectiveDomain is null, then throw a SecurityError DOMException If the given value is not a registrable domain suffix of and is not equal to effectiveDomain , then throw SecurityError DOMException If the surrounding agent 's agent cluster 's is origin-keyed is true, then return. Set this 's origin 's domain to the result of parsing the given value. To determine if a string hostSuffixString is a registrable domain suffix of or is equal to host originalHost , run these steps: If hostSuffixString is the empty string, then return false. Let host be the result of parsing hostSuffixString If host is failure, then return false. If host does not equal originalHost then: If host or originalHost is not a domain , then return false. This excludes hosts that are an IPv4 address or an IPv6 address If host , prefixed by a U+002E FULL STOP (.), does not exactly match the end of originalHost , then return false. If host equals host 's public suffix , then return false. [URL] Return true. 7.5.3 Origin-keyed agent clusters window . originAgentCluster Returns true if this Window belongs to an agent cluster which is origin keyed , in the manner described in this section. Document delivered over a secure context can request that it be placed in an origin keyed agent cluster , by using the ` Origin-Agent-Cluster ` HTTP response header. This header is a structured header whose value must be a boolean [STRUCTURED-FIELDS] Per the processing model in the create and initialize a new Document object , valuesValues that are not the structured header boolean true value (i.e., ` ?1 `) will be ignored. The consequences of using this header are that the resulting Document 's agent cluster key is its origin , instead of the corresponding site . In terms of observable effects, this means that attempting to relax the same-origin restriction using document.domain will instead do nothing, and it will not be possible to send WebAssembly.Module objects to cross-origin Document (even if they are same site ). Behind the scenes, this isolation can allow user agents to allocate implementation-specific resources corresponding to agent clusters , such as processes or threads, more efficiently. Note that within a browsing context group , the ` Origin-Agent-Cluster ` header can never cause same-origin Document objects to end up in different agent clusters , even if one sends the header and the other doesn't. This is prevented by means of the historical agent cluster key map This means that the originAgentCluster getter can return false, even if the header is set, if the header was omitted on a previously-loaded same-origin page in the same browsing context group . Similarly, it can return true even when the header is not set. The originAgentCluster getter steps are to return the surrounding agent 's agent cluster 's is origin-keyed Document s with an opaque origin can be considered unconditionally origin-keyed; for them the header has no effect, and the originAgentCluster getter will always return true. Similarly, Document s whose agent cluster 's cross-origin isolation mode is not none " are automatically origin-keyed. The Origin-Agent-Cluster ` header might be useful as an additional hint to implementations about resource allocation, since the ` Cross-Origin-Opener-Policy ` and Cross-Origin-Embedder-Policy ` headers used to achieve cross-origin isolation are more about ensuring that everything in the same address space opts in to being there. But adding it would have no additional observable effects on author code. 7.6 Sandboxing sandboxing flag set is a set of zero or more of the following flags, which are used to restrict the abilities that potentially untrusted resources have: The sandboxed navigation browsing context flag This flag prevents content from navigating browsing contexts other than the sandboxed browsing context itself (or browsing contexts further nested inside it), auxiliary browsing contexts (which are protected by the sandboxed auxiliary navigation browsing context flag defined next), and the top-level browsing context (which is protected by the sandboxed top-level navigation without user activation browsing context flag and sandboxed top-level navigation with user activation browsing context flag defined below). If the sandboxed auxiliary navigation browsing context flag is not set, then in certain cases the restrictions nonetheless allow popups (new top-level browsing contexts ) to be opened. These browsing contexts always have one permitted sandboxed navigator , set when the browsing context is created, which allows the browsing context that created them to actually navigate them. (Otherwise, the sandboxed navigation browsing context flag would prevent them from being navigated even if they were opened.) The sandboxed auxiliary navigation browsing context flag This flag prevents content from creating new auxiliary browsing contexts , e.g. using the target attribute or the window.open() method. The sandboxed top-level navigation without user activation browsing context flag This flag prevents content from navigating their top-level browsing context and prevents content from closing their top-level browsing context . It is consulted only when the sandboxed browsing context's active window does not have transient activation When the sandboxed top-level navigation without user activation browsing context flag is not set, content can navigate its top-level browsing context , but other browsing contexts are still protected by the sandboxed navigation browsing context flag and possibly the sandboxed auxiliary navigation browsing context flag The sandboxed top-level navigation with user activation browsing context flag This flag prevents content from navigating their top-level browsing context and prevents content from closing their top-level browsing context . It is consulted only when the sandboxed browsing context's active window has transient activation As with the sandboxed top-level navigation without user activation browsing context flag , this flag only affects the top-level browsing context ; if it is not set, other browsing contexts might still be protected by other flags. The sandboxed plugins browsing context flag This flag prevents content from instantiating plugins whether using the embed element the object element , or through of their nested browsing context unless those plugins can be secured The sandboxed origin browsing context flag This flag forces content into a unique origin , thus preventing it from accessing other content from the same origin This flag also prevents script from reading from or writing to the document.cookie IDL attribute , and blocks access to localStorage The sandboxed forms browsing context flag This flag blocks form submission The sandboxed pointer lock browsing context flag This flag disables the Pointer Lock API. [POINTERLOCK] The sandboxed scripts browsing context flag This flag blocks script execution The sandboxed automatic features browsing context flag This flag blocks features that trigger automatically, such as automatically playing a video or automatically focusing a form control The sandboxed document.domain browsing context flag This flag prevents content from using the document.domain setter. The sandbox propagates to auxiliary browsing contexts flag This flag prevents content from escaping the sandbox by ensuring that any auxiliary browsing context it creates inherits the content's active sandboxing flag set The sandboxed modals flag This flag prevents content from using any of the following features to produce modal dialogs: window.alert() window.confirm() window.print() window.prompt() the beforeunload event The sandboxed orientation lock browsing context flag This flag disables the ability to lock the screen orientation. [SCREENORIENTATION] The sandboxed presentation browsing context flag This flag disables the Presentation API. [PRESENTATION] The sandboxed downloads browsing context flag This flag prevents content from initiating or instantiating downloads, whether through downloading hyperlinks or through that gets handled as a When the user agent is to parse a sandboxing directive , given a string input , a sandboxing flag set output , it must run the following steps: Split input on ASCII whitespace , to obtain tokens Let output be empty. Add the following flags to output The sandboxed navigation browsing context flag The sandboxed auxiliary navigation browsing context flag , unless tokens contains the allow-popups keyword. The sandboxed top-level navigation without user activation browsing context flag , unless tokens contains the allow-top-navigation keyword. The sandboxed top-level navigation with user activation browsing context flag , unless tokens contains either the allow-top-navigation-by-user-activation keyword or the allow-top-navigation keyword. This means that if the allow-top-navigation is present, the allow-top-navigation-by-user-activation keyword will have no effect. For this reason, specifying both is a document conformance error. The sandboxed plugins browsing context flag The sandboxed origin browsing context flag , unless the tokens contains the allow-same-origin keyword. The allow-same-origin keyword is intended for two cases. First, it can be used to allow content from the same site to be sandboxed to disable scripting, while still allowing access to the DOM of the sandboxed content. Second, it can be used to embed content from a third-party site, sandboxed to prevent that site from opening popups, etc, without preventing the embedded page from communicating back to its originating site, using the database APIs to store data, etc. The sandboxed forms browsing context flag , unless tokens contains the allow-forms keyword. The sandboxed pointer lock browsing context flag , unless tokens contains the allow-pointer-lock keyword. The sandboxed scripts browsing context flag , unless tokens contains the allow-scripts keyword. The sandboxed automatic features browsing context flag , unless tokens contains the allow-scripts keyword (defined above). This flag is relaxed by the same keyword as scripts, because when scripts are enabled these features are trivially possible anyway, and it would be unfortunate to force authors to use script to do them when sandboxed rather than allowing them to use the declarative features. The sandboxed document.domain browsing context flag The sandbox propagates to auxiliary browsing contexts flag , unless tokens contains the allow-popups-to-escape-sandbox keyword. The sandboxed modals flag , unless tokens contains the allow-modals keyword. The sandboxed orientation lock browsing context flag , unless tokens contains the allow-orientation-lock keyword. The sandboxed presentation browsing context flag , unless tokens contains the allow-presentation keyword. The sandboxed downloads browsing context flag , unless tokens contains the allow-downloads keyword. Every top-level browsing context has a popup sandboxing flag set , which is a sandboxing flag set . When a browsing context is created, its popup sandboxing flag set must be empty. It is populated by the rules for choosing a browsing context and the obtain a browsing context to use for a navigation response algorithm. Every iframe element has an iframe sandboxing flag set which is a sandboxing flag set . Which flags in an iframe sandboxing flag set are set at any particular time is determined by the iframe element's sandbox attribute. Every Document has an active sandboxing flag set which is a sandboxing flag set . When the Document is created, its active sandboxing flag set must be empty. It is populated by the navigation algorithm Every resource that is obtained by the navigation algorithm has forced sandboxing flag set , which is a sandboxing flag set . A resource by default has no flags set in its forced sandboxing flag set , but other specifications can define that certain flags are set. In particular, the forced sandboxing flag set is used by Content Security Policy [CSP] To determine the creation sandboxing flags for a browsing context browsing context , given null or an element embedder , return the union of the flags that are present in the following sandboxing flag sets If embedder is null, then: the flags set on browsing context 's popup sandboxing flag set If embedder is an element, then: the flags set on embedder 's iframe sandboxing flag set If embedder is an element, then: the flags set on embedder 's node document 's active sandboxing flag set After creation, the sandboxing flags for a browsing context browsing context are the result of determining the creation sandboxing flags given browsing context and browsing context 's container 7.7 Cross-origin opener policies cross-origin opener policy value allows a document which is navigated to in a top-level browsing context to force the creation of a new top-level browsing context , and a corresponding group . The possible values are: unsafe-none This is the (current) default and means that the document will occupy the same top-level browsing context as its predecessor, unless that document specified a different cross-origin opener policy same-origin-allow-popups This forces the creation of a new top-level browsing context for the document, unless its predecessor specified the same cross-origin opener policy and they are same origin same-origin This behaves the same as " same-origin-allow-popups ", with the addition that any auxiliary browsing context created needs to contain same origin documents that also have the same cross-origin opener policy or it will appear closed to the opener. same-origin-plus-COEP This behaves the same as " same-origin ", with the addition that it sets the (new) top-level browsing context 's group 's cross-origin isolation mode to one of " logical " or " concrete ". same-origin-plus-COEP " cannot be directly set via the ` Cross-Origin-Opener-Policy ` header, but results from a combination of setting both ` Cross-Origin-Opener-Policy same-origin ` and ` Cross-Origin-Embedder-Policy : require-corp ` together. cross-origin opener policy consists of: value , which is a cross-origin opener policy value , initially " unsafe-none ". reporting endpoint , which is string or null, initially null. report-only value , which is a cross-origin opener policy value , initially unsafe-none ". report-only reporting endpoint which is a string or null, initially null. To match cross-origin opener policy values , given a cross-origin opener policy value , an origin originA , a cross-origin opener policy value , and an origin originB If is " unsafe-none " and is " unsafe-none ", then return true. If is " unsafe-none " or is unsafe-none ", then return false. If is and originA is same origin with originB , then return true. Return false. 7.7.1 The headers Headers/Cross-Origin-Opener-Policy Firefox 79+ Safari No Chrome 83+ Opera No Edge 83+ Edge (Legacy) No Internet Explorer No Firefox Android 79+ Safari iOS No Chrome Android 83+ WebView Android No Samsung Internet No Opera Android No Document 's cross-origin opener policy is derived from the ` Cross-Origin-Opener-Policy ` and the ` Cross-Origin-Opener-Policy-Report-Only HTTP response headers. These headers are structured headers whose value must be a token [STRUCTURED-FIELDS] The valid token values are the opener policy values . The token may also have attached parameters ; of these, the " report-to " parameter can have a valid URL string identifying an appropriate reporting endpoint. [REPORTING] Per the processing model described below, user agents will ignore this header if it contains an invalid value. Likewise, user agents will ignore this header if the value cannot be parsed as a token To obtain a cross-origin opener policy given a response response and an environment reservedEnvironment Let policy be a new cross-origin opener policy If reservedEnvironment is a non-secure context , then return policy Let value be the result of getting a structured field value given Cross-Origin-Opener-Policy ` and " item " from response 's header list If parsedItem is not null, then: If parsedItem [0] is " same-origin ", then: Let coep be the result of obtaining a cross-origin embedder policy from response and reservedEnvironment If coep 's value is " require-corp ", then set policy 's value to " same-origin-plus-COEP ". Otherwise, set policy 's value to " same-origin ". If parsedItem [0] is " same-origin-allow-popups ", then set policy 's value to " same-origin-allow-popups ". If parsedItem [1][" report-to "] exists and it is a string, then set policy 's reporting endpoint to parsedItem [1][" report-to "]. Set parsedItem to the result of getting a structured field value given ` Cross-Origin-Opener-Policy-Report-Only ` and item " from response 's header list If parsedItem is not null, then: If parsedItem [0] is " same-origin ", then: Let coep be the result of obtaining a cross-origin embedder policy from response and reservedEnvironment If coep 's value is " require-corp " or coep 's report-only value is " require-corp ", then set policy 's report-only value to " same-origin-plus-COEP ". Report only COOP also considers report-only COEP to assign the special same-origin-plus-COEP " value. This allows developers more freedom in the order of deployment of COOP and COEP. Otherwise, set policy 's report-only value to " same-origin ". If parsedItem [0] is " same-origin-allow-popups ", then set policy 's report-only value to same-origin-allow-popups ". If parsedItem [1][" report-to "] exists and it is a string, then set policy 's report-only reporting endpoint to parsedItem [1][" report-to "]. Return policy 7.7.2 Browsing context group switches due to cross-origin opener policy To check if COOP values require a browsing context group switch , given a boolean isInitialAboutBlank , two origins responseOrigin activeDocumentNavigationOrigin , and two cross-origin opener policy values responseCOOPValue and activeDocumentCOOPValue If the result of matching activeDocumentCOOPValue activeDocumentNavigationOrigin responseCOOPValue , and responseOrigin is true, return false. If all of the following are true: isInitialAboutBlank activeDocumentCOOPValue 's value is same-origin-allow-popups ". responseCOOPValue is " unsafe-none ", then return false. Return true. To check if enforcing report-only COOP would require a browsing context group switch , given a boolean isInitialAboutBlank , two origins responseOrigin activeDocumentNavigationOrigin , and two cross-origin opener policies responseCOOP and activeDocumentCOOP If the result of checking if COOP values require a browsing context group switch given isInitialAboutBlank responseOrigin activeDocumentNavigationOrigin responseCOOP 's report-only value and activeDocumentCOOPReportOnly 's report-only value is false, then return false. Matching report-only policies allows a website to specify the same report-only cross-origin opener policy on all its pages and not receive violation reports for navigations between these pages. If the result of checking if COOP values require a browsing context group switch given isInitialAboutBlank responseOrigin activeDocumentNavigationOrigin responseCOOP 's value and activeDocumentCOOPReportOnly 's report-only value is true, then return true. If the result of checking if COOP values require a browsing context group switch given isInitialAboutBlank responseOrigin activeDocumentNavigationOrigin responseCOOP 's report-only value and activeDocumentCOOPReportOnly 's value is true, then return true. Return false. cross-origin opener policy enforcement result is struct with the following items A boolean needs a browsing context group switch , initially false. A boolean would need a browsing context group switch due to report-only , initially false. URL url An origin current origin cross-origin opener policy cross-origin opener policy A boolean current context is navigation source To enforce a response's cross-origin opener policy , given a browsing context browsingContext , a URL responseURL , an origin responseOrigin , a cross-origin opener policy responseCOOP , a cross-origin opener policy enforcement result currentCOOPEnforcementResult , and a referrer referrer Let newCOOPEnforcementResult be a new cross-origin opener policy enforcement result whose needs a browsing context group switch is currentCOOPEnforcementResult 's needs a browsing context group switch would need a browsing context group switch due to report-only is currentCOOPEnforcementResult 's would need a browsing context group switch due to report-only url is responseURL origin is responseOrigin coop is responseCOOP , and current context is navigation source is true. Let isInitialAboutBlank be true if browsingContext is still on its initial about:blank Document ; otherwise, false. If isInitialAboutBlank is true and browsingContext 's initial URL is null, set browsingContext 's initial URL to responseURL If the result of checking if COOP values require a browsing context group switch given isInitialAboutBlank currentCOOPEnforcementResult 's cross-origin opener policy 's value currentCOOPEnforcementResult 's origin responseCOOP 's value , and responseOrigin is true, then: Set newCOOPEnforcementResult 's needs a browsing context group switch to true. If browsingContext 's group 's browsing context set 's size is greater than 1, then: Queue a violation report for browsing context group switch when navigating to a COOP response with responseCOOP enforce ", responseURL currentCOOPEnforcementResult 's url currentCOOPEnforcementResult 's origin responseOrigin , and referrer Queue a violation report for browsing context group switch when navigating away from a COOP response with activeDocumentCOOP , " enforce ", currentCOOPEnforcementResult 's url responseURL currentCOOPEnforcementResult 's origin responseOrigin , and currentCOOPEnforcementResult 's current context is navigation source If the result of checking if enforcing report-only COOP would require a browsing context group switch given isInitialAboutBlank responseOrigin currentCOOPEnforcementResult 's origin responseCOOP , and currentCOOPEnforcementResult 's cross-origin opener policy , is true, then: Set result 's would need a browsing context group switch due to report-only to true. If browsingContext 's group 's browsing context set 's size is greater than 1, then: Queue a violation report for browsing context group switch when navigating to a COOP response with responseCOOP , " reporting ", responseURL currentCOOPEnforcementResult 's url currentCOOPEnforcementResult 's origin responseOrigin , and referrer Queue a violation report for browsing context group switch when navigating away from a COOP response with activeDocumentCOOP , " reporting ", currentCOOPEnforcementResult 's url responseURL currentCOOPEnforcementResult 's origin responseOrigin , and currentCOOPEnforcementResult 's current context is navigation source Return newCOOPEnforcementResult To obtain a browsing context to use for a navigation response , given a browsing contexts browsingContext , a sandboxing flag set sandboxFlags , a cross-origin opener policy navigationCOOP , and a cross-origin opener policy enforcement result coopEnforcementResult Assert: browsingContext is a top-level browsing context If coopEnforcementResult 's needs a browsing context group switch is false, then: If coopEnforcementResult 's would need a browsing context group switch due to report-only is true, set browsing context 's virtual browsing context group ID to a new unique identifier. Return browsingContext Let newBrowsingContext be the result of creating a new top-level browsing context If navigationCOOP 's value is " same-origin-plus-COEP ", then set newBrowsingContext 's group 's cross-origin isolation mode to either " logical " or " concrete ". The choice of which is implementation-defined It is difficult on some platforms to provide the security properties required by the cross-origin isolated capability . " concrete grants access to it and " logical " does not. If sandboxFlags is not empty, then: Assert navigationCOOP 's value is unsafe-none ". Assert: newBrowsingContext 's popup sandboxing flag set is empty Set newBrowsingContext 's popup sandboxing flag set to clone of sandboxFlags Discard browsingContext This has no effect on browsingContext 's group , unless browsingContext was its sole top-level browsing context . In that case, the user agent might delete the browsing context group which no longer contains any browsing contexts Return newBrowsingContext The impact of swapping browsing context groups following a navigation is not fully defined. It is currently under discussion in issue #5350 7.7.3 Reporting An accessor-accessed relationship is an enum that describes the relationship between two browsing contexts between which an access happened. It can take the following values: accessor is opener The accessor browsing context or one of its ancestors is the opener browsing context of the accessed browsing context 's top-level browsing context accessor is openee The accessed browsing context or one of its ancestors is the opener browsing context of the accessor browsing context 's top-level browsing context none There is no opener relationship between the accessor browsing context , the accessor browsing context , or any of their ancestors To check if an access between two browsing contexts should be reported , given two browsing contexts accessor and accessed , a JavaScript property name , and an environment settings object environment If is not a cross-origin accessible window property name , then return. If accessor 's active document 's origin or any of its ancestors active document 's origins are not same origin with accessor 's top-level browsing context 's active document 's origin , or if accessed 's active document 's origin or any of its ancestors active document 's origins are not same origin with accessed 's top-level browsing context 's active document 's origin , then return. This avoids leaking information about cross-origin iframes to a top level frame with cross-origin opener policy reporting If accessor 's top-level browsing context 's virtual browsing context group ID is accessed 's top-level browsing context 's virtual browsing context group ID , then return. Let accessorAccessedRelationship be a new accessor-accessed relationship with value none If accessed 's top-level browsing context 's opener browsing context is accessor or an ancestor of accessor , then set accessorAccessedRelationship to accessor is opener If accessor 's top-level browsing context 's opener browsing context is accessed or an ancestor of accessed , then set accessorAccessedRelationship to accessor is openee Queue violation reports for accesses , given accessorAccessedRelationship accessor 's top-level browsing context 's active document 's cross-origin opener policy accessed 's top-level browsing context 's active document 's cross-origin opener policy accessor 's active document 's URL accessed 's active document 's URL accessor 's top-level browsing context 's initial URL accessed 's top-level browsing context 's initial URL accessor 's active document 's origin accessed 's active document 's origin accessor 's top-level browsing context 's opener origin at creation accessed 's top-level browsing context 's opener origin at creation accessor 's top-level browsing context 's active document 's referrer accessed 's top-level browsing context 's active document 's referrer , and environment To sanitize a URL to send in a report given a URL url Let sanitizedURL be a copy of url Set the username given sanitizedURL and the empty string. Set the password given sanitizedURL and the empty string. Return the serialization of sanitizedURL with exclude fragment set to true. To queue a violation report for browsing context group switch when navigating to a COOP response given a cross-origin opener policy coop , a string disposition , a URL coopURL , a URL previousResponseURL , two origins coopOrigin and previousResponseOrigin , and a referrer referrer If coop 's reporting endpoint is null, return. Let coopValue be coop 's value If disposition is " reporting ", then set coopValue to coop 's report-only value Let serializedReferrer be an empty string If referrer is a URL , set serializedReferrer to the serialization of referrer Let body be a new object containing the following properties: key value disposition disposition effectivePolicy coopValue previousResponseURL If coopOrigin and previousResponseOrigin are same origin this is the sanitization of previousResponseURL , null otherwise. referrer serializedReferrer type navigation-to-response Queue body as " coop for coop 's reporting endpoint with coopURL To queue a violation report for browsing context group switch when navigating away from a COOP response given a cross-origin opener policy coop , a string disposition , a URL coopURL , a URL nextResponseURL , two origins coopOrigin and nextResponseOrigin , and a boolean isCOOPResponseNavigationSource If coop 's reporting endpoint is null, return. Let coopValue be coop 's value If disposition is " reporting ", then set coopValue to coop 's report-only value Let body be a new object containing the following properties: key value disposition disposition effectivePolicy coopValue nextResponseURL If coopOrigin and nextResponseOrigin are same origin or isCOOPResponseNavigationSource is true, this is the sanitization of previousResponseURL , null otherwise. type navigation-to-response Queue body as " coop for coop 's reporting endpoint with coopURL To queue violation reports for accesses , given an accessor-accessed relationship accessorAccessedRelationship , two cross-origin opener policies accessorCOOP and accessedCOOP , four URLs accessorURL accessedURL accessorInitialURL accessedInitialURL , four origins accessorOrigin accessedOrigin accessorCreatorOrigin and accessedCreatorOrigin , two referrers accessorReferrer and accessedReferrer , a string propertyName , and an environment settings object environment If coop 's reporting endpoint is null, return. Let coopValue be coop 's value If disposition is " reporting ", then set coopValue to coop 's report-only value If accessorAccessedRelationship is accessor is opener Queue a violation report for access to an opened window , given accessorCOOP accessorURL accessedURL accessedInitialURL accessorOrigin accessedOrigin accessedCreatorOrigin propertyName and environment Queue a violation report for access from the opener , given accessedCOOP accessedURL accessorURL accessedOrigin accessorOrigin propertyName , and accessedReferrer Otherwise, if accessorAccessedRelationship is accessor is openee Queue a violation report for access to the opener , given accessorCOOP accessorURL accessedURL accessorOrigin accessedOrigin propertyName accessorReferrer , and environment Queue a violation report for access from an opened window , given accessedCOOP accessedURL accessorURL accessorInitialURL accessedOrigin accessorOrigin accessorCreatorOrigin , and propertyName Otherwise: Queue a violation report for access to another window , given accessorCOOP accessorURL accessedURL accessorOrigin accessedOrigin propertyName , and environment Queue a violation report for access from another window , given accessedCOOP accessedURL accessorURL accessedOrigin accessorOrigin , and propertyName To queue a violation report for access to the opener , given a cross-origin opener policy coop , two URLs coopURL and openerURL , two origins coopOrigin and openerOrigin , a string propertyName , a referrer referrer , and an environment settings object environment Let sourceFile lineNumber and columnNumber be the relevant script URL and problematic position which triggered this report. Let serializedReferrer be an empty string If referrer is a URL , set serializedReferrer to the serialization of referrer Let body be a new object containing the following properties: key value disposition reporting effectivePolicy coop 's report-only value property propertyName openerURL If coopOrigin and openerOrigin are same origin , this is the sanitization of openerURL , null otherwise. referrer serializedReferrer sourceFile sourceFile lineNumber lineNumber columnNumber columnNumber type access-to-opener Queue body as " coop for coop 's reporting endpoint with coopURL and environment To queue a violation report for access to an opened window , given a cross-origin opener policy coop , three URLs coopURL openedWindowURL and initialWindowURL , three origins coopOrigin openedWindowOrigin , and openerInitialOrigin , a string propertyName , and an environment settings object environment Let sourceFile lineNumber and columnNumber be the relevant script URL and problematic position which triggered this report. Let body be a new object containing the following properties: key value disposition reporting effectivePolicy coop 's report-only value property propertyName openedWindowURL If coopOrigin and openedWindowOrigin are same origin , this is the sanitization of openedWindowURL null otherwise. openedWindowInitialURL If coopOrigin and openerInitialOrigin are same origin this is the sanitization of initialWindowURL , null otherwise. sourceFile sourceFile lineNumber lineNumber columnNumber columnNumber type access-to-opener Queue body as " coop for coop 's reporting endpoint with coopURL and environment To queue a violation report for access to another window , given a cross-origin opener policy coop , two URLs coopURL and otherURL , two origins coopOrigin and otherOrigin , a string propertyName , and an environment settings object environment Let sourceFile lineNumber and columnNumber be the relevant script URL and problematic position which triggered this report. Let body be a new object containing the following properties: key value disposition reporting effectivePolicy coop 's report-only value property propertyName otherURL If coopOrigin and otherOrigin are same origin , this is the sanitization of otherURL , null otherwise. sourceFile sourceFile lineNumber lineNumber columnNumber columnNumber type access-to-opener Queue body as " coop for coop 's reporting endpoint with coopURL and environment To queue a violation report for access from the opener , given a cross-origin opener policy coop , two URLs coopURL and openerURL , two origins coopOrigin and openerOrigin , a string propertyName , and a referrer referrer If coop 's reporting endpoint is null, return. Let serializedReferrer be an empty string If referrer is a URL , set serializedReferrer to the serialization of referrer Let body be a new object containing the following properties: key value disposition reporting effectivePolicy coop 's report-only value property propertyName openerURL If coopOrigin and openerOrigin are same origin , this is the sanitization of openerURL , null otherwise. referrer serializedReferrer type access-to-opener Queue body as " coop for coop 's reporting endpoint with coopURL To queue a violation report for access from an opened window , given a cross-origin opener policy coop , three URLs coopURL openedWindowURL and initialWindowURL , three origins coopOrigin openedWindowOrigin , and openerInitialOrigin , and a string propertyName If coop 's reporting endpoint is null, return. Let body be a new object containing the following properties: key value disposition reporting effectivePolicy coopValue property coop 's report-only value openedWindowURL If coopOrigin and openedWindowOrigin are same origin , this is the sanitization of openedWindowURL null otherwise. openedWindowInitialURL If coopOrigin and openerInitialOrigin are same origin this is the sanitization of initialWindowURL , null otherwise. type access-to-opener Queue body as " coop for coop 's reporting endpoint with coopURL To queue a violation report for access from another window , given a cross-origin opener policy coop , two URLs coopURL and otherURL , two origins coopOrigin and otherOrigin , and a string propertyName If coop 's reporting endpoint is null, return. Let body be a new object containing the following properties: key value disposition reporting effectivePolicy coop 's report-only value property propertyName otherURL If coopOrigin and otherOrigin are same origin , this is the sanitization of otherURL , null otherwise. type access-to-opener Queue body as " coop for coop 's reporting endpoint with coopURL 7.8 Cross-origin embedder policies Headers/Cross-Origin-Embedder-Policy Firefox 79+ Safari No Chrome 83+ Opera No Edge 83+ Edge (Legacy) No Internet Explorer No Firefox Android 79+ Safari iOS No Chrome Android 83+ WebView Android No Samsung Internet No Opera Android No An embedder policy value controls the fetching of cross-origin resources without explicit permission from resource owners. There are two such values: unsafe-none This is the default value. When this value is used, cross-origin resources can be fetched without giving explicit permission through the CORS protocol or the Cross-Origin-Resource-Policy ` header. require-corp When this value is used, fetching cross-origin resources requires the server's explicit permission through the CORS protocol or the Cross-Origin-Resource-Policy ` header. An embedder policy consists of: value , which is an embedder policy value , initially " unsafe-none ". reporting endpoint string, initially the empty string. report only value , which is an embedder policy value , initially unsafe-none ". report only reporting endpoint string, initially the empty string. The coep " report type is a report type whose value is " coep ". It is visible to ReportingObserver 7.8.1 The headers The ` Cross-Origin-Embedder-Policy ` and Cross-Origin-Embedder-Policy-Report-Only ` HTTP response header fields allow a server to declare an embedder policy for an environment settings object . These headers are structured headers whose values must be token [STRUCTURED-FIELDS] The valid token values are the embedder policy values . The token may also have attached parameters ; of these, the " report-to " parameter can have a valid URL string identifying an appropriate reporting endpoint. [REPORTING] The processing model fails open (by defaulting to " unsafe-none ") in the presence of a header that cannot be parsed as a token. This includes inadvertent lists created by combining multiple instances of the ` Cross-Origin-Embedder-Policy ` header present in a given response: Cross-Origin-Embedder-Policy Final embedder policy value No header delivered unsafe-none require-corp require-corp unknown-value unsafe-none require-corp, unknown-value unsafe-none unknown-value, unknown-value unsafe-none unknown-value, require-corp unsafe-none require-corp, require-corp unsafe-none (The same applies to ` Cross-Origin-Embedder-Policy-Report-Only `.) To obtain an embedder policy from a response response and an environment environment Let policy be a new embedder policy If environment is a non-secure context , then return policy Let parsedItem be the result of getting a structured field value with ` Cross-Origin-Embedder-Policy ` and " item " from response 's header list If parsedItem is non-null and parsedItem [0] is " require-corp ": Set policy 's value to " require-corp ". If parsedItem [1][" report-to "] exists , then set policy 's endpoint to parsedItem [1][" report-to "]. Set parsedItem to the result of getting a structured field value with ` Cross-Origin-Embedder-Policy-Report-Only ` and " item from response 's header list If parsedItem is non-null and parsedItem [0] is " require-corp ": Set policy 's report-only value to " require-corp ". If parsedItem [1][" report-to "] exists , then set policy 's report-only reporting endpoint to parsedItem [1][" report-to "]. Return policy 7.8.2 Embedder policy checks To check a navigation response's adherence to its embedder policy given a response response , a browsing context target , and an environment environment If target is not a child browsing context , then return true. Let responsePolicy be the result of obtaining an embedder policy from response and environment Let parentPolicy be target 's container document 's embedder policy If parentPolicy 's report-only value is " require-corp " and responsePolicy 's value is " unsafe-none ", then queue a cross-origin embedder policy inheritance violation with response , " ", parentPolicy 's report only reporting endpoint , " reporting ", and target 's container document 's relevant settings object If parentPolicy 's value is " unsafe-none " or responsePolicy 's value is " require-corp ", then return true. Queue a cross-origin embedder policy inheritance violation with response , " ", parentPolicy 's reporting endpoint enforce ", and target 's container document 's relevant settings object Return false. To check a global object's embedder policy given a WorkerGlobalScope workerGlobalScope , an environment settings object owner , and response response If workerGlobalScope is not a DedicatedWorkerGlobalScope object, then return true. Let policy be workerGlobalScope 's embedder policy Let ownerPolicy be owner 's embedder policy If ownerPolicy 's report-only value is " require-corp " and policy 's value is " unsafe-none ", then queue a cross-origin embedder policy inheritance violation with response , " worker initialization ", owner's policy 's report only reporting endpoint reporting ", and owner If ownerPolicy 's value is " unsafe-none " or policy 's value is " require-corp ", then return true. Queue a cross-origin embedder policy inheritance violation with response , " worker initialization ", owner's policy 's reporting endpoint enforce ", and owner Return false. To queue a cross-origin embedder policy inheritance violation given a response response , a string type , a string endpoint , a string disposition , and an environment settings object settings Let serialized be the result of serializing a response URL for reporting with response Let body be a new object containing the following properties: key value type type blockedURL serialized disposition disposition Queue body as the coep " report type for endpoint on settings 7.9 Policy containers policy container is a struct containing policies that apply to Document , a WorkerGlobalScope , or a WorkletGlobalScope It has the following items CSP list which is a CSP list . It is initially empty. Move other policies into the policy container. To clone a policy container given a policy container policyContainer Let clone be a new policy container For each policy in policyContainer 's CSP list append a copy of policy into clone 's CSP list Return clone To determine whether a URL url requires storing the policy container in history If url 's scheme is " blob ", then return false. If url is about:srcdoc , then return false. If url is local , then return true. Return false. To create a policy container from a fetch response given a response response If response 's URL 's scheme is " blob ", then return a clone of response 's URL 's blob URL entry 's environment 's policy container Let result be a new policy container Set result 's CSP list to the result of parsing a response's Content Security Policies given response Return result To determine navigation params policy container given a URL responseURL and four policy container -or-nulls historyPolicyContainer initiatorPolicyContainer parentPolicyContainer , and responsePolicyContainer If historyPolicyContainer is not null, then: Assert: responseURL requires storing the policy container in history Return a clone of historyPolicyContainer If responseURL is about:srcdoc , then: Assert: parentPolicyContainer is not null. Return a clone of parentPolicyContainer If responseURL is local and initiatorPolicyContainer is not null, then return a clone of initiatorPolicyContainer If responsePolicyContainer is not null, then return responsePolicyContainer Return a new policy container To initialize a worker global scope's policy container given a WorkerGlobalScope workerGlobalScope and a response response If workerGlobalScope 's url is local but its scheme is not " blob ": Assert: workerGlobalScope 's owner set 's size is 1. Set workerGlobalScope 's policy container to a clone of workerGlobalScope 's owner set [0]'s relevant settings object 's policy container Otherwise, set workerGlobalScope 's policy container to the result of creating a policy container from a fetch response given response 7.10 Session history and navigation 7.10.1 Browsing sessions browsing session is …. See whatwg/html issue #4782 and whatwg/html issue #5350 for defining browsing session . It is roughly analogous to a top-level browsing context except that it cannot be replaced due to a ` Cross-Origin-Opener-Policy ` header or navigation. top-level browsing context has an associated browsing session which is a browsing session The browsing session of an environment settings object environment is the result of running these steps: Assert: environment has a responsible document Return environment 's responsible document 's browsing context 's top-level browsing context 's browsing session 7.10.2 The session history of browsing contexts The sequence of Document s in a browsing context is its session history . Each browsing context , including child browsing contexts , has a distinct session history. A browsing context 's session history consists of a flat list of session history entries Each Document object in a browsing context 's session history is associated with a unique History object which must all model the same underlying session history The history getter steps are to return this 's associated Document 's History instance. session history entry is a struct with the following items URL , a URL document , a Document or null Each entry, when first created, has a Document for its document . However, when a Document is not active , it's possible for it to be discarded to free resources. The URL and other data in the session history entry is then used to bring a new Document into being to take the place of the original, in the case where the user agent finds itself having to navigate to the entry. serialized state , which is serialized state or null, initially null policy container , a policy container or null. scroll restoration mode , a scroll restoration mode , initially " auto scroll position data , which is scroll position data for the document 's restorable scrollable regions browsing context name , a browsing context name or null, initially null persisted user state which is implementation-defined , initially null For example, some user agents might want to persist the values of form controls. User agents that persist the value of form controls are encouraged to also persist their directionality (the value of the element's dir attribute). This prevents values from being displayed incorrectly after a history traversal when the user had originally entered the values with an explicit, non-default directionality. Serialized state is a serialization (via StructuredSerializeForStorage ) of an object representing a user interface state. We sometimes informally refer to "state objects", which are the objects representing user interface state supplied by the author, or alternately the objects created by deserializing (via StructuredDeserialize ) serialized state. Pages can add serialized state to the session history. These are then deserialized and returned to the script when the user (or script) goes back in the history, thus enabling authors to use the "navigation" metaphor even in one-page applications. Serialized state is intended to be used for two main purposes: first, storing a preparsed description of the state in the URL so that in the simple case an author doesn't have to do the parsing (though one would still need the parsing for handling URLs passed around by users, so it's only a minor optimization). Second, so that the author can store state that one wouldn't store in the URL because it only applies to the current Document instance and it would have to be reconstructed if a new Document were opened. An example of the latter would be something like keeping track of the precise coordinate from which a popup div was made to animate, so that if the user goes back, it can be made to animate to the same location. Or alternatively, it could be used to keep a pointer into a cache of data that would be fetched from the server based on the information in the URL , so that when going back and forward, the information doesn't have to be fetched again. scroll restoration mode indicates whether the user agent should restore the persisted scroll position (if any) when traversing to an entry . A scroll restoration mode is one of the following: auto The user agent is responsible for restoring the scroll position upon navigation. manual The page is responsible for restoring the scroll position and the user agent does not attempt to do so automatically Several contiguous entries in a session history can share the same document . This can occur when the initial entry is reached via normal , and the following entry is added via history.pushState() . Or it can occur via navigation to a fragment All entries that share the same document (and that are therefore merely different states of one particular document) are contiguous by definition. User agents may discard the documents of entries with non-null documents , as long as the following conditions are met: They must not discard the document of the current entry They must not discard any Document objects which are referenced from script. Apart from these restrictions, this standard does not specify when user agents should discard an entry's document , versus keeping it cached. Discarding Document will set the corresponding document item of any session history entries to null. Subsequent navigations to those entries will result in the creation of a new Document object, and set the document item to it. At any point, one of the entries in the session history is the current entry . This is the entry representing the active document of the browsing context Which entry is the current entry is changed by the algorithms defined in this specification, e.g., during session history traversal The current entry is usually the initial entry created upon navigation. However, it can also be one of the contiguous entries that share the same document , as described above. Each Document in a browsing context can also have a latest entry . This is the entry for that Document to which the browsing context 's session history was most recently traversed. When a Document is created, it initially has no latest entry 7.10.3 The History interface History Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 3+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 10.1+ Window/history Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 3+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 10.1+ enum ScrollRestoration auto manual };
Exposed Window interface History readonly attribute unsigned long length attribute ScrollRestoration scrollRestoration readonly attribute any state undefined go optional long delta = 0); undefined back (); undefined forward (); undefined pushState any data DOMString unused optional USVString url null ); undefined replaceState any data DOMString unused optional USVString url null ); }; window history length History/length Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ Returns the number of entries in the joint session history window history scrollRestoration [ = value History/scrollRestoration Support in all current engines. Firefox 46+ Safari 11+ Chrome 46+ Opera 33+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 46+ Safari iOS 11+ Chrome Android 46+ WebView Android 46+ Samsung Internet 5.0+ Opera Android 33+ Returns the scroll restoration mode of the current entry in the session history Can be set, to change the scroll restoration mode of the current entry in the session history window history state History/state Support in all current engines. Firefox 4+ Safari 6+ Chrome 19+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 6+ Chrome Android 25+ WebView Android 37+ Samsung Internet 1.5+ Opera Android 12.1+ Returns the current serialized state , deserialized into an object. window history go ( [ delta ] ) History/go Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ Goes back or forward the specified number of steps in the joint session history A zero delta will reload the current page. If the delta is out of range, does nothing. window history back () History/back Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ Goes back one step in the joint session history If there is no previous page, does nothing. window history forward () History/forward Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ Goes forward one step in the joint session history If there is no next page, does nothing. window history pushState data , ""[, url ]) History/pushState Support in all current engines. Firefox 4+ Safari 5+ Chrome 5+ Opera 11.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 4+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11.5+ Pushes the given data onto the session history, and, if provided and not null, the given URL. (The second parameter exists for historical reasons, and cannot be omitted; passing the empty string is traditional.) window history replaceState data , ""[, url ]) History/replaceState Support in all current engines. Firefox 4+ Safari 5+ Chrome 5+ Opera 11.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 4+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11.5+ Updates the current entry in the session history to have the given data, and if provided and not null, URL. (The second parameter exists for historical reasons, and cannot be omitted; passing the empty string is traditional.) The joint session history of a top-level browsing context is the union of all the session histories of all browsing contexts of all the fully active Document objects that share that top-level browsing context , with all the entries that are current entries in their respective session histories removed except for the current entry of the joint session history The current entry of the joint session history is the entry that most recently became a current entry in its session history Entries in the joint session history are ordered chronologically by the time they were added to their respective session histories . Each entry has an index; the earliest entry has index 0, and the subsequent entries are numbered with consecutively increasing integers (1, 2, 3, etc). Since each Document in a browsing context might have a different event loop , the actual state of the joint session history can be somewhat nebulous. For example, two sibling iframe elements could both traverse from one unique origin to another at the same time, so their precise order might not be well-defined; similarly, since they might only find out about each other later, they might disagree about the length of the joint session history Each History object has state initially null. The length getter steps are: If this 's associated Document is not fully active then throw a SecurityError DOMException Return the number of entries in the top-level browsing context 's joint session history The actual entries are not accessible from script. The scrollRestoration getter steps are: If this 's associated Document is not fully active then throw a SecurityError DOMException Return this 's session history 's current entry 's scroll restoration mode The scrollRestoration setter steps are: If this 's associated Document is not fully active then throw a SecurityError DOMException Set this 's session history 's current entry 's scroll restoration mode to the given value. The state getter steps are: If this 's associated Document is not fully active then throw a SecurityError DOMException Return this 's state The go( delta method steps are: Let document be this 's associated Document If document is not fully active , then throw a SecurityError DOMException If delta is 0, then act as if the location.reload() method was called, and return. Traverse the history by a delta with delta and document 's browsing context The back() method steps are: Let document be this 's associated Document If document is not fully active , then throw a SecurityError DOMException Traverse the history by a delta with −1 and document 's browsing context The forward() method steps are: Let document be this 's associated Document If document is not fully active , then throw a SecurityError DOMException Traverse the history by a delta with +1 and document 's browsing context Each top-level browsing context has a session history traversal queue initially empty, to which tasks can be added. Each top-level browsing context , when created, must begin running the following algorithm, known as the session history event loop for that top-level browsing context in parallel Wait until this top-level browsing context 's session history traversal queue is not empty. Pull the first task from this top-level browsing context 's session history traversal queue , and execute it. Return to the first step of this algorithm. The session history event loop helps coordinate cross-browsing-context transitions of the joint session history : since each browsing context might, at any particular time, have a different event loop (this can happen if the user navigates from example.com to shop.example ), transitions would otherwise have to involve cross-event-loop synchronization. To traverse the history by a delta given delta and browsing context source browsing context , the user agent must append a task to this top-level browsing context 's session history traversal queue , the task consisting of running the following steps: If the index of the current entry of the joint session history plus delta is less than zero or greater than or equal to the number of items in the joint session history , then return. Let specified entry be the entry in the joint session history whose index is the sum of delta and the index of the current entry of the joint session history Let specified browsing context be the browsing context of the specified entry If source browsing context is not allowed to navigate specified browsing context , then return. If the specified browsing context 's active document 's unload counter is greater than 0, then return. Queue a global task on the history traversal task source given specified browsing context 's active window to perform the following steps: If there is an ongoing attempt to navigate specified browsing context that has not yet matured (i.e. it has not passed the point of making its Document the active document ), then cancel that attempt to navigate the browsing context If the specified browsing context 's active document is not the same Document as the Document of the specified entry , then run these substeps: Prompt to unload the active document of the specified browsing context . If the user refused to allow the document to be unloaded , then return. Unload the active document of the specified browsing context Traverse the history of the specified browsing context to the specified entry with explicitHistoryNavigation set to true. When the user navigates through a browsing context , e.g. using a browser's back and forward buttons, the user agent must traverse the history by a delta with a delta equivalent to the action specified by the user and the browsing context being operated on. The URL and history update steps , given a Document document URL newURL , an optional serialized state -or-null serializedData (default null), and an optional boolean isPush (default false), are: Let browsingContext be document 's browsing context If isPush is true, then: Remove all the entries in browsingContext 's session history after the current entry . If the current entry is the last entry in the session history, then no entries are removed. This doesn't necessarily have to affect the user agent's user interface. Remove any tasks queued by the history traversal task source that are associated with any Document objects in the top-level browsing context 's document family Save persisted state to the current entry Add a session history entry entry to browsingContext 's session history , after the current entry , with newURL as the URL document as the document serializedData as the serialized state the scroll restoration mode of the current entry in the session history as the scroll restoration mode Update the current entry to be this newly added entry. Otherwise: Let entry be browsingContext 's session history 's current entry Set entry 's URL to newURL If serializedData is not null, then set entry 's serialized state to serializedData Update entry so that it represents a GET request, if it currently represents a non-GET request (e.g. it was the result of a POST submission). What does this mean? This is not a part of the definition of session history entry Set document 's URL to newURL Since this is neither a of the browsing context nor a history traversal it does not cause a hashchange event to be fired. If serializedData is not null, then: Let state be StructuredDeserialize serializedData document 's relevant Realm ). If this throws an exception, catch it, ignore the exception, and set state to null. Set document 's History instance's state to state Set the current entry 's document 's latest entry to the current entry The pushState( data unused url method steps are to run the shared history push/replace state steps given this data url , and true. The replaceState( data unused url method steps are to run the shared history push/replace state steps given this data url , and false. The shared history push/replace state steps , given a History history , a value data , a scalar value string -or-null url , and a boolean isPush , are: Let document be history 's associated Document If document is not fully active , then throw a SecurityError DOMException Optionally, return. (For example, the user agent might disallow calls to these methods that are invoked on a timer, or from event listeners that are not triggered in response to a clear user action, or that are invoked in rapid succession.) Let serializedData be StructuredSerializeForStorage data ). Rethrow any exceptions. Let newURL be the session history 's current entry 's URL If url is not null, then: Parse url , relative to the relevant settings object of history If that fails, then throw a SecurityError DOMException Set newURL to the resulting URL record Compare newURL to document 's URL . If any component of these two URL records differ other than the path query , and fragment components, then throw a SecurityError DOMException If the origin of newURL is not same origin with the origin of document , and either the path or query components of the two URL records compared in the previous step differ, throw a SecurityError DOMException . (This prevents sandboxed content from spoofing other pages on the same origin.) Run the URL and history update steps given document and newURL , with serializedData set to serializedData and isPush set to isPush User agents may limit the number of state objects added to the session history per page. If a page hits the implementation-defined limit, user agents must remove the entry immediately after the first entry for that Document object in the session history after having added the new entry. (Thus the state history acts as a FIFO buffer for eviction, but as a LIFO buffer for navigation.) Consider a game where the user can navigate along a line, such that the user is always at some coordinate, and such that the user can bookmark the page corresponding to a particular coordinate, to return to it later. A static page implementing the x=5 position in such a game could look like the following: html lang "en" title Line Game - 5 title You are at coordinate 5 on the line. href "?x=6" Advance to 6 or href "?x=4" retreat to 4 The problem with such a system is that each time the user clicks, the whole page has to be reloaded. Here instead is another way of doing it, using script: html lang "en" title Line Game - 5 title You are at coordinate span id "coord" span on the line. href "?x=6" onclick "go(1); return false;" Advance to 6 or href "?x=4" onclick "go(-1); return false;" retreat to 4 script var currentPage // prefilled by server function go setupPage currentPage ); history pushState currentPage "" '?x=' currentPage ); onpopstate function event setupPage event state ); function setupPage page currentPage page document title 'Line Game - ' currentPage document getElementById 'coord' ). textContent currentPage document links ]. href '?x=' currentPage ); document links ]. textContent 'Advance to ' currentPage ); document links ]. href '?x=' currentPage ); document links ]. textContent 'retreat to ' currentPage ); script In systems without script, this still works like the previous example. However, users that do have script support can now navigate much faster, since there is no network access for the same experience. Furthermore, contrary to the experience the user would have with just a naïve script-based approach, bookmarking and navigating the session history still work. In the example above, the data argument to the pushState() method is the same information as would be sent to the server, but in a more convenient form, so that the script doesn't have to parse the URL each time the user navigates. Applications might not use the same title for a session history entry as the value of the document's title element at that time. For example, here is a simple page that shows a block in the title element. Clearly, when navigating backwards to a previous state the user does not go back in time, and therefore it would be inappropriate to put the time in the session history title. HTML LANG EN TITLE Line TITLE SCRIPT setInterval function () document title 'Line - ' new Date (); }, 1000 ); var function inc () set ); history pushState "" ); function set newI newI document forms value newI SCRIPT BODY ONPOPSTATE "set(event.state)" FORM NAME State: OUTPUT NAME OUTPUT INPUT VALUE "Increment" TYPE BUTTON ONCLICK "inc()" FORM Most applications want to use the same scroll restoration mode value for all of their history entries. To achieve this they can set the scrollRestoration attribute as soon as possible (e.g., in the first script element in the document's head element) to ensure that any entry added to the history session gets the desired scroll restoration mode. head script if 'scrollRestoration' in history history scrollRestoration 'manual' script head 7.10.4 Implementation notes for session history This section is non-normative. The History interface is not meant to place restrictions on how implementations represent the session history to the user. For example, session history could be implemented in a tree-like manner, with each page having multiple "forward" pages. This specification doesn't define how the linear list of pages in the history object are derived from the actual session history as seen from the user's perspective. Similarly, a page containing two iframe s has a history object distinct from the iframe s' history objects, despite the fact that typical web browsers present the user with just one "Back" button, with a session history that interleaves the navigation of the two inner frames and the outer page. Security : It is suggested that to avoid letting a page "hijack" the history navigation facilities of a UA by abusing pushState() the UA provide the user with a way to jump back to the previous page (rather than just going back to the previous state). For example, the back button could have a drop down showing just the pages in the session history, and not showing any of the states. Similarly, an aural browser could have two "back" commands, one that goes back to the previous state, and one that jumps straight back to the previous page. For both pushState() and replaceState() , user agents are encouraged to prevent abuse of these APIs via too-frequent calls or over-large state objects. As detailed above, the algorithm explicitly allows user agents to ignore any such calls when appropriate. 7.10.5 The Location interface Document/location Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 3+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 10.1+ Location Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 3+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 3+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 10.1+ Window/location Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 3+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 10.1+ Each Window object is associated with a unique instance of a Location object, allocated when the Window object is created. The Location exotic object is defined through a mishmash of IDL, invocation of JavaScript internal methods post-creation, and overridden JavaScript internal methods. Coupled with its scary security policy, please take extra care while implementing this excrescence. To create a Location object, run these steps: Let location be a new Location platform object Let valueOf be location 's relevant Realm .[[Intrinsics]].[[ %Object.prototype.valueOf% ]]. Perform ! location .[[DefineOwnProperty]](" valueOf ", { [[Value]]: valueOf [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }). Perform ! location .[[DefineOwnProperty]]( @@toPrimitive , { [[Value]]: undefined, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }). Set the value of the [[DefaultProperties]] internal slot of location to location .[[OwnPropertyKeys]](). Return location The addition of valueOf and @@toPrimitive own data properties, as well as the fact that all of Location 's IDL attributes are marked LegacyUnforgeable , is required by legacy code that consulted the Location interface, or stringified it, to determine the document URL , and then used it in a security-sensitive way. In particular, the valueOf @@toPrimitive , and LegacyUnforgeable stringifier mitigations ensure that code such as foo[location] = bar or location + "" cannot be misdirected. document location [ = value window location [ = value Returns a Location object with the current page's location. Can be set, to navigate to another page. The Document object's location attribute's getter must return this Document object's relevant global object 's Location object, if this Document object is fully active , and null otherwise. The Window object's location attribute's getter must return this Window object's Location object. Location objects provide a representation of the URL of the active document of their Document 's browsing context , and allow the current entry of the browsing context 's session history to be changed, by adding or replacing entries in the history object. Exposed Window interface Location { // but see also additional creation steps and overridden internal methods LegacyUnforgeable stringifier attribute USVString href LegacyUnforgeable readonly attribute USVString origin LegacyUnforgeable attribute USVString protocol LegacyUnforgeable attribute USVString host LegacyUnforgeable attribute USVString hostname LegacyUnforgeable attribute USVString port LegacyUnforgeable attribute USVString pathname LegacyUnforgeable attribute USVString LegacyUnforgeable attribute USVString hash
LegacyUnforgeable undefined assign USVString url ); LegacyUnforgeable undefined replace USVString url ); LegacyUnforgeable undefined reload ();
LegacyUnforgeable SameObject readonly attribute DOMStringList ancestorOrigins }; location toString() location href Location/href Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 3+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ Location/toString Support in all current engines. Firefox 22+ Safari 1+ Chrome 52+ Opera Edge 79+ Edge (Legacy) 12+ Internet Explorer 11 Firefox Android 22+ Safari iOS 1+ Chrome Android 52+ WebView Android 52+ Samsung Internet 6.0+ Opera Android Returns the Location object's URL. Can be set, to navigate to the given URL. location origin Location/origin Support in all current engines. Firefox 21+ Safari 5.1+ Chrome 8+ Opera 15+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 11 Firefox Android 21+ Safari iOS 5+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 14+ Returns the Location object's URL's origin. location protocol Location/protocol Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 3+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ Returns the Location object's URL's scheme. Can be set, to navigate to the same URL with a changed scheme. location host Location/host Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 3+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ Returns the Location object's URL's host and port (if different from the default port for the scheme). Can be set, to navigate to the same URL with a changed host and port. location hostname Location/hostname Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 3+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ Returns the Location object's URL's host. Can be set, to navigate to the same URL with a changed host. location port Location/port Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 3+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ Returns the Location object's URL's port. Can be set, to navigate to the same URL with a changed port. location pathname Location/pathname Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 3+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ Returns the Location object's URL's path. Can be set, to navigate to the same URL with a changed path. location Location/search Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 3+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ Returns the Location object's URL's query (includes leading " " if non-empty). Can be set, to navigate to the same URL with a changed query (ignores leading " "). location hash Location/hash Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 3+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ Returns the Location object's URL's fragment (includes leading " " if non-empty). Can be set, to navigate to the same URL with a changed fragment (ignores leading " "). location assign url Location/assign Support in all current engines. Firefox 1+ Safari 3+ Chrome 1+ Opera 3+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 5.5+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 10.1+ Navigates to the given URL. location replace url Location/replace Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 3+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 5.5+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 10.1+ Removes the current page from the session history and navigates to the given URL. location reload () Location/reload Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 3+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 5.5+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 10.1+ Reloads the current page. location ancestorOrigins Location/ancestorOrigins Firefox No Safari 6+ Chrome 20+ Opera 15+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android No Safari iOS 6+ Chrome Android 25+ WebView Android 4.4+ Samsung Internet 1.5+ Opera Android 14+ Returns a DOMStringList object listing the origins of the ancestor browsing contexts , from the parent browsing context to the top-level browsing context Location object has an associated relevant Document which is this Location object's relevant global object 's browsing context 's active document , if this Location object's relevant global object 's browsing context is non-null, and null otherwise. Location object has an associated url which is this Location object's relevant Document 's URL , if this Location object's relevant Document is non-null, and about:blank otherwise. Location object has an associated ancestor origins list . When a Location object is created, its ancestor origins list must be set to a DOMStringList object whose associated list is the list of strings that the following steps would produce: Let output be a new list of strings. Let current be the browsing context of the Document with which this Location object is associated. Loop : If current has no parent browsing context , jump to the step labeled end Let current be current 's parent browsing context Append the serialization of current 's active document 's origin to output Return to the step labeled loop End : Return output Location object has an associated Location -object-setter navigate algorithm, which given a url , runs these steps: Let historyHandling be " replace ". If any of the following conditions are met, then set historyHandling to " default ": This Location object's relevant Document has completely loaded , or In the task in which the algorithm is running, an activation behavior is currently being processed whose click event's isTrusted attribute is true, or In the task in which the algorithm is running, the event listener for a click event, whose isTrusted attribute is true, is being handled. Location -object navigate , given url and historyHandling To Location -object navigate , given a url and historyHandling Let browsingContext be the current global object 's browsing context Let sourceBrowsingContext be the incumbent global object 's browsing context If browsingContext is still on its initial about:blank Document , then set historyHandling to " replace ". Navigate browsingContext to url with exceptionsEnabled set to true, historyHandling set to historyHandling , and the source browsing context set to sourceBrowsingContext The href attribute's getter must run these steps: If this Location object's relevant Document is non-null and its origin is not same origin-domain with the entry settings object 's origin , then throw a SecurityError DOMException Return this Location object's url serialized The href attribute's setter must run these steps: If this Location object's relevant Document is null, then return. Parse the given value relative to the entry settings object . If that failed, throw a TypeError exception. Location -object-setter navigate given the resulting URL record The href attribute setter intentionally has no security check. The origin attribute's getter must run these steps: If this Location object's relevant Document is non-null and its origin is not same origin-domain with the entry settings object 's origin , then throw a SecurityError DOMException Return the serialization of this Location object's url 's origin The protocol attribute's getter must run these steps: If this Location object's relevant Document is non-null and its origin is not same origin-domain with the entry settings object 's origin , then throw a SecurityError DOMException Return this Location object's url 's scheme followed by " ". The protocol attribute's setter must run these steps: If this Location object's relevant Document is null, then return. If this Location object's relevant Document 's origin is not same origin-domain with the entry settings object 's origin then throw a SecurityError DOMException Let copyURL be a copy of this Location object's url Let possibleFailure be the result of basic URL parsing the given value, followed by " ", with copyURL as url and scheme start state as state override Because the URL parser ignores multiple consecutive colons, providing a value of " https: " (or even " https:::: ") is the same as providing a value of " https ". If possibleFailure is failure, then throw a SyntaxError DOMException If copyURL 's scheme is not an HTTP(S) scheme , then terminate these steps. Location -object-setter navigate to copyURL The host attribute's getter must run these steps: If this Location object's relevant Document is non-null and its origin is not same origin-domain with the entry settings object 's origin , then throw a SecurityError DOMException Let url be this Location object's url If url 's host is null, return the empty string. If url 's port is null, return url 's host serialized Return url 's host serialized , followed by " " and url 's port serialized The host attribute's setter must run these steps: If this Location object's relevant Document is null, then return. If this Location object's relevant Document 's origin is not same origin-domain with the entry settings object 's origin then throw a SecurityError DOMException Let copyURL be a copy of this Location object's url If copyURL 's cannot-be-a-base-URL is true, then return. Basic URL parse the given value, with copyURL as url and host state as state override Location -object-setter navigate to copyURL The hostname attribute's getter must run these steps: If this Location object's relevant Document is non-null and its origin is not same origin-domain with the entry settings object 's origin , then throw a SecurityError DOMException If this Location object's url 's host is null, return the empty string. Return this Location object's url 's host serialized The hostname attribute's setter must run these steps: If this Location object's relevant Document is null, then return. If this Location object's relevant Document 's origin is not same origin-domain with the entry settings object 's origin then throw a SecurityError DOMException Let copyURL be a copy of this Location object's url If copyURL 's cannot-be-a-base-URL is true, then return. Basic URL parse the given value, with copyURL as url and hostname state as state override Location -object-setter navigate to copyURL The port attribute's getter must run these steps: If this Location object's relevant Document is non-null and its origin is not same origin-domain with the entry settings object 's origin , then throw a SecurityError DOMException If this Location object's url 's port is null, return the empty string. Return this Location object's url 's port serialized The port attribute's setter must run these steps: If this Location object's relevant Document is null, then return. If this Location object's relevant Document 's origin is not same origin-domain with the entry settings object 's origin then throw a SecurityError DOMException Let copyURL be a copy of this Location object's url If copyURL cannot have a username/password/port , then return. If the given value is the empty string, then set copyURL 's port to null. Otherwise, basic URL parse the given value, with copyURL as url and port state as state override Location -object-setter navigate to copyURL The pathname attribute's getter must run these steps: If this Location object's relevant Document is non-null and its origin is not same origin-domain with the entry settings object 's origin , then throw a SecurityError DOMException Let url be this Location object's url If url 's cannot-be-a-base-URL is true, then return url 's path [0]. If url 's path is empty, then return the empty string. Return " ", followed by the strings in url 's path (including empty strings), separated from each other by ". The pathname attribute's setter must run these steps: If this Location object's relevant Document is null, then return. If this Location object's relevant Document 's origin is not same origin-domain with the entry settings object 's origin then throw a SecurityError DOMException Let copyURL be a copy of this Location object's url If copyURL 's cannot-be-a-base-URL is true, then return. Set copyURL 's path to the empty list. Basic URL parse the given value, with copyURL as url and path start state as state override Location -object-setter navigate to copyURL The attribute's getter must run these steps: If this Location object's relevant Document is non-null and its origin is not same origin-domain with the entry settings object 's origin , then throw a SecurityError DOMException If this Location object's url 's query is either null or the empty string, return the empty string. Return " ", followed by this Location object's url 's query The attribute's setter must run these steps: If this Location object's relevant Document is null, then return. If this Location object's relevant Document 's origin is not same origin-domain with the entry settings object 's origin then throw a SecurityError DOMException Let copyURL be a copy of this Location object's url If the given value is the empty string, set copyURL 's query to null. Otherwise, run these substeps: Let input be the given value with a single leading " removed, if any. Set copyURL 's query to the empty string. Basic URL parse input , with null, the relevant Document 's document's character encoding copyURL as url , and query state as state override Location -object-setter navigate to copyURL The hash attribute's getter must run these steps: If this Location object's relevant Document is non-null and its origin is not same origin-domain with the entry settings object 's origin , then throw a SecurityError DOMException If this Location object's url 's fragment is either null or the empty string, return the empty string. Return " ", followed by this Location object's url 's fragment The hash attribute's setter must run these steps: If this Location object's relevant Document is null, then return. If this Location object's relevant Document 's origin is not same origin-domain with the entry settings object 's origin then throw a SecurityError DOMException Let copyURL be a copy of this Location object's url Let input be the given value with a single leading " removed, if any. Set copyURL 's fragment to the empty string. Basic URL parse input , with copyURL as url and fragment state as state override Location -object-setter navigate to copyURL Unlike the equivalent API for the and area elements, the hash attribute's setter does not special case the empty string to remain compatible with deployed scripts. When the assign( url method is invoked, the user agent must run the following steps: If this Location object's relevant Document is null, then return. If this Location object's relevant Document 's origin is not same origin-domain with the entry settings object 's origin then throw a SecurityError DOMException Parse url relative to the entry settings object . If that failed, throw a SyntaxError DOMException Location -object navigate given the resulting URL record and " default ". When the replace( url method is invoked, the user agent must run the following steps: If this Location object's relevant Document is null, then return. Parse url relative to the entry settings object . If that failed, throw a SyntaxError DOMException Location -object navigate given the resulting URL record and " replace ". The replace() method intentionally has no security check. When the reload() method is invoked, the user agent must run the appropriate steps from the following list: If this Location object's relevant Document is null Return. If this Location object's relevant Document 's origin is not same origin-domain with the entry settings object 's origin Throw a SecurityError DOMException If the currently executing task is the dispatch of a resize event in response to the user resizing the browsing context Repaint the browsing context and return. If the browsing context 's active document is an iframe srcdoc document Reprocess the iframe attributes of the browsing context 's container Otherwise Navigate the browsing context to this Location object's relevant Document 's URL , with exceptionsEnabled set to true, historyHandling set to " reload ", and the source browsing context set to the browsing context being navigated. When a user requests that the active document of a browsing context be reloaded through a user interface element, the user agent should navigate the browsing context to the same resource as that Document , with historyHandling set to " reload ". In the case of non-idempotent methods (e.g., HTTP POST), the user agent should prompt the user to confirm the operation first, since otherwise transactions (e.g., purchases or database modifications) could be repeated. User agents may allow the user to explicitly override any caches when reloading. The ancestorOrigins attribute's getter must run these steps: If this Location object's relevant Document is null, then return an empty list If this Location object's relevant Document 's origin is not same origin-domain with the entry settings object 's origin , then throw a SecurityError DOMException Otherwise, return this Location object's ancestor origins list The details of how the ancestorOrigins attribute works are still controversial and might change. See issue #1918 for more information. As explained earlier, the Location exotic object requires additional logic beyond IDL for security purposes. The Location object must use the ordinary internal methods except where it is explicitly specified otherwise below. Also, every Location object has a [[DefaultProperties]] internal slot representing its own properties at time of its creation. 7.10.5.1 [[GetPrototypeOf]] ( ) If ! IsPlatformObjectSameOrigin this ) is true, then return ! OrdinaryGetPrototypeOf this ). Return null. 7.10.5.2 [[SetPrototypeOf]] ( Return ! SetImmutablePrototype this ). 7.10.5.3 [[IsExtensible]] ( ) Return true. 7.10.5.4 [[PreventExtensions]] ( ) Return false. 7.10.5.5 [[GetOwnProperty]] ( If ! IsPlatformObjectSameOrigin this ) is true, then: Let desc be ! OrdinaryGetOwnProperty this ). If the value of the [[DefaultProperties]] internal slot of this contains , then set desc .[[Configurable]] to true. Return desc Let property be ! CrossOriginGetOwnPropertyHelper this ). If property is not undefined, then return property Return ? CrossOriginPropertyFallback ). 7.10.5.6 [[DefineOwnProperty]] ( Desc If ! IsPlatformObjectSameOrigin this ) is true, then: If the value of the [[DefaultProperties]] internal slot of this contains , then return false. Return ? OrdinaryDefineOwnProperty this Desc ). Throw a SecurityError DOMException 7.10.5.7 [[Get]] ( Receiver If ! IsPlatformObjectSameOrigin this ) is true, then return ? OrdinaryGet this Receiver ). Return ? CrossOriginGet this Receiver ). 7.10.5.8 [[Set]] ( Receiver If ! IsPlatformObjectSameOrigin this ) is true, then return ? OrdinarySet this Receiver ). Return ? CrossOriginSet this Receiver ). 7.10.5.9 [[Delete]] ( If ! IsPlatformObjectSameOrigin this ) is true, then return ? OrdinaryDelete this ). Throw a SecurityError DOMException 7.10.5.10 [[OwnPropertyKeys]] ( ) If ! IsPlatformObjectSameOrigin this ) is true, then return ! OrdinaryOwnPropertyKeys this ). Return ! CrossOriginOwnPropertyKeys this ). 7.11 Browsing the web 7.11.1 Navigating across documents Certain actions cause the browsing context to navigate to a new resource. A user agent may provide various ways for the user to explicitly cause a browsing context to navigate, in addition to those defined in this specification. For example, following a hyperlink form submission , and the window.open() and location.assign() methods can all cause a browsing context to navigate. resource has a URL, but that might not be the only information necessary to identify it. For example, a form submission that uses HTTP POST would also have the HTTP method and payload. Similarly, an iframe srcdoc document needs to know the data it is to use. Much of the navigation process is concerned with determining how to create a new Document , which ultimately happens in the create and initialize a Document object algorithm. The parameters to this algorithm are tracked via a navigation params struct , which has the following items request null or a request that started the navigation response response that ultimately was navigated to (potentially a network error origin an origin to use for the new Document policy container policy container to use for the new Document final sandboxing flag set sandboxing flag set to impose on the new Document cross-origin opener policy cross-origin opener policy to use for the new Document COOP enforcement result cross-origin opener policy enforcement result , used for reporting and potentially for causing a browsing context group switch reserved environment null or an environment reserved for the new Document browsing context the browsing context to be navigated (or discarded, if a browsing context group switch occurs) history handling history handling behavior has cross-origin redirects a boolean Once a navigation params struct is created, this standard does not mutate any of its items . They are only passed onward to other algorithms. After Document creation, the session history gets updated. A history handling behavior is used to track the desired type of session history update throughout the navigation process. It is one of the following: default A regular navigation which adds a new entry to the session history. entry update A navigation to an existing session history entry to recreate that entry's document , which was previously discarded reload A navigation intended to reload the current page and replace the current session history entry replace A non-reload navigation that will replace the current session history entry Navigation always involves source browsing context , which is the browsing context which was responsible for starting the navigation. As explained in issue #1130 the use of a browsing context as source might not be the correct architecture. To navigate a browsing context browsingContext to a resource resource , with an optional boolean exceptionsEnabled (default false), an optional history handling behavior historyHandling (default " default "), an optional policy container -or-null historyPolicyContainer (default null) and an optional string navigationType (default other "): If resource is a URL , then set resource to a new request whose url is resource If resource is a request and historyHandling is " reload ", then set resource 's reload-navigation flag If the source browsing context is not allowed to navigate browsingContext , then: If exceptionsEnabled is given and is true, then throw a SecurityError DOMException Otherwise, the user agent may instead offer to open resource in a new top-level browsing context or in the top-level browsing context of the source browsing context , at the user's option, in which case the user agent must navigate that designated top-level browsing context to resource as if the user had requested it independently. Doing so, however, can be dangerous, as it means that the user is overriding the author's explicit request to sandbox the content. If browsingContext 's active document 's unload counter is greater than 0, then return. If historyHandling is not " reload ", resource is a request resource 's url equals browsingContext 's active document 's URL with exclude fragments set to true, and resource 's url 's fragment is non-null, then: Navigate to a fragment given browsingContext resource 's url , and historyHandling Return. If historyHandling is " default ", resource is a request , and either resource 's url equals browsingContext 's active document 's URL or resource 's url 's scheme is javascript ", then set historyHandling to replace ". Let activeDocumentNavigationOrigin be the origin of the active document of browsingContext Let incumbentNavigationOrigin be the origin of the incumbent settings object , or if no script was involved, the origin of the node document of the element that initiated the Let initiatorPolicyContainer be a clone of the source browsing context 's active document 's policy container If resource is a request , then set resource 's policy container to initiatorPolicyContainer Cancel any preexisting but not yet mature attempt to navigate browsingContext , including canceling any instances of the fetch algorithm started by those attempts. If one of those attempts has already created and initialized a new Document object abort that Document also. (Navigation attempts that have matured already have session history entries, and are therefore handled during the update the session history with the new page algorithm, later.) Prompt to unload the active document of browsingContext If the user refused to allow the document to be unloaded , then return. If this instance of the algorithm gets canceled while this step is running, the prompt to unload algorithm must nonetheless be run to completion. Abort the active document of browsingContext If browsingContext is a child browsing context , then put it in the delaying load events mode The user agent must take this child browsing context out of the delaying load events mode when this algorithm later matures , or when it terminates (whether due to having run all the steps, or being canceled, or being aborted), whichever happens first. Let sandboxFlags be the result of determining the creation sandboxing flags given browsingContext and browsingContext 's container Let allowedToDownload be the result of running the allowed to algorithm given the source browsing context and browsingContext Let hasTransientActivation be true if the source browsing context 's active window has transient activation ; otherwise false. Return to whatever algorithm invoked the navigation steps and continue running these steps in parallel This is the step that attempts to obtain resource , if necessary. Jump to the first appropriate substep: If resource is a response Assert: browsingContext is not a top-level browsing context Let finalSandboxFlags be the union of browsingContext 's sandboxing flags and resource 's forced sandboxing flag set Let responseOrigin be the result of determining the origin given browsingContext resource 's url finalSandboxFlags incumbentNavigationOrigin , and activeDocumentNavigationOrigin Let coop be a new cross-origin opener policy Let coopEnforcementResult be a new cross-origin opener policy enforcement result whose needs a browsing context group switch is false, would need a browsing context group switch due to report-only is false, url is resource 's url origin is responseOrigin cross-origin opener policy is coop , and current context is navigation source is false. Let policyContainer be the result of determining navigation params policy container given resource 's url historyPolicyContainer initiatorPolicyContainer browsingContext 's parent browsing context 's active document 's policy container and null. Let navigationParams be a new navigation params whose request is null, response is resource origin is responseOrigin policy container is policyContainer final sandboxing flag set is finalSandboxFlags cross-origin opener policy is coop COOP enforcement result is coopEnforcementResult reserved environment is null, browsing context is browsingContext history handling is historyHandling , and has cross-origin redirects is false. Run process a navigate response with navigationType allowedToDownload hasTransientActivation , and navigationParams If resource is a request whose url 's scheme is " javascript Queue a global task on the DOM manipulation task source given browsingContext 's active window to run these steps: Let response be the result of executing javascript: URL request given resource navigationType , the source browsing context , and browsingContext Let finalSandboxFlags be the union of browsingContext 's sandboxing flags and response 's forced sandboxing flag set Let coopEnforcementResult be a new cross-origin opener policy enforcement result whose needs a browsing context group switch is false, would need a browsing context group switch due to report-only is false, url is resource 's url origin is activeDocumentNavigationOrigin cross-origin opener policy is browsingContext 's active document 's cross-origin opener policy , and current context is navigation source is false. Let navigationParams be a new navigation params whose request is resource response is response origin is activeDocumentNavigationOrigin policy container is browsingContext 's active document 's policy container final sandboxing flag set is finalSandboxFlags cross-origin opener policy is browsingContext 's active document 's cross-origin opener policy COOP enforcement result is coopEnforcementResult reserved environment is null, browsing context is browsingContext history handling is historyHandling , and has cross-origin redirects is false. Run process a navigate response with navigationType allowedToDownload hasTransientActivation , and navigationParams So for example a javascript: URL in an href attribute of an element would only be evaluated when the link was followed , while such a URL in the src attribute of an iframe element would be evaluated in the context of the iframe 's nested browsing context when the iframe is being set up. Once evaluated, its return value (if it was a string) would replace that browsing context 's active document , thus also changing the corresponding Window object. If resource is a request whose url 's scheme is a fetch scheme Run process a navigate fetch given resource , the source browsing context browsingContext navigationType sandboxFlags historyPolicyContainer initiatorPolicyContainer allowedToDownload hasTransientActivation incumbentNavigationOrigin activeDocumentNavigationOrigin , and historyHandling Otherwise, resource is a request whose url 's scheme is neither " javascript " nor a fetch scheme Run process a navigate URL scheme given resource 's url browsingContext , and hasTransientActivation To process a navigate fetch , given a request request , two browsing contexts sourceBrowsingContext and browsingContext a string navigationType , a sandboxing flag set sandboxFlags two policy containers historyPolicyContainer and initiatorPolicyContainer , a boolean allowedToDownload , a boolean hasTransientActivation , two origins incumbentNavigationOrigin and activeDocumentNavigationOrigin , and a history handling behavior historyHandling Let response be null. Set request 's client to sourceBrowsingContext 's active document 's relevant settings object destination to " document ", mode to " navigate ", credentials mode to " include ", use-URL-credentials flag redirect mode to " manual ", and replaces client id to browsingContext 's active document 's relevant settings object 's id If hasTransientActivation is true, then set request 's user-activation to true. If browsingContext 's container is non-null: If the browsingContext 's container has a browsing context scope origin , then set request 's origin to that browsing context scope origin Set request 's destination to browsingContext 's container 's local name Let responseOrigin be null. Let currentContextIsSource be the result of whether browsingContext 's active document is same origin with sourceBrowsingContext 's active document Let coopEnforcementResult be a new cross-origin opener policy enforcement result whose needs a browsing context group switch is false, would need a browsing context group switch due to report-only is false, url is browsingContext 's active document 's url origin is browsingContext 's active document 's origin cross-origin opener policy is browsingContext 's active document 's cross-origin opener policy , and current context is navigation source is currentContextIsSource Let finalSandboxFlags be an empty sandboxing flag set Let locationURL be null. Let currentURL be request 's current URL Let hasCrossOriginRedirects be false. While true: If locationURL is non-null, then: If locationURL 's origin is not the same as currentURL 's origin , then set hasCrossOriginRedirects to true. Set currentURL to locationURL If request 's reserved client is not null and currentURL 's origin is not the same as request 's reserved client 's creation URL 's origin , then: Run the environment discarding steps for request 's reserved client Set request 's reserved client to null. If request 's reserved client is null, then: Let topLevelCreationURL be currentURL Let topLevelOrigin be null. If browsingContext is not a top-level browsing context , then: Let parentEnvironment be browsingContext 's container 's relevant settings object Set topLevelCreationURL to parentEnvironment 's top-level creation URL and topLevelOrigin to parentEnvironment 's top-level origin Set request 's reserved client to a new environment whose id is a unique opaque string, target browsing context is browsingContext creation URL is currentURL top-level creation URL is topLevelCreationURL , and top-level origin is topLevelOrigin The created environment's active service worker is set in the Handle Fetch algorithm during the fetch if the request URL matches a service worker registration. [SW] If the result of Should navigation request of type be blocked by Content Security Policy? given request and navigationType is " Blocked ", then set response to a network error and break [CSP] Otherwise: If response is null, fetch request Otherwise, perform HTTP-redirect fetch using request and response Wait for the task on the networking task source to process response and set response to the result. Set finalSandboxFlags to the union of browsingContext 's sandboxing flags and response 's forced sandboxing flag set Set responseOrigin to the result of determining the origin given browsingContext request 's url finalSandboxFlags incumbentNavigationOrigin , and activeDocumentNavigationOrigin If browsingContext is a top-level browsing context , then: Set responseCOOP to the result of obtaining a cross-origin opener policy given response and request 's reserved client If sandboxFlags is not empty and responseCOOP 's value is not " unsafe-none ", then set response to an appropriate network error and break This results in a network error as one cannot simultaneously provide a clean slate to a response using cross-origin opener policy and sandbox the result of navigating to that response. Set coopEnforcementResult to the result of enforcing the response's cross-origin opener policy given browsingContext request 's url responseOrigin responseCOOP coopEnforcementResult and request 's referrer If response is not a network error browsingContext is a child browsing context , and the result of performing a cross-origin resource policy check with browsingContext 's container document 's origin browsingContext 's container document 's relevant settings object request 's destination response , and true is blocked , then set response to a network error and break Here we're running the cross-origin resource policy check against the parent browsing context rather than sourceBrowsingContext . This is because we care about the same-originness of the embedded content against the parent context, not the navigation source. Set locationURL to response 's location URL given currentURL 's fragment If locationURL is not a URL whose scheme is an HTTP(S) scheme , then break Navigation handles redirects manually as navigation is the only place in the web platform that cares for redirects to mailto: URLs and such. If locationURL is failure, then set response to a network error Otherwise, if locationURL is a URL whose scheme is " blob ", " file ", " filesystem ", or " javascript ", then set response to a network error. Otherwise, if locationURL is a URL whose scheme is a fetch scheme , then run process a navigate fetch with a new request whose url is locationURL sourceBrowsingContext browsingContext navigationType allowedToDownload hasTransientActivation sandboxFlags historyPolicyContainer initiatorPolicyContainer incumbentNavigationOrigin activeDocumentNavigationOrigin , and historyHandling , and return. Otherwise, if locationURL is a URL Process a navigate URL scheme given locationURL browsingContext , and hasTransientActivation Return. Let responsePolicyContainer to be the result of creating a policy container from a fetch response response Let resultPolicyContainer be the result of determining navigation params policy container given response 's URL historyPolicyContainer initiatorPolicyContainer , null, and responsePolicyContainer Let navigationParams be a new navigation params whose request is request response is response origin is responseOrigin policy container is resultPolicyContainer final sandboxing flag set is finalSandboxFlags cross-origin opener policy is responseCOOP COOP enforcement result is coopEnforcementResult reserved environment is request 's reserved client browsing context is browsingContext history handling is historyHandling , and has cross-origin redirects is hasCrossOriginRedirects Run process a navigate response with navigationType allowedToDownload hasTransientActivation , and navigationParams To process a navigate response , given a string navigationType , a boolean allowedToDownload , a boolean hasTransientActivation , and a navigation params navigationParams Let response be navigationParams 's response Let browsingContext be navigationParams 's browsing context Let failure be false. If response is a network error , then set failure to true. Otherwise, if the result of Should navigation response to navigation request of type in target be blocked by Content Security Policy? given navigationParams 's request response navigationParams 's policy container 's CSP list navigationType , and browsingContext is " Blocked ", then set failure to true. [CSP] Otherwise, if navigationParams 's reserved environment is non-null and the result of checking a navigation response's adherence to its embedder policy given response browsingContext , and navigationParams 's reserved environment is false, then set failure to true. Otherwise, if the result of checking a navigation response's adherence to X-Frame-Options given response browsingContext and navigationParams 's origin is false, then set failure to true. If failure is true, then: Display the inline content with an appropriate error shown to the user given browsingContext Run the environment discarding steps for navigationParams 's reserved environment Return. This is where the network errors defined and propagated by Fetch such as DNS or TLS errors, end up being displayed to users. [FETCH] If response 's status is 204 or 205, then return. If response has a ` Content-Disposition ` header specifying the attachment disposition type, then: If allowedToDownload is true, then handle response as a Return. Let type be the computed type of response If the user agent has been configured to process resources of the given type using some mechanism other than rendering the content in a browsing context , then skip this step. Otherwise, if the type is one of the following types, jump to the appropriate entry in the following list, and process response as described there: an HTML MIME type Follow the steps given in the HTML document section providing navigationParams . Once the steps have completed, return. an XML MIME type that is not an explicitly supported XML MIME type Follow the steps given in the XML document section providing navigationParams and type . Once the steps have completed, return. JavaScript MIME type JSON MIME type that is not an explicitly supported JSON MIME type text/css text/plain text/vtt Follow the steps given in the plain text file section providing navigationParams and type . Once the steps have completed, return. multipart/x-mixed-replace Follow the steps given in the multipart/x-mixed-replace section providing navigationParams . Once the steps have completed, return. A supported image, video, or audio type Follow the steps given in the media section providing navigationParams and type . Once the steps have completed, return. A type that will use an external application to render the content in browsingContext Follow the steps given in the plugin section providing navigationParams and type . Once the steps have completed, return. An explicitly supported XML MIME type is an XML MIME type for which the user agent is configured to use an external application to render the content (either a plugin rendering directly in browsingContext , or a separate application), or one for which the user agent has dedicated processing rules (e.g., a web browser with a built-in Atom feed viewer would be said to explicitly support the application/atom+xml MIME type), or one for which the user agent has a dedicated handler. An explicitly supported JSON MIME type is a JSON MIME type for which the user agent is configured to use an external application to render the content (either a plugin rendering directly in browsingContext , or a separate application), or one for which the user agent has dedicated processing rules, or one for which the user agent has a dedicated handler. Non-document content : If, given type , the new resource is to be handled by displaying some sort of inline content, e.g., a native rendering of the content or an error message because the specified type is not supported, then display the inline content given browsingContext and then return. Otherwise, the document's type is such that the resource will not affect browsingContext , e.g., because the resource is to be handed to an external application or because it is an unknown type that will be processed as a download Hand-off to external software given response and hasTransientActivation To process a navigate URL scheme , given a URL url , a browsing context browsingContext , and a boolean hasTransientActivation If url is to be handled using a mechanism that does not affect browsingContext , e.g., because url 's scheme is handled externally, then hand-off to external software given url and hasTransientActivation Otherwise, url is to be handled by displaying some sort of inline content, e.g., an error message because the specified scheme is not one of the supported protocols, or an inline prompt to allow the user to select registered handler for the given scheme. Display the inline content given browsingContext In the case of a registered handler being used, navigate will be invoked with a new URL. To hand-off to external software given a URL or response resource and a boolean hasTransientActivation , user agents should perform the appropriate handoff of resource while attempting to mitigate the risk that this is an attempt to exploit the target software. For example, user agents could prompt the user to confirm that the source browsing context 's active document 's origin is to be allowed to invoke the external software in question. In particular, if hasTransientActivation is false, then the user agent should not invoke the external software package without prior user confirmation. For example, there could be a vulnerability in the target software's URL handler which a hostile page would attempt to exploit by tricking a user into clicking a link. To execute a javascript: URL request given a request request , a string navigationType , and two browsing contexts source and browsingContext , run these steps: Let response be a response whose status is 204 If both of the following are true: source 's active document 's origin is same origin with browsingContext 's active document 's origin As explained in issue #2591 this step does not work and presents a security issue. The result of Should navigation request of type be blocked by Content Security Policy? given request and navigationType is " Allowed ". [CSP] then: Let urlString be the result of running the URL serializer on request 's url Let encodedScriptSource be the result of removing the leading " javascript: " from urlString Let scriptSource be the UTF-8 decoding of the percent-decoding of encodedScriptSource Append browsingContext 's active document 's URL to request 's URL list Let settings be browsingContext 's active document 's relevant settings object Let baseURL be settings 's API base URL Let script be the result of creating a classic script given scriptSource settings baseURL , and the default classic script fetch options Let evaluationStatus be the result of running the classic script script Let result be undefined if evaluationStatus is an abrupt completion or evaluationStatus .[[Value]] is empty, or evaluationStatus .[[Value]] otherwise. If Type result ) is String, then set response to a response whose header list consists of Content-Type `/` text/html ` and ` Referrer-Policy `/ settings 's referrer policy , and whose body is result The exact conversion between the string result and the bytes that comprise a response body is not yet specified, pending further investigation into user agent behavior. See issue #1129 Return response In addition to the specific issues linked above, javascript: URLs have a dedicated label on the issue tracker documenting various problems with their specification. Some of the sections below, to which the above algorithm defers in certain cases, use the following steps to create and initialize a Document object given a type type content type contentType , and navigation params navigationParams Let browsingContext be the result of the obtaining a browsing context to use for a navigation response given navigationParams 's browsing context navigationParams 's final sandboxing flag set navigationParams 's cross-origin opener policy , and navigationParams 's COOP enforcement result Let permissionsPolicy be the result of creating a permissions policy from a response given browsingContext navigationParams 's origin , and navigationParams 's response [PERMISSIONSPOLICY] The creating a permissions policy from a response algorithm makes use of the passed origin . If document.domain has been used for browsingContext 's container document , then its origin cannot be same origin-domain with the passed origin, because these steps run before the document is created, so it cannot itself yet have used document.domain . Note that this means that Permissions Policy checks are less permissive compared to doing a same origin check instead. See below for some examples of this in action. Let creationURL be navigationParams 's response 's URL If navigationParams 's request is non-null, then set creationURL to navigationParams 's request 's current URL If browsingContext is still on its initial about:blank Document , and navigationParams 's history handling is " replace ", and browsingContext 's active document 's origin is same origin-domain with navigationParams 's origin , then do nothing. This means that both the initial about:blank Document , and the new Document that is about to be created, will share the same Window object. Otherwise: Let oacHeader be the result of getting a structured field value given ` Origin-Agent-Cluster ` and " item " from response 's header list Let requestsOAC be true if oacHeader is not null and oacHeader [0] is the boolean true; otherwise false. If navigationParams 's reserved environment is a non-secure context , then set requestsOAC to false. Let agent be the result of obtaining a similar-origin window agent given navigationParams 's origin browsingContext 's group , and requestsOAC Let realm execution context be the result of creating a new JavaScript realm given agent and the following customizations: For the global object, create a new Window object. For the global this binding, use browsingContext 's WindowProxy object. Let topLevelCreationURL be creationURL Let topLevelOrigin be navigationParams 's origin If browsingContext is not a top-level browsing context , then: Let parentEnvironment be browsingContext 's container 's relevant settings object Set topLevelCreationURL to parentEnvironment 's top-level creation URL Set topLevelOrigin to parentEnvironment 's top-level origin Set up a window environment settings object with creationURL realm execution context navigationParams 's reserved environment topLevelCreationURL , and topLevelOrigin This is the usual case, where the new Document we're about to create gets a new Window to go along with it. Let document be a new Document , whose type is type content type is contentType origin is navigationParams 's origin policy container is navigationParams 's policy container permissions policy is permissionsPolicy active sandboxing flag set is navigationParams 's final sandboxing flag set , and cross-origin opener policy is navigationParams 's cross-origin opener policy The new Window 's associated Document is set to document later, when the caller of this algorithm updates the session history with the new page . That algorithm sets the active document as part of its larger role of synchronizing the Window Document browsing context , and session history Set document 's URL to creationURL Set document 's current document readiness to " loading ". Set document 's referrer policy to the result of parsing the Referrer-Policy ` header of navigationParams 's response [REFERRERPOLICY] If navigationParam 's reserved environment is non-null, then set document 's embedder policy to the result of obtaining an embedder policy given navigationParams 's response and navigationParam 's reserved environment . Otherwise, set it to " unsafe-none ". Run CSP initialization for a Document given document [CSP] If navigationParams 's request is non-null, then: Set document 's referrer to the empty string. Let referrer be navigationParams 's request 's referrer If referrer is a URL record , then set document 's referrer to the serialization of referrer Per Fetch referrer will be either a URL record or " no-referrer " at this point. Set document 's load timing info to a new document load timing info Let historyHandling be navigationParams 's history handling Let navigationType be the result of switching on navigationParams 's history handling default replace navigate reload reload entry update back_forward Create the navigation timing entry for document , with navigationParams 's response 's timing info navigationParams 's request 's redirect count , and navigationType If navigationParams 's response has a ` Refresh ` header, then: Let value be the isomorphic decoding of the value of the header. Run the shared declarative refresh steps with document and value We do not currently have a spec for how to handle multiple ` Refresh ` headers. This is tracked as issue #2900 Return document In this example, the child document is not allowed to use PaymentRequest despite being same origin-domain at the time the child document tries to use it. At the time the child document is initialized, only the parent document has set document.domain , and the child document has not. script document domain 'example.com' script iframe src b.html > iframe script document domain 'example.com' // This happens after the document is initialized new PaymentRequest ); // Not allowed to use script In this example, the child document is allowed to use PaymentRequest , despite not being same origin-domain at the time the child document tries to use it. At the time the child document is initialized, none of the documents have set document.domain yet so same origin-domain falls back to a normal same origin check. iframe src b.html > iframe script document domain 'example.com' script script new PaymentRequest ); // Allowed to use script Some of the sections below, to which the above algorithm defers in certain cases, require the user agent to update the session history with the new page , given some params navigationParams and a Document newDocument . When a user agent is required to do this, it must queue a global task on the networking task source , given the relevant global object of the Document object of the current entry (not the new one), to run the following steps: Let sessionHistory be navigationParams 's browsing context 's session history Let unloadTimingInfo be a new document unload timing info Let previousDocument be sessionHistory 's current entry 's document Unload previousDocument with unloadTimingInfo If this instance of the algorithm is canceled while this step is running the unload a document algorithm, then the unload a document algorithm must be allowed to run to completion, but this instance of the algorithm must not run beyond this step. (In particular, for instance, the cancelation of this algorithm does not abort any event dispatch or script execution occurring as part of unloading the document or its descendants.) If navigationParams 's has cross-origin redirects is false, and newDocument 's origin is the same as previousDocument 's origin , then set newDocument 's previous document unload timing to unloadTimingInfo Switch on navigationParams 's history handling entry update reload Let oldDocument be sessionHistory 's current entry 's document For each entry of sessionHistory : if entry 's document is oldDocument , then set entry 's document to newDocument Traverse the history to sessionHistory 's current entry with historyHandling set to navigationParams 's history handling replace Let newEntry be a new session history entry whose URL is newDocument 's URL and document is newDocument Some browsers copy over the serialized state sessionHistory 's current entry in cases where its URL equals that of newDocument , but this is inconsistent. See issue #6213 for more discussion on this. If newDocument 's URL requires storing the policy container in history , set newEntry 's policy container to navigationParams 's policy container Insert newEntry into sessionHistory after its current entry Traverse the history to newEntry with historyHandling set to " replace ". default Remove all the entries in sessionHistory after its current entry (If the current entry is the last entry in the session history, then no entries are removed.) This doesn't necessarily have to affect the user agent's user interface. Let newEntry be a new session history entry whose URL is newDocument 's URL and document is newDocument If newDocument 's URL requires storing the policy container in history , then set newEntry 's policy container to navigationParams 's policy container Append newEntry to sessionHistory Traverse the history to newEntry The navigation algorithm has now matured Try to scroll to the fragment for newDocument To try to scroll to the fragment for a Document document perform the following steps in parallel Wait for an implementation-defined amount of time. (This is intended to allow the user agent to optimize the user experience in the face of performance concerns.) Queue a global task on the networking task source given document 's relevant global object to run these steps: If document has no parser, or its parser has stopped parsing , or the user agent has reason to believe the user is no longer interested in scrolling to the fragment , then abort these steps. Scroll to the fragment given in document 's URL . If this does not find an indicated part of the document , then try to scroll to the fragment for document 7.11.2 Page load processing model for HTML files When an HTML document is to be loaded , given navigation params navigationParams , the user agent must queue a task on the networking task source to: Let document be the result of creating and initializing a Document object given " html ", " text/html ", and navigationParams Create an HTML parser and associate it with the document . Each task that the networking task source places on the task queue while fetching runs must then fill the parser's input byte stream with the fetched bytes and cause the HTML parser to perform the appropriate processing of the input stream. The input byte stream converts bytes into characters for use in the tokenizer . This process relies, in part, on character encoding information found in the real Content-Type metadata of the resource; the computed type is not used for this purpose. When no more bytes are available, the user agent must queue a global task on the networking task source given the newly-created Document 's relevant global object for the parser to process the implied EOF character, which eventually causes load event to be fired. After creating the Document object, but before any script execution, certainly before the parser stops , the user agent must update the session history with the new page given navigationParams and the newly-created Document 7.11.3 Page load processing model for XML files When faced with displaying an XML file inline, provided navigation params navigationParams and a string type , user agents must follow the requirements defined in XML and Namespaces in XML XML Media Types DOM , and other relevant specifications to create and initialize a Document object given " xml ", type , and navigationParams . They must also create a corresponding XML parser [XML] [XMLNS] [RFC7303] [DOM] At the time of writing, the XML specification community had not actually yet specified how XML and the DOM interact. The actual HTTP headers and other metadata, not the headers as mutated or implied by the algorithms given in this specification, are the ones that must be used when determining the character encoding according to the rules given in the above specifications. Once the character encoding is established, the document's character encoding must be set to that character encoding. Then, with the newly created Document , the user agent must update the session history with the new page given navigationParams and the newly-created Document . User agents may do this before the complete document has been parsed (thus achieving incremental rendering ), and must do this before any scripts are to be executed. Error messages from the parse process (e.g., XML namespace well-formedness errors) may be reported inline by mutating the Document 7.11.4 Page load processing model for text files When a plain text document is to be loaded, provided navigation params navigationParams and a string type , the user agent must queue a task on the networking task source to: Let document be the result of creating and initializing a Document object given " html ", type , and navigationParams Create an HTML parser and associate it with the document . Act as if the tokenizer had emitted a start tag token with the tag name "pre" followed by a single U+000A LINE FEED (LF) character, and switch the HTML parser 's tokenizer to the PLAINTEXT state . Each task that the networking task source places on the task queue while fetching runs must then fill the parser's input byte stream with the fetched bytes and cause the HTML parser to perform the appropriate processing of the input stream. The rules for how to convert the bytes of the plain text document into actual characters, and the rules for actually rendering the text to the user, are defined by the specifications for the computed MIME type of the resource (i.e., type ). The document's character encoding must be set to the character encoding used to decode the document. When no more bytes are available, the user agent must queue a global task on the networking task source given the newly-created Document 's relevant global object for the parser to process the implied EOF character, which eventually causes load event to be fired. After creating the Document object, but potentially before the page has finished parsing, the user agent must update the session history with the new page given navigationParams and the newly-created Document User agents may add content to the head element of the Document e.g., linking to a style sheet, providing script, or giving the document a title In particular, if the user agent supports the Format=Flowed feature of RFC 3676 then the user agent would need to apply extra styling to cause the text to wrap correctly and to handle the quoting feature. This could be performed using, e.g., a CSS extension. 7.11.5 Page load processing model for multipart/x-mixed-replace resources When a resource with the type multipart/x-mixed-replace is to be loaded in a browsing context , the user agent must parse the resource using the rules for multipart types. [RFC2046] This algorithm is passed navigation params , but it's unclear how exactly to use them. For each body part obtained from the resource, the user agent must run process a navigate response using the new body part and the same browsing context , with history handling set to " replace " if a previous body part from the same resource resulted in a creating and initializing a Document object , and otherwise using the same setup as the navigate attempt that caused this section to be invoked in the first place. For the purposes of algorithms processing these body parts as if they were complete stand-alone resources, the user agent must act as if there were no more bytes for those resources whenever the boundary following the body part is reached. Thus, load events (and for that matter unload events) do fire for each body part loaded. 7.11.6 Page load processing model for media When an image, video, or audio resource is to be loaded, provided navigation params navigationParams and a string type , the user agent should: Let document be the result of creating and initializing a Document object given " html ", type , and navigationParams Append an html element to document Append a head element to the html element. Append a body element to the html element. Append an element host element for the media, as described below, to the body element. Set the appropriate attribute of the element host element , as described below, to the address of the image, video, or audio resource. The element host element to create for the media is the element given in the table below in the second cell of the row whose first cell describes the media. The appropriate attribute to set is the one given by the third cell in that same row. Type of media Element for the media Appropriate attribute Image img src Video video src Audio audio src Then, the user agent must act as if it had stopped parsing After creating the Document object, but potentially before the page has finished fully loading, the user agent must update the session history with the new page given navigationParams and the newly-created Document User agents may add content to the head element of the Document , or attributes to the element host element , e.g., to link to a style sheet, to provide a script, to give the document a title , or to make the media autoplay 7.11.7 Page load processing model for content that uses plugins When a resource that requires an external resource to be rendered is to be loaded, provided navigation params navigationParams and a string type , the user agent should: Let document be the result of creating and initializing a Document object given " html ", type , and navigationParmas Mark document as being a plugin document Append an html element to document Append a head element to the html element. Append a body element to the html element. Append an embed to the body element Set the src attribute of the embed element to the address of the resource. The term plugin document is used by Content Security Policy as part of the mechanism that ensures iframe can't be used to evade plugin-types directives. [CSP] Then, the user agent must act as if it had stopped parsing After creating the Document object, but potentially before the page has finished fully loading, the user agent must update the session history with the new page given navigationParams and the newly-created Document User agents may add content to the head element of the Document , or attributes to the embed element, e.g. to link to a style sheet or to give the document a title If the Document 's active sandboxing flag set has its sandboxed plugins browsing context flag set, the synthesized embed element will fail to render the content if the relevant plugin cannot be secured 7.11.8 Page load processing model for inline content that doesn't have a DOM When the user agent is to display a user agent page inline, provided a browsing context browsingContext , the user agent should: Let navigationParams be a new navigation params whose request is null, response is null, origin is a new opaque origin final sandboxing flag set is an empty set, cross-origin opener policy is a new cross-origin opener policy COOP enforcement result is a new cross-origin opener policy enforcement result reserved environment is null, and browsing context is browsingContext The algorithm called in the next step is not prepared to deal with a null response . Probably we should synthesize one instead. Let document be the result of creating and initializing a Document object given " html ", " text/html ", and navigationParams Either associate document with a custom rendering that is not rendered using the normal Document rendering rules, or mutate document until it represents the content the user agent wants to render. Once the page has been set up, the user agent must act as if it had stopped parsing After creating the Document object, but potentially before the page has been completely set up, the user agent must update the session history with the new page given navigationParams and the newly-created Document 7.11.9 Navigating to a fragment To navigate to a fragment given a browsing context browsingContext , a URL url , and a history handling behavior historyHandling If historyHandling is not " replace ", then remove all the entries in browsingContext 's session history after the current entry . (If the current entry is the last entry in the session history, then no entries are removed.) This doesn't necessarily have to affect the user agent's user interface. Remove any tasks queued by the history traversal task source that are associated with any Document objects in browsingContext 's top-level browsing context 's document family Append a new session history entry to the session history whose URL is url document is the current entry 's document policy container is the current entry 's policy-container and scroll restoration mode is the current entry 's scroll restoration mode Traverse the history to the new entry, with historyHandling set to historyHandling and with nonBlockingEvents set to true. This will scroll to the fragment given in what is now the document's URL If the scrolling fails because the relevant ID has not yet been parsed, then the original algorithm will take care of the scrolling instead, as the last few steps of its update the session history with the new page algorithm. When the user agent is required to scroll to the fragment and the indicated part of the document , if any, is being rendered , the user agent must either change the scrolling position of the document using the following algorithm, or perform some other action such that the indicated part of the document is brought to the user's attention. If there is no indicated part, or if the indicated part is not being rendered , then the user agent must do nothing. The aforementioned algorithm is as follows: If there is no indicated part of the document , set the Document 's target element to null. If the indicated part of the document is the top of the document, then: Set the Document 's target element to null. Scroll to the beginning of the document for the Document [CSSOMVIEW] Otherwise: Let target be element that is the indicated part of the document Set the Document 's target element to target Scroll target into view with behavior set to "auto", block set to "start", and inline set to "nearest". [CSSOMVIEW] Run the focusing steps for target , with the Document 's viewport as the fallback target Move the sequential focus navigation starting point to target The indicated part of the document is the one that the fragment , if any, identifies. The semantics of the fragment in terms of mapping it to a node is defined by the specification that defines the MIME type used by the Document (for example, the processing of fragments for XML MIME types is the responsibility of RFC7303). [RFC7303] There is also a target element for each Document , which is used in defining the :target pseudo-class and is updated by the above algorithm. It is initially null. For HTML documents (and HTML MIME types ), the following processing model must be followed to determine what the indicated part of the document is. Let fragment be the document's URL 's fragment If fragment is the empty string, then the indicated part of the document is the top of the document; return. If find a potential indicated element with fragment returns non-null, then the return value is the indicated part of the document return. Let fragmentBytes be the result of percent-decoding fragment Let decodedFragment be the result of running UTF-8 decode without BOM on fragmentBytes If find a potential indicated element with decodedFragment returns non-null, then the return value is the indicated part of the document return. If decodedFragment is an ASCII case-insensitive match for the string top , then the indicated part of the document is the top of the document; return. There is no indicated part of the document To find a potential indicated element given a string fragment , run these steps: If there is an element in the document tree that has an ID equal to fragment , then return the first such element in tree order If there is an element in the document tree that has a name attribute whose value is equal to fragment , then return the first such element in tree order Return null. 7.11.10 History traversal To traverse the history to a session history entry entry with an optional history handling behavior historyHandling (default " default "), an optional boolean nonBlockingEvents (default false), and an optional boolean explicitHistoryNavigation (default false): This algorithm is not just invoked when explicitly going back or forwards in the session history — it is also invoked in other situations, for example when navigating a browsing context as part of updating the session history with the new page If entry 's document is null, then: Assert: historyHandling is " default ". Let request be a new request whose url is entry 's URL If explicitHistoryNavigation is true, then set request 's history-navigation flag Navigate the browsing context to request with historyHandling set to " entry update " and with historyPolicyContainer set to entry 's policy container . The navigation must be done using the same source browsing context as was used the first time entry was created. The " navigate " algorithm reinvokes this "traverse" algorithm to complete the traversal, at which point entry 's document is non-null. If the resource was obtained using a non-idempotent action, for example a POST form submission, or if the resource is no longer available, for example because the computer is now offline and the page wasn't cached, navigating to it again might not be possible. In this case, the navigation will result in a different page than previously; for example, it might be an error message explaining the problem or offering to resubmit the form. Return. Save persisted state to the current entry Let newDocument be entry 's document If newDocument is different than the current entry 's document , or historyHandling is " entry update " or " reload ", then: Remove any tasks queued by the history traversal task source that are associated with any Document objects in the top-level browsing context 's document family If newDocument 's origin is not same origin with the current entry 's document 's origin then: Let entriesToUpdate be all entries in the session history whose document 's origin is same origin as the active document and that are contiguous with the current entry For each entryToUpdate of entriesToUpdate , set entryToUpdate 's browsing context name to the current browsing context name If the browsing context is a top-level browsing context but not an auxiliary browsing context whose disowned is false, then set the browsing context's name to the empty string. Set the active document of the browsing context to newDocument If entry 's browsing context name is not null, then: Set the browsing context's name to entry 's browsing context name Let entriesToUpdate be all entries in the session history whose document 's origin is same origin as the new active document 's origin and that are contiguous with entry For each entryToUpdate of entriesToUpdate , set entryToUpdate 's browsing context name to null. If newDocument has any form controls whose autofill field name is " off ", invoke the reset algorithm of each of those elements. If newDocument 's current document readiness complete ", then queue a global task on the DOM manipulation task source given newDocument 's relevant global object to run the following steps: If newDocument 's page showing flag is true, then abort these steps. Set newDocument 's page showing flag to true. Run any session history document visibility change steps for newDocument that are defined by other applicable specifications This is specifically intended for use by Page Visibility [PAGEVIS] Fire an event named pageshow at newDocument 's relevant global object , using PageTransitionEvent , with the persisted attribute initialized to true, and legacy target override flag set. Set newDocument 's URL to entry 's URL Set newDocument 's is initial about:blank to false. The spec currently allows keeping the initial about:blank Document in session history, but this is probably a bug: see issue #6491 (and especially this comment ). If we fix that then we can convert this step into an assert that newDocument 's is initial about:blank is false, i.e., an assert that we never traverse back to the initial about:blank Document Let hashChanged be false, and let oldURL and newURL be null. If entry 's URL 's fragment is not identical to the current entry 's URL 's fragment , and entry 's document equals the current entry 's document , then set hashChanged to true, set oldURL to the current entry 's URL , and set newURL to entry 's URL If historyHandling is " replace ", then remove the entry immediately before entry in the session history If entry 's persisted user state is null, and its URL 's fragment is non-null, then scroll to the fragment Set the current entry to entry Let targetRealm be the current Realm Record Let state be null. If entry 's serialized state is not null, then set state to StructuredDeserialize entry 's serialized state targetRealm ). If this throws an exception, catch it and ignore the exception. Set newDocument 's History object's state to state Let stateChanged be true if newDocument has a latest entry , and that entry is not entry ; otherwise let it be false. Set newDocument 's latest entry to entry If nonBlockingEvents is false, then run the following steps immediately . Otherwise, queue a global task on the DOM manipulation task source given newDocument 's relevant global object to run the following steps instead. If stateChanged is true, then fire an event named popstate at newDocument 's relevant global object , using PopStateEvent , with the state attribute initialized to state Restore persisted state from entry If hashChanged is true, then fire an event named hashchange at the browsing context 's active window , using HashChangeEvent , with the oldURL attribute initialized to oldURL and the newURL attribute initialized to newURL 7.11.10.1 Persisted history entry state To save persisted state to a session history entry entry Set the scroll position data of entry to contain the scroll positions for all of entry 's document 's restorable scrollable regions Optionally, update entry 's persisted user state to reflect any state that the user agent wishes to persist, such as the values of form fields. To restore persisted state from a session history entry entry If entry 's scroll restoration mode is " auto ", then the user agent may use entry 's scroll position data to restore the scroll positions of entry 's document 's restorable scrollable regions The user agent not restoring scroll positions does not imply that scroll positions will be left at any particular value (e.g., (0,0)). The actual scroll position depends on the navigation type and the user agent's particular caching strategy. So web applications cannot assume any particular scroll position but rather are urged to set it to what they want it to be. Optionally, update other aspects of entry 's document and its rendering, for instance values of form fields, that the user agent had previously recorded in entry 's persisted user state This can even include updating the dir attribute of textarea elements or input elements whose type attribute is in either the Text state or the state, if the persisted state includes the directionality of user input in such controls. The restorable scrollable regions of a Document document are document 's viewport , and all of document 's scrollable regions excepting any child browsing contexts of document Child browsing context scroll restoration is handled by the history entry for those browsing contexts' Document s. 7.11.10.2 The PopStateEvent interface PopStateEvent Support in all current engines. Firefox 4+ Safari Yes Chrome 4+ Opera Yes Edge 79+ Edge (Legacy) 12+ Internet Explorer Firefox Android 4+ Safari iOS Yes Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android Yes Exposed Window interface PopStateEvent Event constructor DOMString type optional PopStateEventInit eventInitDict = {}); readonly attribute any state }; dictionary PopStateEventInit EventInit any state null }; event state Returns a copy of the information that was provided to pushState() or replaceState() The state attribute must return the value it was initialized to. It represents the context information for the event, or null, if the state represented is the initial state of the Document 7.11.10.3 The HashChangeEvent interface HashChangeEvent Support in all current engines. Firefox 3.6+ Safari 5+ Chrome 5+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 8+ Firefox Android 4+ Safari iOS 5+ Chrome Android Yes WebView Android 37+ Samsung Internet Yes Opera Android 11+ Exposed Window interface HashChangeEvent Event constructor DOMString type optional HashChangeEventInit eventInitDict = {}); readonly attribute USVString oldURL readonly attribute USVString newURL }; dictionary HashChangeEventInit EventInit USVString oldURL = ""; USVString newURL = ""; }; event oldURL HashChangeEvent/oldURL Support in all current engines. Firefox 6+ Safari Yes Chrome Yes Opera Yes Edge Yes Edge (Legacy) 12+ Internet Explorer No Firefox Android Yes Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes Returns the URL of the session history entry that was previously current. event newURL HashChangeEvent/newURL Support in all current engines. Firefox 6+ Safari Yes Chrome Yes Opera Yes Edge Yes Edge (Legacy) 12+ Internet Explorer No Firefox Android Yes Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes Returns the URL of the session history entry that is now current. The oldURL attribute must return the value it was initialized to. It represents context information for the event, specifically the URL of the session history entry that was traversed from. The newURL attribute must return the value it was initialized to. It represents context information for the event, specifically the URL of the session history entry that was traversed to. 7.11.10.4 The PageTransitionEvent interface PageTransitionEvent Support in all current engines. Firefox Yes Safari Yes Chrome Yes Opera Yes Edge Yes Edge (Legacy) 12+ Internet Explorer Yes Firefox Android Yes Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes Exposed Window interface PageTransitionEvent Event constructor DOMString type optional PageTransitionEventInit eventInitDict = {}); readonly attribute boolean persisted }; dictionary PageTransitionEventInit EventInit boolean persisted false }; event persisted PageTransitionEvent/persisted Support in all current engines. Firefox Yes Safari Yes Chrome Yes Opera Yes Edge Yes Edge (Legacy) 12+ Internet Explorer 11 Firefox Android Yes Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes For the pageshow event, returns false if the page is newly being loaded (and the load event will fire). Otherwise, returns true. For the pagehide event, returns false if the page is going away for the last time. Otherwise, returns true, meaning that the page might be reused if the user navigates back to this page (if the Document 's salvageable state stays true). Things that can cause the page to be unsalvageable include: The user agent decided to not keep the Document alive in a session history entry after unload Having iframe s that are not salvageable Active WebSocket objects Aborting a Document The persisted attribute must return the value it was initialized to. It represents the context information for the event. 7.11.11 Loading documents Document has a completely loaded time (a time or null), which is initially null. Document is considered completely loaded if its completely loaded time is non-null. To completely finish loading Document document Assert: document 's browsing context is non-null. Set document 's completely loaded time to the current time. Let container be document 's browsing context 's container If container is an iframe element, then queue an element task on the DOM manipulation task source given container to run the iframe load event steps given container Otherwise, if container is non-null, then queue an element task on the DOM manipulation task source given container to fire an event named load at container 7.11.12 Unloading documents Document has a salvageable state, which must initially be true, and a page showing flag, which must initially be false. The page showing flag is used to ensure that scripts receive pageshow and pagehide events in a consistent manner (e.g. that they never receive two pagehide events in a row without an intervening pageshow , or vice versa). Event loops have a termination nesting level counter, which must initially be 0. Document objects have an unload counter , which is used to ignore certain operations while the below algorithms run. Initially, the counter must be set to zero. To prompt to unload , given a Document object document and optionally a recursiveFlag , run these steps: Increase the event loop 's termination nesting level by 1. Increase the document 's unload counter by 1. Let event be the result of creating an event using BeforeUnloadEvent Initialize event 's type attribute to beforeunload and its cancelable attribute true. Dispatch Dispatch event at document 's relevant global object Decrease the event loop 's termination nesting level by 1. If all of the following are true: document 's active sandboxing flag set does not have its sandboxed modals flag set document 's relevant global object has sticky activation event 's canceled flag is set, or the returnValue attribute of event is not the empty string then the user agent may ask the user to confirm that they wish to unload the document. The message shown to the user is not customizable, but instead determined by the user agent. In particular, the actual value of the returnValue attribute is ignored. The user agent is encouraged to avoid asking the user for confirmation if it judges that doing so would be annoying, deceptive, or pointless. If the user agent asks the user for confirmation, it must pause while waiting for the user's response. If the user did not confirm the page navigation, then the user agent refused to allow the document to be unloaded If the recursiveFlag is not set, then: Let descendants be the list of the descendant browsing contexts of document For each browsingContext in descendants Prompt to unload browsingContext 's active document with the recursiveFlag set. If the user refused to allow the document to be unloaded , then the user implicitly also refused to allow document to be unloaded break Decrease the document 's unload counter by 1. To unload Document document , given an optional recursiveFlag and a document unload timing info -or-null unloadTimingInfo (default null): Increase the event loop 's termination nesting level by one. Increase document 's unload counter by 1. If document 's page showing flag is false, then jump to the step labeled unload event below (i.e. skip firing the pagehide event and don't rerun the unloading document visibility change steps ). Set document 's page showing flag to false. If the user agent does not intend to keep document alive in a session history entry (such that it can be reused later on history traversal ), set document 's salvageable state to false. Fire an event named pagehide at document 's relevant global object , using PageTransitionEvent , with the persisted attribute initialized to true if document 's salvageable state is true, and false otherwise, and legacy target override flag set. Run any unloading document visibility change steps for document that are defined by other applicable specifications This is specifically intended for use by Page Visibility [PAGEVIS] If unloadTimingInfo is not null, then set unloadTimingInfo 's unload event start time to the current high resolution time given document 's relevant global object Unload event : If document 's salvageable state is false, then fire an event named unload at document 's relevant global object , with legacy target override flag set. If unloadTimingInfo is not null, then set unloadTimingInfo 's unload event end time to the current high resolution time given document 's relevant global object Decrease the event loop 's termination nesting level by one. Run any unloading document cleanup steps for document that are defined by this specification and other applicable specifications If the recursiveFlag is not set, then: Let descendants be the list of the descendant browsing contexts of document For each browsingContext in descendants Unload the active document of browsingContext with the recursiveFlag set. If the salvageable state of the active document of browsingContext is false, then set the salvageable state of document to false also. If document 's salvageable state is false, then discard document Decrease document 's unload counter by 1. This specification defines the following unloading document cleanup steps Other specifications can define more. Given a Document document Let window be document 's relevant global object For each WebSocket object webSocket whose relevant global object is window make disappear webSocket If this affected any WebSocket objects, then set document 's salvageable state to false. If document 's salvageable state is false, then: For each EventSource object eventSource whose relevant global object is equal to window forcibly close eventSource Empty window 's list of active timers 7.11.12.1 The BeforeUnloadEvent interface BeforeUnloadEvent Support in all current engines. Firefox 1.5+ Safari Yes Chrome 30+ Opera 17+ Edge 79+ Edge (Legacy) 12+ Internet Explorer Yes Firefox Android 4+ Safari iOS Yes Chrome Android 30+ WebView Android 37+ Samsung Internet 3.0+ Opera Android 18+ Exposed Window interface BeforeUnloadEvent Event attribute DOMString returnValue }; There are no BeforeUnloadEvent -specific initialization methods. The BeforeUnloadEvent interface is a legacy interface which allows prompting to unload to be controlled not only by canceling the event, but by setting the returnValue attribute to a value besides the empty string. Authors should use the preventDefault() method, or other means of canceling events, instead of using returnValue The returnValue attribute controls the process of prompting to unload . When the event is created, the attribute must be set to the empty string. On getting, it must return the last value it was set to. On setting, the attribute must be set to the new value. This attribute is a DOMString only for historical reasons. Any value besides the empty string will be treated as a request to ask the user for confirmation. 7.11.13 Aborting a document load To abort Document document Abort the active documents of every child browsing context . If this results in any of those Document objects having their salvageable state set to false, then set document 's salvageable state to false also. Cancel any instances of the fetch algorithm in the context of document , discarding any tasks queued for them, and discarding any further data received from the network for them. If this resulted in any instances of the fetch algorithm being canceled or any queued tasks or any network data getting discarded, then set document 's salvageable state to false. If document has an active parser , then: Set document 's active parser was aborted to true. Abort that parser Set document 's salvageable state to false. User agents may allow users to explicitly invoke the abort a document algorithm for a Document . If the user does so, then, if that Document is an active document , the user agent should queue a task to fire an event named abort at that Document object's relevant global object before invoking the abort algorithm. To stop document loading given a Document object document run these steps: If document is not an active document , then return. Let browsingContext be document 's browsing context If there is an existing attempt to navigate browsingContext and document 's unload counter is 0, then cancel that Abort document 7.11.14 The ` X-Frame-Options ` header The ` X-Frame-Options ` HTTP response header is a legacy way of controlling whether and how a Document may be loaded inside of a child browsing context . It is obsoleted by the frame-ancestors CSP directive, which provides more granular control over the same situations. It was originally defined in HTTP Header Field X-Frame-Options , but the definition and processing model here supersedes that document. [CSP] [RFC7034] In particular, HTTP Header Field X-Frame-Options specified an ` ALLOW-FROM ` variant of the header, but that is not to be implemented. Per the below processing model, ifIf both a CSP frame-ancestors directive and an X-Frame-Options ` header are used in the same response , then ` X-Frame-Options ` is ignored. For web developers and conformance checkers, its value ABNF is: X-Frame-Options "DENY" "SAMEORIGIN" To check a navigation response's adherence to ` X-Frame-Options , given navigationParams navigationParams , a browsing context browsingContext , and an origin destinationOrigin If browsingContext is not a child browsing context , then return true. For each policy of navigationParams 's policy container 's CSP list If policy 's disposition is not " enforce ", then continue If policy 's directive set contains frame-ancestors directive, then return true. Let rawXFrameOptions be the result of getting, decoding, and splitting X-Frame-Options ` from navigationParams 's response 's header list Let xFrameOptions be a new set For each value of rawXFrameOptions append value converted to ASCII lowercase , to xFrameOptions If xFrameOptions 's size is greater than 1, and xFrameOptions contains any of " deny ", " allowall ", or " sameorigin ", then return false. The intention here is to block any attempts at applying X-Frame-Options ` which were trying to do something valid, but appear confused. This is the only impact of the legacy ` ALLOWALL ` value on the processing model. If xFrameOptions 's size is greater than 1, then return true. This means it contains multiple invalid values, which we treat the same way as if the header was omitted entirely. If xFrameOptions [0] is " deny ", then return false. If xFrameOptions [0] is " sameorigin ", then: Let containerDocument be browsingContext 's container document While containerDocument is not null: If containerDocument 's origin is not same origin with destinationOrigin , then return false. Let containerBC be containerDocument 's browsing context Set containerDocument to containerBC 's container document , if containerBC is non-null; otherwise, null. Return true. If we've reached this point then we have a lone invalid value (which could potentially be one the legacy ` ALLOWALL ` or ` ALLOW-FROM ` forms). These are treated as if the header were omitted entirely. The following table illustrates the processing of various values for the header, including non-conformant ones: X-Frame-Options Valid Result DENY embedding disallowed SAMEORIGIN same-origin embedding allowed INVALID embedding allowed ALLOWALL embedding allowed ALLOW-FROM=https://example.com/ embedding allowed (from anywhere) The following table illustrates how various non-conformant cases involving multiple values are processed: X-Frame-Options Result SAMEORIGIN, SAMEORIGIN same-origin embedding allowed SAMEORIGIN, DENY embedding disallowed SAMEORIGIN, embedding disallowed SAMEORIGIN, ALLOWALL embedding disallowed SAMEORIGIN, INVALID embedding disallowed ALLOWALL, INVALID embedding disallowed ALLOWALL, embedding disallowed INVALID, INVALID embedding allowed The same results are obtained whether the values are delivered in a single header whose value is comma-delimited, or in multiple headers. Web application APIs 8.1 Scripting 8.1.1 Introduction Various mechanisms can cause author-provided executable code to run in the context of a document. These mechanisms include, but are probably not limited to: Processing of script elements. Navigating to javascript: URLs Event handlers, whether registered through the DOM using addEventListener() , by explicit event handler content attributes , by event handler IDL attributes , or otherwise. Processing of technologies like SVG that have their own scripting features. 8.1.2 Agents and agent clusters 8.1.2.1 Integration with the JavaScript agent formalism JavaScript defines the concept of an agent . This section gives the mapping of that language-level concept on to the web platform. Conceptually, the agent concept is an architecture-independent, idealized "thread" in which JavaScript code runs. Such code can involve multiple globals/ realms that can synchronously access each other, and thus needs to run in a single execution thread. Two Window objects having the same agent does not indicate they can directly access all objects created in each other's realms. They would have to be same origin-domain ; see IsPlatformObjectSameOrigin The following types of agents exist on the web platform: Similar-origin window agent Contains various Window objects which can potentially reach each other, either directly or by using document.domain If the encompassing agent cluster 's is origin-keyed is true, then all the Window objects will be same origin , can reach each other directly, and document.domain will no-op. Two Window objects that are same origin can be in different similar-origin window agents , for instance if they are each in their own browsing context group Dedicated worker agent Contains a single DedicatedWorkerGlobalScope Shared worker agent Contains a single SharedWorkerGlobalScope Service worker agent Contains a single ServiceWorkerGlobalScope Worklet agent Contains a single WorkletGlobalScope object. Although a given worklet can have multiple realms, each such realm needs its own agent, as each realm can be executing code independently and at the same time as the others. Only shared and dedicated worker agents allow the use of JavaScript Atomics APIs to potentially block To create an agent , given a boolean canBlock Let signifier be a new unique internal value. Let candidateExecution be a new candidate execution Let agent be a new agent whose [[CanBlock]] is canBlock , [[Signifier]] is signifier , [[CandidateExecution]] is candidateExecution , and [[IsLockFree1]], [[IsLockFree2]], and [[LittleEndian]] are set at the implementation's discretion. Set agent 's event loop to a new event loop Return agent The relevant agent for a platform object platformObject is platformObject 's relevant Realm 's agent This pointer is not yet defined in the JavaScript specification; see tc39/ecma262#1357 The agent equivalent of the current Realm Record is the surrounding agent 8.1.2.2 Integration with the JavaScript agent cluster formalism JavaScript also defines the concept of an agent cluster , which this standard maps to the web platform by placing agents appropriately when they are created using the obtain a similar-origin window agent or obtain a worker/worklet agent algorithms. The agent cluster concept is crucial for defining the JavaScript memory model, and in particular among which agents the backing data of SharedArrayBuffer objects can be shared. Conceptually, the agent cluster concept is an architecture-independent, idealized "process boundary" that groups together multiple "threads" agents ). The agent clusters defined by the specification are generally more restrictive than the actual process boundaries implemented in user agents. By enforcing these idealized divisions at the specification level, we ensure that web developers see interoperable behavior with regard to shared memory, even in the face of varying and changing user agent process models. An agent cluster has an associated cross-origin isolation mode , which is a cross-origin isolation mode . It is initially " none ". An agent cluster has an associated is origin-keyed (a boolean), which is initially false. The following defines the allocation of the agent clusters of similar-origin window agents An agent cluster key is a site or tuple origin . Without web developer action to achieve origin-keyed agent clusters , it will be a site An equivalent formulation is that an agent cluster key can be a scheme-and-host or an origin To obtain a similar-origin window agent given an origin origin , a browsing context group group , and a boolean requestsOAC , run these steps: Let site be the result of obtaining a site with origin Let key be site If group 's cross-origin isolation mode is not " none ", then set key to origin Otherwise, if group 's historical agent cluster key map origin exists , then set key to group 's historical agent cluster key map origin ]. Otherwise: If requestsOAC is true, then set key to origin Set group 's historical agent cluster key map origin to key If group 's agent cluster map key does not exist , then: Let agentCluster be a new agent cluster Set agentCluster 's cross-origin isolation mode to group 's cross-origin isolation mode Set agentCluster 's is origin-keyed to true if key equals origin ; otherwise false. Add the result of creating an agent , given false, to agentCluster Set group 's agent cluster map key ] to agentCluster Return the single similar-origin window agent contained in group 's agent cluster map key ]. This means that there is only one similar-origin window agent per browsing context agent cluster. (However, dedicated worker and worklet agents might be in the same cluster.) The following defines the allocation of the agent clusters of all other types of agents. To obtain a worker/worklet agent , given an environment settings object or null outside settings , a boolean isTopLevel , and a boolean canBlock , run these steps: Let agentCluster be null. If isTopLevel is true, then: Set agentCluster to a new agent cluster Set agentCluster 's is origin-keyed to true. These workers can be considered to be origin-keyed. However, this is not exposed through any APIs (in the way that originAgentCluster exposes the origin-keyedness for windows). Otherwise: Assert: outside settings is not null. Let ownerAgent be outside settings 's Realm 's agent. Set agentCluster to the agent cluster which contains ownerAgent Let agent be the result of creating an agent given canBlock Add agent to agentCluster Return agent To obtain a dedicated/shared worker agent , given an environment settings object outside settings and a boolean isShared , return the result of obtaining a worker/worklet agent given outside settings isShared , and true. To obtain a worklet agent , given an environment settings object outside settings , return the result of obtaining a worker/worklet agent given outside settings , false, and false. To obtain a service worker agent , return the result of obtaining a worker/worklet agent given null, true, and false. The following pairs of global objects are each within the same agent cluster , and thus can use SharedArrayBuffer instances to share memory with each other: Window object and a dedicated worker that it created. A worker (of any type) and a dedicated worker it created. Window object and the Window object of an iframe element that created that could be same origin-domain with Window object and a same origin-domain Window object that opened it. Window object and a worklet that it created. The following pairs of global objects are not within the same agent cluster , and thus cannot share memory: Window object and a shared worker it created. A worker (of any type) and a shared worker it created. Window object and a service worker it created. Window object and the Window object of an iframe element that created that cannot be same origin-domain with Any two Window objects whose browsing contexts do not have a non-null opener or ancestor relationship. This holds even if the two Window objects are same origin 8.1.3 Realms and their counterparts The JavaScript specification introduces the realm concept, representing a global environment in which script is run. Each realm comes with an implementation-defined global object ; much of this specification is devoted to defining that global object and its properties. For web specifications, it is often useful to associate values or algorithms with a realm/global object pair. When the values are specific to a particular type of realm, they are associated directly with the global object in question, e.g., in the definition of the Window or WorkerGlobalScope interfaces. When the values have utility across multiple realms, we use the environment settings object concept. Finally, in some cases it is necessary to track associated values before a realm/global object/environment settings object even comes into existence (for example, during ). These values are tracked in the environment concept. 8.1.3.1 Environments An environment is an object that identifies the settings of a current or potential execution environment. An environment has the following fields: An id An opaque string that uniquely identifies this environment creation URL URL that represents the location of the resource with which this environment is associated. In the case of an environment settings object , this URL might be distinct from the environment settings object 's responsible document 's URL , due to mechanisms such as history.pushState() top-level creation URL Null or a URL that represents the creation URL of the "top-level" environment . It is null for workers and worklets. top-level origin for now implementation-defined value, null, or an origin . For a "top-level" potential execution environment it is null (i.e., when there is no response yet); otherwise it is the "top-level" environment 's origin . For a dedicated worker or worklet it is the top-level origin of its creator. For a shared or service worker it is an implementation-defined value. This is distinct from the top-level creation URL 's origin when sandboxing, workers, and worklets are involved. target browsing context Null or a target browsing context for a navigation request An active service worker Null or a service worker that controls the environment An execution ready flag A flag that indicates whether the environment setup is done. It is initially unset. Specifications may define environment discarding steps for environments. The steps take an environment as input. The environment discarding steps are run for only a select few environments: the ones that will never become execution ready because, for example, they failed to load. 8.1.3.2 Environment settings objects An environment settings object is an environment that additionally specifies algorithms for: realm execution context JavaScript execution context shared by all scripts that use this settings object, i.e. all scripts in a given JavaScript realm . When we run a classic script or run a module script , this execution context becomes the top of the JavaScript execution context stack , on top of which another execution context specific to the script in question is pushed. (This setup ensures ParseScript and Source Text Module Record 's Evaluate know which Realm to use.) module map module map that is used when importing JavaScript modules. responsible document Document that is assigned responsibility for actions taken by the scripts that use this environment settings object For example, the URL of the responsible document is used to set the URL of the Document after it has been reset using document.open() If the responsible event loop is not a window event loop , then the environment settings object has no responsible document An API URL character encoding A character encoding used to encode URLs by APIs called by scripts that use this environment settings object An API base URL URL used by APIs called by scripts that use this environment settings object to parse URLs An origin An origin used in security checks. policy container policy container containing policies used for security checks. referrer policy The default referrer policy for fetches performed using this environment settings object as a request client [REFERRERPOLICY] An embedder policy An embedder policy used by cross-origin resource policy checks for fetches performed using this environment settings object as a request client cross-origin isolated capability A boolean representing whether scripts that use this environment settings object are allowed to use APIs that require cross-origin isolation. An environment settings object also has an outstanding rejected promises weak set and an about-to-be-notified rejected promises list , used to track unhandled promise rejections . The outstanding rejected promises weak set must not create strong references to any of its members, and implementations are free to limit its size, e.g. by removing old entries from it when new ones are added. An environment settings object 's responsible event loop is its global object 's relevant agent 's event loop 8.1.3.3 Realms, settings objects, and global objects global object is a JavaScript object that is the [[GlobalObject]] field of JavaScript realm In this specification, all JavaScript realms are created with global objects that are either Window or WorkerGlobalScope objects. There is always a 1-to-1-to-1 mapping between JavaScript realms global objects , and environment settings objects JavaScript realm has a [[HostDefined]] field, which contains the Realm's settings object JavaScript realm has a [[GlobalObject]] field, which contains the Realm's global object Each global object in this specification is created during the creation of a corresponding JavaScript realm , known as the global object's Realm Each global object in this specification is created alongside a corresponding environment settings object known as its relevant settings object An environment settings object 's realm execution context 's Realm component is the environment settings object's Realm An environment settings object 's Realm then has a [[GlobalObject]] field, which contains the environment settings object's global object To create a new JavaScript realm in an agent agent , optionally with instructions to create a global object or a global this binding (or both), the following steps are taken: Perform InitializeHostDefinedRealm () with the provided customizations for creating the global object and the global this binding. Let realm execution context be the running JavaScript execution context This is the JavaScript execution context created in the previous step. Remove realm execution context from the JavaScript execution context stack Let realm be realm execution context 's Realm component. Set realm 's agent to agent This pointer is not yet defined in the JavaScript specification; see tc39/ecma262#1357 If agent 's agent cluster 's cross-origin isolation mode is " none ", then: Let global be realm 's global object Let status be ! global .[[Delete]](" SharedArrayBuffer "). Assert: status is true. This is done for compatibility with web content and there is some hope that this can be removed in the future. Web developers can still get at the constructor through new WebAssembly.Memory({ shared:true, initial:0, maximum:0 }).buffer.constructor Return realm execution context When defining algorithm steps throughout this specification, it is often important to indicate what JavaScript realm is to be used—or, equivalently, what global object or environment settings object is to be used. In general, there are at least four possibilities: Entry This corresponds to the script that initiated the currently running script action: i.e., the function or script that the user agent called into when it called into author code. Incumbent This corresponds to the most-recently-entered author function or script on the stack, or the author function or script that originally scheduled the currently-running callback. Current This corresponds to the currently-running function object, including built-in user-agent functions which might not be implemented as JavaScript. (It is derived from the current JavaScript realm .) Relevant Every platform object has a relevant Realm , which is roughly the JavaScript realm in which it was created. When writing algorithms, the most prominent platform object whose relevant Realm might be important is the this value of the currently-running function object. In some cases, there can be other important relevant Realms , such as those of any arguments. Note how the entry incumbent , and current concepts are usable without qualification, whereas the relevant concept must be applied to a particular platform object The incumbent and entry concepts should not be used by new specifications, as they are excessively complicated and unintuitive to work with. We are working to remove almost all existing uses from the platform: see issue #1430 for incumbent , and issue #1431 for entry In general, web platform specifications should use the relevant concept, applied to the object being operated on (usually the this value of the current method). This mismatches the JavaScript specification, where current is generally used as the default (e.g. in determining the JavaScript realm whose Array constructor should be used to construct the result in Array.prototype.map ). But this inconsistency is so embedded in the platform that we have to accept it going forward. Consider the following pages, with a.html being loaded in a browser window, b.html being loaded in an iframe as shown, and c.html and d.html omitted (they can simply be empty documents): html lang "en" title Entry page title iframe src "b.html" > iframe button onclick "frames[0].hello()" Hello button html lang "en" title Incumbent page title iframe src "c.html" id "c" > iframe iframe src "d.html" id "d" > iframe script const document querySelector "#c" ). contentWindow const document querySelector "#d" ). contentWindow window hello () => call ); }; script Each page has its own browsing context , and thus its own JavaScript realm global object , and environment settings object When the print() method is called in response to pressing the button in a.html , then: The entry Realm is that of a.html The incumbent Realm is that of b.html The current Realm is that of c.html (since it is the print() method from c.html whose code is running). The relevant Realm of the object on which the print() method is being called is that of d.html One reason why the relevant concept is generally a better default choice than the current concept is that it is more suitable for creating an object that is to be persisted and returned multiple times. For example, the navigator.getBattery() method creates promises in the relevant Realm for the Navigator object on which it is invoked. This has the following impact: [BATTERY] html lang "en" title Relevant Realm demo: outer page title script function doTest () const promise navigator getBattery call frames ]. navigator ); console log promise instanceof Promise ); // logs false console log promise instanceof frames ]. Promise ); // logs true frames ]. hello (); script iframe src "inner.html" onload "doTest()" > iframe html lang "en" title Relevant Realm demo: inner page title script function hello () const promise navigator getBattery (); console log promise instanceof Promise ); // logs true console log promise instanceof parent Promise ); // logs false script If the algorithm for the getBattery() method had instead used the current Realm , all the results would be reversed. That is, after the first call to getBattery() in outer.html , the Navigator object in inner.html would be permanently storing Promise object created in outer.html 's JavaScript realm , and calls like that inside the hello() function would thus return a promise from the "wrong" realm. Since this is undesirable, the algorithm instead uses the relevant Realm , giving the sensible results indicated in the comments above. The rest of this section deals with formally defining the entry incumbent current , and relevant concepts. 8.1.3.3.1 Entry The process of calling scripts will push or pop realm execution contexts onto the JavaScript execution context stack , interspersed with other execution contexts With this in hand, we define the entry execution context to be the most recently pushed item in the JavaScript execution context stack that is a realm execution context . The entry Realm is the entry execution context 's Realm component. Then, the entry settings object is the environment settings object of the entry Realm Similarly, the entry global object is the global object of the entry Realm 8.1.3.3.2 Incumbent All JavaScript execution contexts must contain, as part of their code evaluation state, a skip-when-determining-incumbent counter value, which is initially zero. In the process of preparing to run a callback and cleaning up after running a callback , this value will be incremented and decremented. Every event loop has an associated backup incumbent settings object stack , initially empty. Roughly speaking, it is used to determine the incumbent settings object when no author code is on the stack, but author code is responsible for the current algorithm having been run in some way. The process of preparing to run a callback and cleaning up after running a callback manipulate this stack. [WEBIDL] When Web IDL is used to invoke author code, or when HostEnqueuePromiseJob invokes a promise job, they use the following algorithms to track relevant data for determining the incumbent settings object To prepare to run a callback with an environment settings object settings Push settings onto the backup incumbent settings object stack Let context be the topmost script-having execution context If context is not null, increment context 's skip-when-determining-incumbent counter To clean up after running a callback with an environment settings object settings Let context be the topmost script-having execution context This will be the same as the topmost script-having execution context inside the corresponding invocation of prepare to run a callback If context is not null, decrement context 's skip-when-determining-incumbent counter Assert: the topmost entry of the backup incumbent settings object stack is settings Remove settings from the backup incumbent settings object stack Here, the topmost script-having execution context is the topmost entry of the JavaScript execution context stack that has a non-null ScriptOrModule component, or null if there is no such entry in the JavaScript execution context stack With all this in place, the incumbent settings object is determined as follows: Let context be the topmost script-having execution context If context is null, or if context 's skip-when-determining-incumbent counter is greater than zero, then: Assert: the backup incumbent settings object stack is not empty. This assert would fail if you try to obtain the incumbent settings object from inside an algorithm that was triggered neither by calling scripts nor by Web IDL invoking a callback. For example, it would trigger if you tried to obtain the incumbent settings object inside an algorithm that ran periodically as part of the event loop , with no involvement of author code. In such cases the incumbent concept cannot be used. Return the topmost entry of the backup incumbent settings object stack Return context 's Realm component's settings object Then, the incumbent Realm is the Realm of the incumbent settings object Similarly, the incumbent global object is the global object of the incumbent settings object The following series of examples is intended to make it clear how all of the different mechanisms contribute to the definition of the incumbent concept: Consider the following starter example: iframe > iframe script frames ]. postMessage "some data" "*" ); script There are two interesting environment settings objects here: that of window , and that of frames[0] . Our concern is: what is the incumbent settings object at the time that the algorithm for postMessage() executes? It should be that of window , to capture the intuitive notion that the author script responsible for causing the algorithm to happen is executing in window , not frames[0] . This makes sense: the window post message steps use the incumbent settings object to determine the source property of the resulting MessageEvent , and in this case window is definitely the source of the message. Let us now explain how the steps given above give us our intuitively-desired result of window 's relevant settings object When the window post message steps look up the incumbent settings object , the topmost script-having execution context will be that corresponding to the script element: it was pushed onto the JavaScript execution context stack as part of ScriptEvaluation during the run a classic script algorithm. Since there are no Web IDL callback invocations involved, the context's skip-when-determining-incumbent counter is zero, so it is used to determine the incumbent settings object ; the result is the environment settings object of window (Note how the environment settings object of frames[0] is the relevant settings object of this at the time the postMessage() method is called, and thus is involved in determining the target of the message. Whereas the incumbent is used to determine the source .) Consider the following more complicated example: iframe > iframe script const bound frames ]. postMessage bind frames ], "some data" "*" ); window setTimeout bound ); script This example is very similar to the previous one, but with an extra indirection through Function.prototype.bind as well as setTimeout() . But, the answer should be the same: invoking algorithms asynchronously should not change the incumbent concept. This time, the result involves more complicated mechanisms: When bound is converted to a Web IDL callback type, the incumbent settings object is that corresponding to window (in the same manner as in our starter example above). Web IDL stores this as the resulting callback value's callback context When the task posted by setTimeout() executes, the algorithm for that task uses Web IDL to invoke the stored callback value. Web IDL in turn calls the above prepare to run a callback algorithm. This pushes the stored callback context onto the backup incumbent settings object stack . At this time (inside the timer task) there is no author code on the stack, so the topmost script-having execution context is null, and nothing gets its skip-when-determining-incumbent counter incremented. Invoking the callback then calls bound , which in turn calls the postMessage() method of frames[0] . When the postMessage() algorithm looks up the incumbent settings object , there is still no author code on the stack, since the bound function just directly calls the built-in method. So the topmost script-having execution context will be null: the JavaScript execution context stack only contains an execution context corresponding to postMessage() , with no ScriptEvaluation context or similar below it. This is where we fall back to the backup incumbent settings object stack . As noted above, it will contain as its topmost entry the relevant settings object of window . So that is what is used as the incumbent settings object while executing the postMessage() algorithm. Consider this final, even more convoluted example: button click me button iframe > iframe script const bound frames ]. location assign bind frames ]. location "https://example.com/" ); document querySelector "button" ). addEventListener "click" bound ); script iframe src "a.html" > iframe script const iframe document querySelector "iframe" ); iframe onload function onLoad () iframe contentWindow document querySelector "button" ). click (); }; script Again there are two interesting environment settings objects in play: that of a.html , and that of b.html . When the location.assign() method triggers the Location -object navigate algorithm, what will be the incumbent settings object ? As before, it should intuitively be that of a.html : the click listener was originally scheduled by a.html , so even if something involving b.html causes the listener to fire, the incumbent responsible is that of a.html The callback setup is similar to the previous example: when bound is converted to a Web IDL callback type, the incumbent settings object is that corresponding to a.html which is stored as the callback's callback context When the click() method is called inside b.html , it dispatches click event on the button that is inside a.html . This time, when the prepare to run a callback algorithm executes as part of event dispatch, there is author code on the stack; the topmost script-having execution context is that of the onLoad function, whose skip-when-determining-incumbent counter gets incremented. Additionally, a.html 's environment settings object (stored as the EventHandler 's callback context ) is pushed onto the backup incumbent settings object stack Now, when the Location -object navigate algorithm looks up the incumbent settings object , the topmost script-having execution context is still that of the onLoad function (due to the fact we are using a bound function as the callback). Its skip-when-determining-incumbent counter value is one, however, so we fall back to the backup incumbent settings object stack . This gives us the environment settings object of a.html , as expected. Note that this means that even though it is the iframe inside a.html that navigates, it is a.html itself that is used as the source browsing context , which determines among other things the request client . This is perhaps the only justifiable use of the incumbent concept on the web platform ; in all other cases the consequences of using it are simply confusing and we hope to one day switch them to use current or relevant as appropriate. 8.1.3.3.3 Current The JavaScript specification defines the current Realm Record , sometimes abbreviated to the "current Realm". [JAVASCRIPT] Then, the current settings object is the environment settings object of the current Realm Record Similarly, the current global object is the global object of the current Realm Record 8.1.3.3.4 Relevant The relevant Realm for a platform object is the value of its [[Realm]] field Then, the relevant settings object for a platform object is the environment settings object of the relevant Realm for Similarly, the relevant global object for a platform object is the global object of the relevant Realm for 8.1.3.4 Enabling and disabling scripting Scripting is enabled for an environment settings object settings when all of the following conditions are true: The user agent supports scripting. The user has not disabled scripting for settings at this time. (User agents may provide users with the option to disable scripting globally, or in a finer-grained manner, e.g., on a per-origin basis, down to the level of individual environment settings objects .) Either settings 's global object is not a Window object, or settings 's global object 's associated Document 's active sandboxing flag set does not have its sandboxed scripts browsing context flag set. Scripting is disabled for an environment settings object when scripting is not enabled for it, i.e., when any of the above conditions are false. Scripting is enabled for a node node if node 's node document 's browsing context is non-null, and scripting is enabled for node 's relevant settings object Scripting is disabled for a node when scripting is not enabled , i.e., when its node document 's browsing context is null or when scripting is disabled for its relevant settings object 8.1.3.5 Secure contexts An environment environment is a secure context if the following algorithm returns true: If environment is an environment settings object , then: Let global be environment 's global object If global is a WorkerGlobalScope , then: If global 's owner set [0]'s relevant settings object is a secure context , then return true. We only need to check the 0th item since they will necessarily all be consistent. Return false. If global is a WorkletGlobalScope , then return true. Worklets can only be created in secure contexts. If the result of Is url potentially trustworthy? given environment 's top-level creation URL is " Potentially Trustworthy ", then return true. Return false. An environment is a non-secure context if it is not a secure context 8.1.4 Script processing model 8.1.4.1 Scripts script is one of two possible structs . All scripts have: settings object An environment settings object , containing various settings that are shared with other scripts in the same context. record Either a Script Record , for classic scripts ; a Source Text Module Record , for module scripts ; or null. In the former two cases, it represents a parsed script; null represents a failure parsing. parse error A JavaScript value, which has meaning only if the record is null, indicating that the corresponding script source text could not be parsed. This value is used for internal tracking of immediate parse errors when creating scripts , and is not to be used directly. Instead, consult the error to rethrow when determining "what went wrong" for this script. An error to rethrow A JavaScript value representing an error that will prevent evaluation from succeeding. It will be re-thrown by any attempts to run the script. This could be the script's parse error , but in the case of a module script it could instead be the parse error from one of its dependencies, or an error from resolve a module specifier Since this exception value is provided by the JavaScript specification, we know that it is never null, so we use null to signal that no error has occurred. Fetch options script fetch options , containing various options related to fetching this script or module scripts that it imports. base URL A base URL used for resolving module specifiers . This will either be the URL from which the script was obtained, for external scripts, or the document base URL of the containing document, for inline scripts. classic script is a type of script that has the following additional item muted errors boolean A boolean which, if true, means that error information will not be provided for errors in this script. This is used to mute errors for cross-origin scripts, since that can leak private information. module script is another type of script . It has no additional items The active script is determined by the following algorithm: Let record be GetActiveScriptOrModule (). If record is null, return null. Return record .[[HostDefined]]. The active script concept is so far only used by the import() feature, to determine the base URL to use for resolving relative module specifiers. 8.1.4.2 Fetching scripts This section introduces a number of algorithms for fetching scripts, taking various necessary inputs and resulting in classic or module scripts Script fetch options is a struct with the following items cryptographic nonce The cryptographic nonce metadata used for the initial fetch and for fetching any imported modules integrity metadata The integrity metadata used for the initial fetch parser metadata The parser metadata used for the initial fetch and for fetching any imported modules credentials mode The credentials mode used for the initial fetch (for module scripts ) and for fetching any imported modules (for both module scripts and classic scripts referrer policy The referrer policy used for the initial fetch and for fetching any imported modules Recall that via the import() feature, classic scripts can import module scripts The default classic script fetch options are a script fetch options whose cryptographic nonce is the empty string, integrity metadata is the empty string, parser metadata is " not-parser-inserted ", credentials mode is " same-origin ", and referrer policy is the empty string. Given a request request and a script fetch options options , we define: set up the classic script request Set request 's cryptographic nonce metadata to options 's cryptographic nonce , its integrity metadata to options 's integrity metadata , its parser metadata to options 's parser metadata , and its referrer policy to options 's referrer policy set up the module script request Set request 's cryptographic nonce metadata to options 's cryptographic nonce , its integrity metadata to options 's integrity metadata , its parser metadata to options 's parser metadata , its credentials mode to options 's credentials mode , and its referrer policy to options 's referrer policy For any given script fetch options options , the descendant script fetch options are a new script fetch options whose items all have the same values, except for the integrity metadata , which is instead the empty string. The algorithms below can be customized by optionally supplying a custom perform the fetch hook, which takes a request and an is top-level flag. The algorithm must complete with a response (which may be a network error ), either synchronously (when using fetch a classic worker-imported script ) or asynchronously (otherwise). The is top-level flag will be set for all classic script fetches, and for the initial fetch when fetching an external module script graph fetching a module worker script graph , or fetching an import() module script graph , but not for the fetches resulting from import statements encountered throughout the graph. By default, not supplying the perform the fetch will cause the below algorithms to simply fetch the given request , with algorithm-specific customizations to the request and validations of the resulting response To layer your own customizations on top of these algorithm-specific ones, supply a perform the fetch hook that modifies the given request fetches it, and then performs specific validations of the resulting response (completing with a network error if the validations fail). The hook can also be used to perform more subtle customizations, such as keeping a cache of responses and avoiding performing a fetch at all. Service Workers is an example of a specification that runs these algorithms with its own options for the hook. [SW] Now for the algorithms themselves. To fetch a classic script given a url , a settings object , some options , a CORS setting , and a character encoding , run these steps. The algorithm will asynchronously complete with either null (on failure) or a new classic script (on success). Let request be the result of creating a potential-CORS request given url , " script ", and CORS setting Set request 's client to settings object Set up the classic script request given request and options If the caller specified custom steps to perform the fetch , perform them on request , with the is top-level flag set. Return from this algorithm, and when the custom perform the fetch steps complete with response response , run the remaining steps. Otherwise, fetch request . Return from this algorithm, and run the remaining steps as part of the fetch's process response for the response response response can be either CORS-same-origin or CORS-cross-origin . This only affects how error reporting happens. Set response to response 's unsafe response If response 's type is " error ", or response 's status is not an ok status , then asynchronously complete this algorithm with null, and return. For historical reasons, this algorithm does not include MIME type checking, unlike the other script-fetching algorithms in this section. If response 's Content Type metadata , if any, specifies a character encoding, and the user agent supports that encoding, then set character encoding to that encoding (ignoring the passed-in value). Let source text be the result of decoding response 's body to Unicode, using character encoding as the fallback encoding. The decode algorithm overrides character encoding if the file contains a BOM. Let muted errors be true if response was CORS-cross-origin , and false otherwise. Let script be the result of creating a classic script given source text settings object response 's url options , and muted errors Asynchronously complete this algorithm with script To fetch a classic worker script given a url , a fetch client settings object , a destination , and a script settings object , run these steps. The algorithm will asynchronously complete with either null (on failure) or a new classic script (on success). Let request be a new request whose url is url client is fetch client settings object destination is destination mode is " same-origin ", credentials mode is " same-origin ", parser metadata is " not parser-inserted ", and whose use-URL-credentials flag is set. If the caller specified custom steps to perform the fetch , perform them on request , with the is top-level flag set. Return from this algorithm, and when the custom perform the fetch steps complete with response response , run the remaining steps. Otherwise, fetch request . Return from this algorithm, and run the remaining steps as part of the fetch's process response for the response response Set response to response 's unsafe response If either of the following conditions are met: response 's type is " error "; or response 's status is not an ok status then asynchronously complete this algorithm with null, and return. If both of the following conditions are met: response 's url 's scheme is an HTTP(S) scheme ; and the result of extracting a MIME type from response 's header list is not a JavaScript MIME type then asynchronously complete this algorithm with null, and return. Other fetch schemes are exempted from MIME type checking for historical web-compatibility reasons. We might be able to tighten this in the future; see issue #3255 Let source text be the result of UTF-8 decoding response 's body Let script be the result of creating a classic script using source text script settings object response 's url , and the default classic script fetch options Asynchronously complete this algorithm with script To fetch a classic worker-imported script given a url and a settings object , run these steps. The algorithm will synchronously complete with a classic script on success, or throw an exception on failure. Let request be a new request whose url is url client is settings object destination is " script ", parser metadata is " not parser-inserted ", synchronous flag is set, and whose use-URL-credentials flag is set. If the caller specified custom steps to perform the fetch , perform them on request , with the is top-level flag set. Let response be the result. Otherwise, fetch request , and let response be the result. Unlike other algorithms in this section, the fetching process is synchronous here. Thus any perform the fetch steps will also finish their work synchronously. Set response to response 's unsafe response If any of the following conditions are met: response 's type is " error "; or response 's status is not an ok status ; or the result of extracting a MIME type from response 's header list is not a JavaScript MIME type then throw a NetworkError DOMException Let source text be the result of UTF-8 decoding response 's body Let muted errors be true if response was CORS-cross-origin , and false otherwise. Let script be the result of creating a classic script given source text settings object response 's url , the default classic script fetch options and muted errors Return script To fetch an external module script graph given a url , a settings object , and some options , run these steps. The algorithm will asynchronously complete with either null (on failure) or a module script (on success). Fetch a single module script given url settings object , " script ", options settings object client ", and with the top-level module fetch flag set. If the caller of this algorithm specified custom perform the fetch steps, pass those along as well. Wait until the algorithm asynchronously completes with result If result is null, asynchronously complete this algorithm with null, and return. Let visited set be « url ». Fetch the descendants of and link result given settings object destination , and visited set . When this asynchronously completes with final result , asynchronously complete this algorithm with final result To fetch an import() module script graph given a specifier , a base URL , a settings object , and some options , run these steps. The algorithm will asynchronously complete with either null (on failure) or a module script (on success). Let url be the result of resolving a module specifier given base URL and specifier If url is failure, then asynchronously complete this algorithm with null, and return. Fetch a single module script given url settings object , " script ", options settings object client ", and with the top-level module fetch flag set. If the caller of this algorithm specified custom perform the fetch steps, pass those along as well. Wait until the algorithm asynchronously completes with result If result is null, asynchronously complete this algorithm with null, and return. Let visited set be « url ». Fetch the descendants of and link result given settings object destination , and visited set . When this asynchronously completes with final result , asynchronously complete this algorithm with final result To fetch a modulepreload module script graph given a url , a destination , a settings object , and some options , run these steps. The algorithm will asynchronously complete with either null (on failure) or a module script (on success), although it will perform optional steps even after completing. Fetch a single module script given url settings object destination options settings object , " client ", and with the top-level module fetch flag set. Wait until algorithm asynchronously completes with result Asynchronously complete this algorithm with result , but do not return. If result is not null, optionally perform the following steps: Let visited set be « url ». Fetch the descendants of and link result given settings object destination , and visited set Generally, performing these steps will be beneficial for performance, as it allows pre-loading the modules that will invariably be requested later, via algorithms such as fetch an external module script graph that fetch the entire graph. However, user agents might wish to skip them in bandwidth-constrained situations, or situations where the relevant fetches are already in flight. To fetch an inline module script graph given a source text base URL settings object , and options , run these steps. The algorithm will asynchronously complete with either null (on failure) or a module script (on success). Let script be the result of creating a module script using source text settings object base URL , and options If script is null, asynchronously complete this algorithm with null, and return. Let visited set be an empty set Fetch the descendants of and link script , given settings object , the destination " script ", and visited set . When this asynchronously completes with final result , asynchronously complete this algorithm with final result To fetch a module worker script graph given a url , a fetch client settings object , a destination , a credentials mode , and a module map settings object fetch a worklet/module worker script graph given url fetch client settings object destination credentials mode , and module map settings object , asynchronously completing with the asynchronous completion result of that algorithm. To fetch a worklet script graph given a url , a fetch client settings object , a destination , a credentials mode , a module map settings object , and a module responses map fetch a worklet/module worker script graph given url fetch client settings object destination credentials mode , and module map settings object asynchronously completing with the asynchronous completion result of that algorithm. Use the following custom steps to perform the fetch given response Let requestURL be request 's url If moduleResponsesMap requestURL ] is " fetching ", wait in parallel until that entry's value changes, then queue a task on the networking task source to proceed with running the following steps. If moduleResponsesMap requestURL exists , then asynchronously complete the perform the fetch steps with moduleResponsesMap requestURL ]. Set moduleResponsesMap requestURL ] to fetching ". Fetch request . To process response for the response response Set moduleResponsesMap requestURL ] to response Asynchronously complete the perform the fetch steps with response The following algorithms are meant for internal use by this specification only as part of fetching an external module script graph or other similar concepts above, and should not be used directly by other specifications. This diagram illustrates how these algorithms relate to the ones above, as well as to each other: To fetch a worklet/module worker script graph given a url , a fetch client settings object , a destination , a credentials mode , and a module map settings object , run these steps. The algorithm will asynchronously complete with either null (on failure) or a module script (on success). Let options be a script fetch options whose cryptographic nonce is the empty string, integrity metadata is the empty string, parser metadata is " not-parser-inserted ", credentials mode is credentials mode , and referrer policy is the empty string. Fetch a single module script given url fetch client settings object destination options module map settings object client ", and with the top-level module fetch flag set. If the caller of this algorithm specified custom perform the fetch steps, pass those along as well. Wait until the algorithm asynchronously completes with result If result is null, asynchronously complete this algorithm with null, and return. Let visited set be « url ». Fetch the descendants of and link result given fetch client settings object destination , and visited set . When this asynchronously completes with final result , asynchronously complete this algorithm with final result To fetch the descendants of and link a module script module script , given a fetch client settings object , a destination , and a visited set , run these steps. The algorithm will asynchronously complete with either null (on failure) or with module script (on success). Fetch the descendants of module script , given fetch client settings object destination and visited set Return from this algorithm, and run the following steps when fetching the descendants of a module script asynchronously completes with result If result is null, then asynchronously complete this algorithm with result In this case, there was an error fetching one or more of the descendants. We will not attempt to link. Let parse error be the result of finding the first parse error given result If parse error is null, then: Let record be result 's record Perform record Link (). This step will recursively call Link on all of the module's unlinked dependencies. If this throws an exception, set result 's error to rethrow to that exception. Otherwise, set result 's error to rethrow to parse error Asynchronously complete this algorithm with result To fetch the descendants of a module script module script , given a fetch client settings object , a destination , and a visited set run these steps. The algorithm will asynchronously complete with either null (on failure) or with module script (on success). If module script 's record is null, then asynchronously complete this algorithm with module script and return. Let record be module script 's record If record is not a Cyclic Module Record , or if record .[[RequestedModules]] is empty asynchronously complete this algorithm with module script Let urls be a new empty list For each string requested of record .[[RequestedModules]], Let url be the result of resolving a module specifier given module script 's base URL and requested Assert: url is never failure, because resolving a module specifier must have been previously successful with these same two arguments. If visited set does not contain url , then: Append url to urls Append url to visited set Let options be the descendant script fetch options for module script 's fetch options Assert: options is not null, as module script is a module script For each url in urls , perform the internal module script graph fetching procedure given url fetch client settings object destination options module script 's settings object visited set , and module script 's base URL . If the caller of this algorithm specified custom perform the fetch steps, pass those along while performing the internal module script graph fetching procedure These invocations of the internal module script graph fetching procedure should be performed in parallel to each other. If any of the invocations of the internal module script graph fetching procedure asynchronously complete with null, asynchronously complete this algorithm with null, and return. Otherwise, wait until all of the internal module script graph fetching procedure invocations have asynchronously completed. Asynchronously complete this algorithm with module script To perform the internal module script graph fetching procedure given a url , a fetch client settings object , a destination , some options , a module map settings object , a visited set , and a referrer , perform these steps. The algorithm will asynchronously complete with either null (on failure) or a module script (on success). Assert: visited set contains url Fetch a single module script given url fetch client settings object destination options module map settings object referrer , and with the top-level module fetch flag unset. If the caller of this algorithm specified custom perform the fetch steps, pass those along while fetching a single module script Return from this algorithm, and run the following steps when fetching a single module script asynchronously completes with result If result is null, asynchronously complete this algorithm with null, and return. Fetch the descendants of result given fetch client settings object destination , and visited set When the appropriate algorithm asynchronously completes with final result asynchronously complete this algorithm with final result To fetch a single module script , given a url , a fetch client settings object , a destination , some options , a module map settings object , a referrer , and a top-level module fetch flag, run these steps. The algorithm will asynchronously complete with either null (on failure) or a module script (on success). Let moduleMap be module map settings object 's module map If moduleMap url ] is " fetching ", wait in parallel until that entry's value changes, then queue a task on the networking task source to proceed with running the following steps. If moduleMap url exists asynchronously complete this algorithm with moduleMap url ], and return. Set moduleMap url ] to " fetching ". Let request be a new request whose url is url destination is destination mode is " cors ", referrer is referrer , and client is fetch client settings object If destination is " worker ", " sharedworker ", or " serviceworker ", and the top-level module fetch flag is set, then set request 's mode to " same-origin ". Set up the module script request given request and options If the caller specified custom steps to perform the fetch , perform them on request , setting the is top-level flag if the top-level module fetch flag is set. Return from this algorithm, and when the custom perform the fetch steps complete with response response , run the remaining steps. Otherwise, fetch request . Return from this algorithm, and run the remaining steps as part of the fetch's process response for the response response response is always CORS-same-origin If any of the following conditions are met: response 's type is " error "; or response 's status is not an ok status ; or the result of extracting a MIME type from response 's header list is not a JavaScript MIME type then set moduleMap url ] to null, asynchronously complete this algorithm with null, and return. Let source text be the result of UTF-8 decoding response 's body Let module script be the result of creating a module script given source text module map settings object response 's url , and options Set moduleMap url ] to module script , and asynchronously complete this algorithm with module script It is intentional that the module map is keyed by the request URL , whereas the base URL for the module script is set to the response URL . The former is used to deduplicate fetches, while the latter is used for URL resolution. To find the first parse error given a root moduleScript and an optional discoveredSet Let moduleMap be moduleScript 's settings object 's module map If discoveredSet was not given, let it be an empty set Append moduleScript to discoveredSet If moduleScript 's record is null, then return moduleScript 's parse error Let childSpecifiers be the value of moduleScript 's record 's [[RequestedModules]] internal slot. Let childURLs be the list obtained by calling resolve a module specifier once for each item of childSpecifiers , given moduleScript 's base URL and that item. (None of these will ever fail, as otherwise moduleScript would have been marked as itself having a parse error .) Let childModules be the list obtained by getting each value in moduleMap whose key is given by an item of childURLs For each childModule of childModules Assert: childModule is a module script (i.e., it is not " fetching " or null); by now all module scripts in the graph rooted at moduleScript will have successfully been fetched. If discoveredSet already contains childModule continue Let childParseError be the result of finding the first parse error given childModule and discoveredSet If childParseError is not null, return childParseError Return null. 8.1.4.3 Creating scripts To create a classic script , given a string source , an environment settings object settings , a URL baseURL , some script fetch options options , and an optional muted errors boolean: If muted errors was not provided, let it be false. If muted errors is true, then set baseURL to about:blank When muted errors is true, baseURL is the script's CORS-cross-origin response 's url , which shouldn't be exposed to JavaScript. Therefore, baseURL is sanitized here. If scripting is disabled for settings , then set source to the empty string. Let script be a new classic script that this algorithm will subsequently initialize. Set script 's settings object to settings Set script 's base URL to baseURL Set script 's fetch options to options Set script 's muted errors to muted errors Set script 's parse error and error to rethrow to null. Let result be ParseScript source settings 's Realm script ). Passing script as the last parameter here ensures result .[[HostDefined]] will be script If result is a list of errors, then: Set script 's parse error and its error to rethrow to result [0]. Return script Set script 's record to result Return script To create a module script , given a string source , an environment settings object settings , a URL baseURL , and some script fetch options options If scripting is disabled for settings , then set source to the empty string. Let script be a new module script that this algorithm will subsequently initialize. Set script 's settings object to settings Set script 's base URL to baseURL Set script 's fetch options to options Set script 's parse error and error to rethrow to null. Let result be ParseModule source settings 's Realm script ). Passing script as the last parameter here ensures result .[[HostDefined]] will be script If result is a list of errors, then: Set script 's parse error to result [0]. Return script For each string requested of result .[[RequestedModules]]: Let url be the result of resolving a module specifier given script 's base URL and requested If url is failure, then: Let error be a new TypeError exception. Set script 's parse error to error Return script This step is essentially validating all of the requested module specifiers. We treat a module with unresolvable module specifiers the same as one that cannot be parsed; in both cases, a syntactic issue makes it impossible to ever contemplate linking the module later. Set script 's record to result Return script 8.1.4.4 Calling scripts To run a classic script given a classic script script and an optional boolean rethrow errors (default false): Let settings be the settings object of script Check if we can run script with settings . If this returns "do not run" then return NormalCompletion (empty). Prepare to run script given settings Let evaluationStatus be null. If script 's error to rethrow is not null, then set evaluationStatus to Completion { [[Type]]: throw, [[Value]]: script 's error to rethrow , [[Target]]: empty }. Otherwise, set evaluationStatus to ScriptEvaluation script 's record ). If ScriptEvaluation does not complete because the user agent has aborted the running script , leave evaluationStatus as null. If evaluationStatus is an abrupt completion , then: If rethrow errors is true and script 's muted errors is false, then: Clean up after running script with settings Rethrow evaluationStatus .[[Value]]. If rethrow errors is true and script 's muted errors is true, then: Clean up after running script with settings Throw a NetworkError DOMException Otherwise, rethrow errors is false. Perform the following steps: Report the exception given by evaluationStatus .[[Value]] for script Clean up after running script with settings Return evaluationStatus Clean up after running script with settings If evaluationStatus is a normal completion, then return evaluationStatus If we've reached this point, evaluationStatus was left as null because the script was aborted prematurely during evaluation. Return Completion { [[Type]]: throw, [[Value]]: a new QuotaExceededError DOMException , [[Target]]: empty }. To run a module script given a module script script and an optional boolean preventErrorReporting (default false): Let settings be the settings object of script Check if we can run script with settings . If this returns "do not run", then return a promise resolved with undefined. Prepare to run script given settings Let evaluationPromise be null. If script 's error to rethrow is not null, then set evaluationPromise to a promise rejected with script 's error to rethrow Otherwise: Let record be script 's record Set evaluationPromise to record Evaluate (). This step will recursively evaluate all of the module's dependencies. If Evaluate fails to complete as a result of the user agent aborting the running script , then set evaluationPromise to a promise rejected with a new QuotaExceededError DOMException If preventErrorReporting is false, then upon rejection of evaluationPromise with reason report the exception given by reason for script Clean up after running script with settings Return evaluationPromise The steps to check if we can run script with an environment settings object settings are as follows. They return either "run" or "do not run". If the global object specified by settings is a Window object whose Document object is not fully active , then return "do not run". If scripting is disabled for settings , then return "do not run". Return "run". The steps to prepare to run script with an environment settings object settings are as follows: Push settings 's realm execution context onto the JavaScript execution context stack ; it is now the running JavaScript execution context Add settings to the currently running task 's script evaluation environment settings object set The steps to clean up after running script with an environment settings object settings are as follows: Assert: settings 's realm execution context is the running JavaScript execution context Remove settings 's realm execution context from the JavaScript execution context stack If the JavaScript execution context stack is now empty, perform a microtask checkpoint . (If this runs scripts, these algorithms will be invoked reentrantly.) These algorithms are not invoked by one script directly calling another, but they can be invoked reentrantly in an indirect manner, e.g. if a script dispatches an event which has event listeners registered. The running script is the script in the [[HostDefined]] field in the ScriptOrModule component of the running JavaScript execution context 8.1.4.5 Killing scripts Although the JavaScript specification does not account for this possibility, it's sometimes necessary to abort a running script . This causes any ScriptEvaluation or Source Text Module Record Evaluate invocations to cease immediately, emptying the JavaScript execution context stack without triggering any of the normal mechanisms like finally blocks. [JAVASCRIPT] User agents may impose resource limitations on scripts, for example CPU quotas, memory limits, total execution time limits, or bandwidth limitations. When a script exceeds a limit, the user agent may either throw a QuotaExceededError DOMException abort the script without an exception, prompt the user, or throttle script execution. For example, the following script never terminates. A user agent could, after waiting for a few seconds, prompt the user to either terminate the script or let it continue. script while true /* loop */ script User agents are encouraged to allow users to disable scripting whenever the user is prompted either by a script (e.g. using the window.alert() API) or because of a script's actions (e.g. because it has exceeded a time limit). If scripting is disabled while a script is executing, the script should be terminated immediately. User agents may allow users to specifically disable scripts just for the purposes of closing a browsing context For example, the prompt mentioned in the example above could also offer the user with a mechanism to just close the page entirely, without running any unload event handlers. 8.1.4.6 Runtime script errors In various scenarios, the user agent can report an exception by firing an error event at the Window . If this event is not canceled, then the error is considered not handled, and can be reported to the developer console. When the user agent is required to report an error for a particular script script with a particular position line col , using a particular target target , it must run these steps, after which the error is either handled or not handled If target is in error reporting mode , then return; the error is not handled Let target be in error reporting mode Let message be an implementation-defined string describing the error in a helpful manner. Let errorValue be the value that represents the error: in the case of an uncaught exception, that would be the value that was thrown; in the case of a JavaScript error that would be an Error object. If there is no corresponding value, then the null value must be used instead. Let urlString be the result of applying the URL serializer to the URL record that corresponds to the resource from which script was obtained. The resource containing the script will typically be the file from which the Document was parsed, e.g. for inline script elements or event handler content attributes ; or the JavaScript file that the script was in, for external scripts. Even for dynamically-generated scripts, user agents are strongly encouraged to attempt to keep track of the original source of a script. For example, if an external script uses the document.write() API to insert an inline script element during parsing, the URL of the resource containing the script would ideally be reported as being the external script, and the line number might ideally be reported as the line with the document.write() call or where the string passed to that call was first constructed. Naturally, implementing this can be somewhat non-trivial. User agents are similarly encouraged to keep careful track of the original line numbers, even in the face of document.write() calls mutating the document as it is parsed, or event handler content attributes spanning multiple lines. If script 's muted errors is true, then set message to Script error. ", urlString to the empty string, line and col to 0, and errorValue to null. Let notHandled be true. If target implements EventTarget , then set notHandled to the result of firing an event named error at target , using ErrorEvent , with the cancelable attribute initialized to true, the message attribute initialized to message , the filename attribute initialized to urlString , the lineno attribute initialized to line , the colno attribute initialized to col , and the error attribute initialized to errorValue Let target no longer be in error reporting mode If notHandled is false, then the error is handled . Otherwise, the error is not handled Returning true in an event handler cancels the event per the event handler processing algorithm When the user agent is to report an exception , the user agent must report the error for the relevant script , with the problematic position (line number and column number) in the resource containing the script, using the global object specified by the script's settings object as the target. If the error is still not handled after this, then the error may be reported to a developer console. The existence of both report an error and report an exception is confusing, and both algorithms have known problems. You can track future cleanup in this area in issue #958 ErrorEvent Support in all current engines. Firefox Yes Safari Yes Chrome 10+ Opera 11+ Edge 79+ Edge (Legacy) 12+ Internet Explorer Yes Firefox Android Yes Safari iOS Yes Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11+ The ErrorEvent interface is defined as follows: Exposed =( Window Worker )] interface ErrorEvent Event constructor DOMString type optional ErrorEventInit eventInitDict = {}); readonly attribute DOMString message readonly attribute USVString filename readonly attribute unsigned long lineno readonly attribute unsigned long colno readonly attribute any error }; dictionary ErrorEventInit EventInit DOMString message = ""; USVString filename = ""; unsigned long lineno = 0; unsigned long colno = 0; any error null }; The message attribute must return the value it was initialized to. It represents the error message. The filename attribute must return the value it was initialized to. It represents the URL of the script in which the error originally occurred. The lineno attribute must return the value it was initialized to. It represents the line number where the error occurred in the script. The colno attribute must return the value it was initialized to. It represents the column number where the error occurred in the script. The error attribute must return the value it was initialized to. Where appropriate, it is set to the object representing the error (e.g., the exception object in the case of an uncaught DOM exception). 8.1.4.7 Unhandled promise rejections Window/rejectionhandled_event Support in all current engines. Firefox 69+ Safari 11+ Chrome 49+ Opera 36+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 🔰 68+ Safari iOS 11.3+ Chrome Android 49+ WebView Android 49+ Samsung Internet 5.0+ Opera Android 36+ In addition to synchronous runtime script errors , scripts may experience asynchronous promise rejections, tracked via the unhandledrejection and rejectionhandled events. Tracking these rejections is done via the HostPromiseRejectionTracker abstract operation, but reporting them is defined here. To notify about rejected promises on a given environment settings object settings object Let list be a copy of settings object 's about-to-be-notified rejected promises list If list is empty, return. Clear settings object 's about-to-be-notified rejected promises list Let global be settings object 's global object Queue a global task on the DOM manipulation task source given global to run the following substep: For each promise in list If 's [[PromiseIsHandled]] internal slot is true, continue to the next iteration of the loop. Let notHandled be the result of firing an event named unhandledrejection at global , using PromiseRejectionEvent , with the cancelable attribute initialized to true, the promise attribute initialized to , and the reason attribute initialized to the value of 's [[PromiseResult]] internal slot. If notHandled is false, then the promise rejection is handled . Otherwise, the promise rejection is not handled If 's [[PromiseIsHandled]] internal slot is false, add to settings object 's outstanding rejected promises weak set This algorithm results in promise rejections being marked as handled or not handled . These concepts parallel handled and not handled script errors. If a rejection is still not handled after this, then the rejection may be reported to a developer console. PromiseRejectionEvent/PromiseRejectionEvent Support in all current engines. Firefox 69+ Safari 11+ Chrome 49+ Opera 36+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 🔰 68+ Safari iOS 11.3+ Chrome Android 49+ WebView Android 49+ Samsung Internet 5.0+ Opera Android 36+ The PromiseRejectionEvent interface is defined as follows: PromiseRejectionEvent Support in all current engines. Firefox 69+ Safari 11+ Chrome 49+ Opera 36+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 🔰 68+ Safari iOS 11.3+ Chrome Android 49+ WebView Android 49+ Samsung Internet 5.0+ Opera Android 36+ Exposed =( Window Worker )] interface PromiseRejectionEvent Event constructor DOMString type PromiseRejectionEventInit eventInitDict ); readonly attribute Promise any promise readonly attribute any reason }; dictionary PromiseRejectionEventInit EventInit required Promise any promise any reason }; PromiseRejectionEvent/promise Support in all current engines. Firefox 69+ Safari 11+ Chrome 49+ Opera 36+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 🔰 68+ Safari iOS 11.3+ Chrome Android 49+ WebView Android 49+ Samsung Internet 5.0+ Opera Android 36+ The promise attribute must return the value it was initialized to. It represents the promise which this notification is about. PromiseRejectionEvent/reason Support in all current engines. Firefox 69+ Safari 11+ Chrome 49+ Opera 36+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 🔰 68+ Safari iOS 11.3+ Chrome Android 49+ WebView Android 49+ Samsung Internet 5.0+ Opera Android 36+ The reason attribute must return the value it was initialized to. It represents the rejection reason for the promise. 8.1.5 JavaScript specification host hooks The JavaScript specification contains a number of implementation-defined abstract operations, that vary depending on the host environment. This section defines them for user agent hosts. 8.1.5.1 HostEnsureCanCompileStrings callerRealm calleeRealm JavaScript contains an implementation-defined HostEnsureCanCompileStrings callerRealm calleeRealm ) abstract operation. User agents must use the following implementation: [JAVASCRIPT] Perform ? EnsureCSPDoesNotBlockStringCompilation callerRealm calleeRealm ). [CSP] 8.1.5.2 HostPromiseRejectionTracker promise operation JavaScript contains an implementation-defined HostPromiseRejectionTracker promise operation ) abstract operation. User agents must use the following implementation: [JAVASCRIPT] Let script be the running script If script 's muted errors is true, terminate these steps. Let settings object be script 's settings object If operation is "reject" Add promise to settings object 's about-to-be-notified rejected promises list If operation is "handle" If settings object 's about-to-be-notified rejected promises list contains promise , then remove promise from that list and return. If settings object 's outstanding rejected promises weak set does not contain promise , then return. Remove promise from settings object 's outstanding rejected promises weak set Let global be settings object 's global object Queue a global task on the DOM manipulation task source given global to fire an event named rejectionhandled at global , using PromiseRejectionEvent , with the promise attribute initialized to promise , and the reason attribute initialized to the value of promise 's [[PromiseResult]] internal slot. 8.1.5.3 Job-related host hooks Reference/Global_Objects/Promise#Incumbent_settings_object_tracking Support in one engine only. Firefox 50+ Safari No Chrome No Opera No Edge No Edge (Legacy) No Internet Explorer No Firefox Android 50+ Safari iOS No Chrome Android No WebView Android No Samsung Internet No Opera Android No The JavaScript specification defines Jobs to be scheduled and run later by the host, as well as JobCallback Records which encapsulate JavaScript functions that are called as part of jobs. The JavaScript specification contains a number of implementation-defined abstract operations that lets the host define how jobs are scheduled and how JobCallbacks are handled. HTML uses these abstract operations to track the incumbent settings object in promises and FinalizationRegistry callbacks by saving and restoring the incumbent settings object and a JavaScript execution context for the active script in JobCallbacks. This section defines them for user agent hosts. 8.1.5.3.1 HostCallJobCallback callback argumentsList JavaScript contains an implementation-defined HostCallJobCallback callback argumentsList ) abstract operation to let hosts restore state when invoking JavaScript callbacks from inside tasks. User agents must use the following implementation: [JAVASCRIPT] Let incumbent settings be callback .[[HostDefined]].[[IncumbentSettings]]. Let script execution context be callback .[[HostDefined]].[[ActiveScriptContext]]. Prepare to run a callback with incumbent settings This affects the incumbent concept while the callback runs. If script execution context is not null, then push script execution context onto the JavaScript execution context stack This affects the active script while the callback runs. Let result be Call callback .[[Callback]], argumentsList ). If script execution context is not null, then pop script execution context from the JavaScript execution context stack Clean up after running a callback with incumbent settings Return result 8.1.5.3.2 HostEnqueueFinalizationRegistryCleanupJob finalizationRegistry JavaScript has the ability to register objects with FinalizationRegistry objects, in order to schedule a cleanup action if they are found to be garbage collected. The JavaScript specification contains an implementation-defined HostEnqueueFinalizationRegistryCleanupJob finalizationRegistry abstract operation to schedule the cleanup action. The timing and occurrence of cleanup work is implementation-defined in the JavaScript specification. User agents might differ in when and whether an object is garbage collected, affecting both whether the return value of the WeakRef.prototype.deref() method is undefined, and whether FinalizationRegistry cleanup callbacks occur. There are well-known cases in popular web browsers where objects are not accessible to JavaScript, but they remain retained by the garbage collector indefinitely. HTML clears kept-alive WeakRef objects in the perform a microtask checkpoint algorithm. Authors would be best off not depending on the timing details of garbage collection implementations. Cleanup actions do not take place interspersed with synchronous JavaScript execution, but rather happen in queued tasks . User agents must use the following implementation: [JAVASCRIPT] Let global be finalizationRegistry .[[Realm]]'s global object Queue a global task on the JavaScript engine task source given global to perform the following steps: Let entry be finalizationRegistry .[[CleanupCallback]].[[Callback]].[[Realm]]'s environment settings object Check if we can run script with entry . If this returns "do not run", then return. Prepare to run script with entry This affects the entry concept while the cleanup callback runs. Let result be the result of performing CleanupFinalizationRegistry finalizationRegistry ). Clean up after running script with entry If result is an abrupt completion , then report the exception given by result .[[Value]]. 8.1.5.3.3 HostEnqueuePromiseJob job realm JavaScript contains an implementation-defined HostEnqueuePromiseJob job realm abstract operation to schedule Promise-related operations. HTML schedules these operations in the microtask queue. User agents must use the following implementation: [JAVASCRIPT] If realm is not null, then let job settings be the settings object for realm . Otherwise, let job settings be null. If realm is not null, it is the Realm of the author code that will run. When job is returned by NewPromiseReactionJob , it is the realm of the promise's handler function. When job is returned by NewPromiseResolveThenableJob , it is the realm of the then function. If realm is null, either no author code will run or author code is guaranteed to throw. For the former, the author may not have passed in code to run, such as in promise.then(null, null) . For the latter, it is because a revoked Proxy was passed. In both cases, all the steps below that would otherwise use job settings get skipped. Queue a microtask on the surrounding agent 's event loop to perform the following steps: If job settings is not null, then check if we can run script with job settings . If this returns "do not run" then return. If job settings is not null, then prepare to run script with job settings This affects the entry concept while the job runs. Let result be job (). job is an abstract closure returned by NewPromiseReactionJob or NewPromiseResolveThenableJob . The promise's handler function when job is returned by NewPromiseReactionJob , and the then function when job is returned by NewPromiseResolveThenableJob , are wrapped in JobCallback Records . HTML saves the incumbent settings object and JavaScript execution context for to the active script in HostMakeJobCallback and restores them in HostCallJobCallback If job settings is not null, then clean up after running script with job settings If result is an abrupt completion , then report the exception given by result .[[Value]]. 8.1.5.3.4 HostMakeJobCallback callable JavaScript contains an implementation-defined HostMakeJobCallback callable ) abstract operation to let hosts attach state to JavaScript callbacks that are called from inside task s. User agents must use the following implementation: [JAVASCRIPT] Let incumbent settings be the incumbent settings object Let active script be the active script Let script execution context be null. If active script is not null, set script execution context to a new JavaScript execution context , with its Function field set to null, its Realm field set to active script 's settings object 's Realm , and its ScriptOrModule set to active script 's record As seen below, this is used in order to propagate the current active script forward to the time when the job callback is invoked. A case where active script is non-null, and saving it in this way is useful, is the following: Promise resolve 'import(`./example.mjs`)' ). then eval ); Without this step (and the steps that use it in HostCallJobCallback ), there would be no active script when the import() expression is evaluated, since eval() is a built-in function that does not originate from any particular script With this step in place, the active script is propagated from the above code into the job, allowing import() to use the original script's base URL appropriately. active script can be null if the user clicks on the following button: button onclick "Promise.resolve('import(`./example.mjs`)').then(eval)" Click me button In this case, the JavaScript function for the event handler will be created by the get the current value of the event handler algorithm, which creates a function with null [[ScriptOrModule]] value. Thus, when the promise machinery calls HostMakeJobCallback , there will be no active script to pass along. As a consequence, this means that when the import() expression is evaluated, there will still be no active script . Fortunately that is handled by our implementations of HostResolveImportedModule and HostImportModuleDynamically , by falling back to using the current settings object 's API base URL Return the JobCallback Record { [[Callback]]: callable [[HostDefined]]: { [[IncumbentSettings]]: incumbent settings , [[ActiveScriptContext]]: script execution context } }. 8.1.5.4 Module-related host hooks The JavaScript specification defines a syntax for modules, as well as some host-agnostic parts of their processing model. This specification defines the rest of their processing model: how the module system is bootstrapped, via the script element with type attribute set to " module ", and how modules are fetched, resolved, and executed. [JAVASCRIPT] Although the JavaScript specification speaks in terms of "scripts" versus "modules", in general this specification speaks in terms of classic scripts versus module scripts , since both of them use the script element. modulePromise import( specifier Returns a promise for the module namespace object for the module script identified by specifier . This allows dynamic importing of module scripts at runtime, instead of statically using the import statement form. The specifier will be resolved relative to the active script 's base URL The returned promise will be rejected if an invalid specifier is given, or if a failure is encountered while fetching or evaluating the resulting module graph. This syntax can be used inside both classic and module scripts . It thus provides a bridge into the module-script world, from the classic-script world. url import . meta . url Returns the active module script 's base URL This syntax can only be used inside module scripts module map is a map of URL records to values that are either a module script null (used to represent failed fetches), or a placeholder value " fetching ". Module maps are used to ensure that imported JavaScript modules are only fetched, parsed, and evaluated once per Document or worker Since module maps are keyed by URL, the following code will create three separate entries in the module map , since it results in three different URLs: import "https://example.com/module.mjs" import "https://example.com/module.mjs#map-buster" import "https://example.com/module.mjs?debug=true" That is, URL queries and fragments can be varied to create distinct entries in the module map ; they are not ignored. Thus, three separate fetches and three separate module evaluations will be performed. In contrast, the following code would only create a single entry in the module map , since after applying the URL parser to these inputs, the resulting URL records are equal: import "https://example.com/module2.mjs" import "https:example.com/module2.mjs" import "https://///example.com\\module2.mjs" import "https://example.com/foo/../module2.mjs" So in this second example, only one fetch and one module evaluation will occur. Note that this behavior is the same as how shared workers are keyed by their parsed constructor url To resolve a module specifier given a URL base URL and a string specifier , perform the following steps. It will return either a URL record or failure. Apply the URL parser to specifier . If the result is not failure, return the result. If specifier does not start with the character U+002F SOLIDUS ( ), the two-character sequence U+002E FULL STOP, U+002F SOLIDUS ( ./ ), or the three-character sequence U+002E FULL STOP, U+002E FULL STOP, U+002F SOLIDUS ( ../ ), return failure. This restriction is in place so that in the future we can allow custom module loaders to give special meaning to "bare" import specifiers, like import "jquery" or import "web/crypto" . For now any such imports will fail, instead of being treated as relative URLs. Return the result of applying the URL parser to specifier with base URL The following are valid module specifiers according to the above algorithm: http:example.com\pears.js (becomes as step 1 parses with no base URL) //example.com/bananas ./strawberries.mjs.cgi ../lychees /limes.jsx data:text/javascript,export default 'grapes'; blob:https://whatwg.org/d0360e2f-caee-469f-9a2f-87d5b0456f6f The following are valid module specifiers according to the above algorithm, but will invariably cause failures when they are fetched javascript:export default 'artichokes'; data:text/plain,export default 'kale'; about:legumes wss://example.com/celery The following are not valid module specifiers according to the above algorithm: pumpkins.js .tomato ..zucchini.mjs .\yam.es 8.1.5.4.1 HostGetImportMetaProperties moduleRecord Reference/Statements/import.meta Support in all current engines. Firefox 62+ Safari 11.1+ Chrome 64+ Opera 51+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 62+ Safari iOS 12+ Chrome Android 64+ WebView Android 64+ Samsung Internet 9.0+ Opera Android 47+ JavaScript contains an implementation-defined HostGetImportMetaProperties abstract operation. User agents must use the following implementation: [JAVASCRIPT] Let module script be moduleRecord .[[HostDefined]]. Let urlString be module script 's base URL serialized Return « Record { [[Key]]: "url", [[Value]]: urlString } ». 8.1.5.4.2 HostImportModuleDynamically referencingScriptOrModule specifier promiseCapability JavaScript contains an implementation-defined HostImportModuleDynamically abstract operation. User agents must use the following implementation: [JAVASCRIPT] Let settings object be the current settings object If settings object 's global object implements WorkletGlobalScope or ServiceWorkerGlobalScope , then: Let completion be Completion { [[Type]]: throw, [[Value]]: a new TypeError , [[Target]]: empty }. Perform FinishDynamicImport referencingScriptOrModule specifier promiseCapability completion ). Return. Let base URL be settings object 's API base URL Let fetch options be the default classic script fetch options If referencingScriptOrModule is not null, then: Let referencing script be referencingScriptOrModule .[[HostDefined]]. Set settings object to referencing script 's settings object Set base URL to referencing script 's base URL Set fetch options to the descendant script fetch options for referencing script 's fetch options As explained above for HostResolveImportedModule , in the common case, referencingScriptOrModule is non-null. Fetch an import() module script graph given specifier base URL settings object , and fetch options . Wait until the algorithm asynchronously completes with result Let promise be null. If result is null, then set promise to a promise rejected with a new TypeError Otherwise, set promise to the result of running a module script given result and true. Perform FinishDynamicImport referencingScriptOrModule specifier promiseCapability promise ). Return undefined. 8.1.5.4.3 HostResolveImportedModule referencingScriptOrModule specifier JavaScript contains an implementation-defined HostResolveImportedModule abstract operation. User agents must use the following implementation: [JAVASCRIPT] Let settings object be the current settings object Let base URL be settings object 's API base URL If referencingScriptOrModule is not null, then: Let referencing script be referencingScriptOrModule .[[HostDefined]]. Set settings object to referencing script 's settings object Set base URL to referencing script 's base URL referencingScriptOrModule is not usually null, but will be so for event handlers per the get the current value of the event handler algorithm. For example, given: button onclick "import('./foo.mjs')" Click me button If a click event occurs, then at the time the import() expression runs, GetActiveScriptOrModule will return null, which will be passed to this abstract operation when HostResolveImportedModule is called by FinishDynamicImport Let moduleMap be settings object 's module map Let url be the result of resolving a module specifier given base URL and specifier Assert: url is never failure, because resolving a module specifier must have been previously successful with these same two arguments (either while creating the corresponding module script , or in fetch an import() module script graph ). Let resolved module script be moduleMap url ]. (This entry must exist for us to have gotten to this point.) Assert: resolved module script is a module script (i.e., is not null or " fetching "). Assert: resolved module script 's record is not null. Return resolved module script 's record 8.1.6 Event loops 8.1.6.1 Definitions To coordinate events, user interaction, scripts, rendering, networking, and so forth, user agents must use event loops as described in this section. Each agent has an associated event loop , which is unique to that agent. The event loop of a similar-origin window agent is known as a window event loop . The event loop of a dedicated worker agent shared worker agent , or service worker agent is known as a worker event loop . And the event loop of a worklet agent is known as a worklet event loop Event loops do not necessarily correspond to implementation threads. For example, multiple window event loops could be cooperatively scheduled in a single thread. However, for the various worker agents that are allocated with [[CanBlock]] set to true, the JavaScript specification does place requirements on them regarding forward progress , which effectively amount to requiring dedicated per-agent threads in those cases. An event loop has one or more task queues . A task queue is a set of tasks Task queues are sets not queues , because step one of the event loop processing model grabs the first runnable task from the chosen queue, instead of dequeuing the first task. The microtask queue is not a task queue Tasks encapsulate algorithms that are responsible for such work as: Events Dispatching an Event object at a particular EventTarget object is often done by a dedicated task. Not all events are dispatched using the task queue ; many are dispatched during other tasks. Parsing The HTML parser tokenizing one or more bytes, and then processing any resulting tokens, is typically a task. Callbacks Calling a callback is often done by a dedicated task. Using a resource When an algorithm fetches a resource, if the fetching occurs in a non-blocking fashion then the processing of the resource once some or all of the resource is available is performed by a task. Reacting to DOM manipulation Some elements have tasks that trigger in response to DOM manipulation, e.g. when that element is inserted into the document Formally, a task is a struct which has: Steps A series of steps specifying the work to be done by the task. source One of the task sources , used to group and serialize related tasks. document Document associated with the task, or null for tasks that are not in a window event loop script evaluation environment settings object set set of environment settings objects used for tracking script evaluation during the task. task is runnable if its document is either null or fully active Per its source field, each task is defined as coming from a specific task source . For each event loop , every task source must be associated with a specific task queue Essentially, task sources are used within standards to separate logically-different types of tasks, which a user agent might wish to distinguish between. Task queues are used by user agents to coalesce task sources within a given event loop For example, a user agent could have one task queue for mouse and key events (to which the user interaction task source is associated), and another to which all other task sources are associated. Then, using the freedom granted in the initial step of the event loop processing model , it could give keyboard and mouse events preference over other tasks three-quarters of the time, keeping the interface responsive but not starving other task queues. Note that in this setup, the processing model still enforces that the user agent would never process events from any one task source out of order. Each event loop has a currently running task , which is either a task or null. Initially, this is null. It is used to handle reentrancy. Each event loop has a microtask queue , which is a queue of microtasks , initially empty. A microtask is a colloquial way of referring to a task that was created via the queue a microtask algorithm. Each event loop has a performing a microtask checkpoint boolean, which is initially false. It is used to prevent reentrant invocation of the perform a microtask checkpoint algorithm. 8.1.6.2 Queuing tasks To queue a task on a task source source , which performs a series of steps steps , optionally given an event loop event loop and a document document If event loop was not given, set event loop to the implied event loop If document was not given, set document to the implied document Let task be a new task Set task 's steps to steps Set task 's source to source Set task 's document to the document Set task 's script evaluation environment settings object set to an empty set Let queue be the task queue to which source is associated on event loop Append task to queue Failing to pass an event loop and document to queue a task means relying on the ambiguous and poorly-specified implied event loop and implied document concepts. Specification authors should either always pass these values, or use the wrapper algorithms queue a global task or queue an element task instead. Using the wrapper algorithms is recommended. To queue a global task on a task source source , with global object global and a series of steps steps Let event loop be global 's relevant agent 's event loop Let document be global 's associated Document , if global is Window object; otherwise null. Queue a task given source event loop document , and steps To queue an element task on a task source source with an element element and a series of steps steps Let global be element 's relevant global object Queue a global task given source global , and steps To queue a microtask which performs a series of steps steps optionally given an event loop event loop and a document document If event loop was not given, set event loop to the implied event loop If document was not given, set document to the implied document Let microtask be a new task Set microtask 's steps to steps Set microtask 's source to the microtask task source Set microtask 's document to document Set task 's script evaluation environment settings object set to an empty set Enqueue task on event loop 's microtask queue It is possible for a microtask to be moved to a regular task queue , if, during its initial execution, it spins the event loop . This is the only case in which the source document and script evaluation environment settings object set of the microtask are consulted; they are ignored by the perform a microtask checkpoint algorithm. The implied event loop when queuing a task is the one that can deduced from the context of the calling algorithm. This is generally unambiguous, as most specification algorithms only ever involve a single agent (and thus a single event loop ). The exception is algorithms involving or specifying cross-agent communication (e.g., between a window and a worker); for those cases, the implied event loop concept must not be relied upon and specifications must explicitly provide an event loop when queuing a task or microtask The implied document when queuing a task on an event loop event loop is determined as follows: If event loop is not a window event loop , then return null. If the task is being queued in the context of an element, then return the element's node document If the task is being queued in the context of a browsing context , then return the browsing context's active document If the task is being queued by or for a script , then return the script's settings object 's responsible document Assert: this step is never reached, because one of the previous conditions must be true. Really? Both implied event loop and implied document are vaguely-defined and have a lot of action-at-a-distance. The hope is to remove these, especially implied document . See issue #4980 8.1.6.3 Processing model An event loop must continually run through the following steps for as long as it exists: Let taskQueue be one of the event loop 's task queues , chosen in an implementation-defined manner, with the constraint that the chosen task queue must contain at least one runnable task . If there is no such task queue, then jump to the microtasks step below. Remember that the microtask queue is not a task queue so it will not be chosen in this step. However, a task queue to which the microtask task source is associated might be chosen in this step. In that case, the task chosen in the next step was originally a microtask , but it got moved as part of spinning the event loop Let oldestTask be the first runnable task in taskQueue , and remove it from taskQueue Set the event loop 's currently running task to oldestTask Let taskStartTime be the current high resolution time Perform oldestTask 's steps Set the event loop 's currently running task back to null. Microtasks Perform a microtask checkpoint Let hasARenderingOpportunity be false. Let now be the current high resolution time [HRT] Report the task 's duration by performing the following steps: Let top-level browsing contexts be an empty set For each environment settings object settings of oldestTask 's script evaluation environment settings object set append setting 's top-level browsing context to top-level browsing contexts Report long tasks , passing in taskStartTime now (the end time of the task), top-level browsing contexts , and oldestTask Update the rendering : if this is a window event loop then: Let docs be all Document objects whose relevant agent 's event loop is this event loop, sorted arbitrarily except that the following conditions must be met: Any Document whose browsing context 's container document is must be listed after in the list. If there are two documents and whose browsing contexts are both child browsing contexts whose container documents are another Document , then the order of and in the list must match the shadow-including tree order of their respective browsing context containers in 's node tree In the steps below that iterate over docs , each Document must be processed in the order it is found in the list. Rendering opportunities : Remove from docs all Document objects whose browsing context do not have a rendering opportunity browsing context has a rendering opportunity if the user agent is currently able to present the contents of the browsing context to the user, accounting for hardware refresh rate constraints and user agent throttling for performance reasons, but considering content presentable even if it's outside the viewport. Browsing context rendering opportunities are determined based on hardware constraints such as display refresh rates and other factors such as page performance or whether the page is in the background. Rendering opportunities typically occur at regular intervals. This specification does not mandate any particular model for selecting rendering opportunities. But for example, if the browser is attempting to achieve a 60Hz refresh rate, then rendering opportunities occur at a maximum of every 60th of a second (about 16.7ms). If the browser finds that a browsing context is not able to sustain this rate, it might drop to a more sustainable 30 rendering opportunities per second for that browsing context , rather than occasionally dropping frames. Similarly, if a browsing context is not visible, the user agent might decide to drop that page to a much slower 4 rendering opportunities per second, or even less. If docs is not empty, then set hasARenderingOpportunity to true. Unnecessary rendering : Remove from docs all Document objects which meet both of the following conditions: The user agent believes that updating the rendering of the Document 's browsing context would have no visible effect, and The Document 's map of animation frame callbacks is empty. Remove from docs all Document objects for which the user agent believes that it's preferrable to skip updating the rendering for other reasons. The step labeled Rendering opportunities prevents the user agent from updating the rendering when it is unable to present new content to the user (there's no rendering opportunity ). The step labeled Unnecessary rendering prevents the user agent from updating the rendering when there's no new content to draw. This step enables the user agent to prevent the steps below from running for other reasons, for example, to ensure certain tasks are executed immediately after each other, with only microtask checkpoints interleaved (and without, e.g., animation frame callbacks interleaved). Concretely, a user agent might wish to coalesce timer callbacks together, with no intermediate rendering updates. For each fully active Document in docs flush autofocus candidates for that Document if its browsing context is a top-level browsing context For each fully active Document in docs run the resize steps for that Document , passing in now as the timestamp. [CSSOMVIEW] For each fully active Document in docs run the scroll steps for that Document , passing in now as the timestamp. [CSSOMVIEW] For each fully active Document in docs evaluate media queries and report changes for that Document , passing in now as the timestamp. [CSSOMVIEW] For each fully active Document in docs update animations and send events for that Document , passing in now as the timestamp. [WEBANIMATIONS] For each fully active Document in docs run the fullscreen steps for that Document , passing in now as the timestamp. [FULLSCREEN] For each fully active Document in docs run the animation frame callbacks for that Document , passing in now as the timestamp. For each fully active Document in docs run the update intersection observations steps for that Document , passing in now as the timestamp. [INTERSECTIONOBSERVER] Invoke the mark paint timing algorithm for each Document object in docs For each fully active Document in docs , update the rendering or user interface of that Document and its browsing context to reflect the current state. If all of the following are true this is a window event loop there is no task in this event loop 's task queues whose document is fully active this event loop 's microtask queue is empty hasARenderingOpportunity is false then for each Window object whose relevant agent 's event loop is this event loop, run the start an idle period algorithm , passing the Window [REQUESTIDLECALLBACK] If this is a worker event loop , then: If this event loop 's agent 's single realm 's global object is a supported DedicatedWorkerGlobalScope and the user agent believes that it would benefit from having its rendering updated at this time, then: Let now be the current high resolution time [HRT] Run the animation frame callbacks for that DedicatedWorkerGlobalScope , passing in now as the timestamp. Update the rendering of that dedicated worker to reflect the current state. Similar to the notes for updating the rendering in a window event loop , a user agent can determine the rate of rendering in the dedicated worker. If there are no tasks in the event loop 's task queues and the WorkerGlobalScope object's closing flag is true, then destroy the event loop , aborting these steps, resuming the run a worker steps described in the Web workers section below. When a user agent is to perform a microtask checkpoint If the event loop 's performing a microtask checkpoint is true, then return. Set the event loop 's performing a microtask checkpoint to true. While the event loop 's microtask queue is not empty Let oldestMicrotask be the result of dequeuing from the event loop 's microtask queue Set the event loop 's currently running task to oldestMicrotask Run oldestMicrotask This might involve invoking scripted callbacks, which eventually calls the clean up after running script steps, which call this perform a microtask checkpoint algorithm again, which is why we use the performing a microtask checkpoint flag to avoid reentrancy. Set the event loop 's currently running task back to null. For each environment settings object whose responsible event loop is this event loop notify about rejected promises on that environment settings object Cleanup Indexed Database transactions Perform ClearKeptObjects (). When WeakRef.prototype.deref() returns an object, that object is kept alive until the next invocation of ClearKeptObjects (), after which it is again subject to garbage collection. Set the event loop 's performing a microtask checkpoint to false. When an algorithm running in parallel is to await a stable state , the user agent must queue a microtask that runs the following steps, and must then stop executing (execution of the algorithm resumes when the microtask is run, as described in the following steps): Run the algorithm's synchronous section Resumes execution of the algorithm in parallel , if appropriate, as described in the algorithm's steps. Steps in synchronous sections are marked with ⌛. Algorithm steps that say to spin the event loop until a condition goal is met are equivalent to substituting in the following algorithm steps: Let task be the event loop 's currently running task task could be a microtask Let task source be task 's source Let old stack be a copy of the JavaScript execution context stack Empty the JavaScript execution context stack Perform a microtask checkpoint If task is a microtask this step will be a no-op due to performing a microtask checkpoint being true. In parallel Wait until the condition goal is met. Queue a task on task source to: Replace the JavaScript execution context stack with old stack Perform any steps that appear after this spin the event loop instance in the original algorithm. This resumes task Stop task , allowing whatever algorithm that invoked it to resume. This causes the event loop 's main set of steps or the perform a microtask checkpoint algorithm to continue. Unlike other algorithms in this and other specifications, which behave similar to programming-language function calls, spin the event loop is more like a macro, which saves typing and indentation at the usage site by expanding into a series of steps and operations. An algorithm whose steps are: Do something. Spin the event loop until awesomeness happens. Do something else. is a shorthand which, after "macro expansion", becomes Do something. Let old stack be a copy of the JavaScript execution context stack Empty the JavaScript execution context stack Perform a microtask checkpoint In parallel Wait until awesomeness happens. Queue a task on the task source in which "do something" was done to: Replace the JavaScript execution context stack with old stack Do something else. Here is a more full example of the substitution, where the event loop is spun from inside a task that is queued from work in parallel. The version using spin the event loop In parallel Do parallel thing 1. Queue a task on the DOM manipulation task source to: Do task thing 1. Spin the event loop until awesomeness happens. Do task thing 2. Do parallel thing 2. The fully expanded version: In parallel Do parallel thing 1. Let old stack be null. Queue a task on the DOM manipulation task source to: Do task thing 1. Set old stack to a copy of the JavaScript execution context stack Empty the JavaScript execution context stack Perform a microtask checkpoint Wait until awesomeness happens. Queue a task on the DOM manipulation task source to: Replace the JavaScript execution context stack with old stack Do task thing 2. Do parallel thing 2. Some of the algorithms in this specification, for historical reasons, require the user agent to pause while running a task until a condition goal is met. This means running the following steps: If necessary, update the rendering or user interface of any Document or browsing context to reflect the current state. Wait until the condition goal is met. While a user agent has a paused task , the corresponding event loop must not run further tasks , and any script in the currently running task must block. User agents should remain responsive to user input while paused, however, albeit in a reduced capacity since the event loop will not be doing anything. Pausing is highly detrimental to the user experience, especially in scenarios where a single event loop is shared among multiple documents. User agents are encouraged to experiment with alternatives to pausing such as spinning the event loop or even simply proceeding without any kind of suspended execution at all, insofar as it is possible to do so while preserving compatibility with existing content. This specification will happily change if a less-drastic alternative is discovered to be web-compatible. In the interim, implementers should be aware that the variety of alternatives that user agents might experiment with can change subtle aspects of event loop behavior, including task and microtask timing. Implementations should continue experimenting even if doing so causes them to violate the exact semantics implied by the pause operation. 8.1.6.4 Generic task sources The following task sources are used by a number of mostly unrelated features in this and other specifications. The DOM manipulation task source This task source is used for features that react to DOM manipulations, such as things that happen in a non-blocking fashion when an element is inserted into the document The user interaction task source This task source is used for features that react to user interaction, for example keyboard or mouse input. Events sent in response to user input (e.g. click events) must be fired using tasks queued with the user interaction task source [UIEVENTS] The networking task source This task source is used for features that trigger in response to network activity. The history traversal task source This task source is used to queue calls to history.back() and similar APIs. 8.1.6.5 Dealing with the event loop from other specifications Writing specifications that correctly interact with the event loop can be tricky. This is compounded by how this specification uses concurrency-model-independent terminology, so we say things like " event loop " and " in parallel " instead of using more familiar model-specific terms like "main thread" or "on a background thread". By default, specification text generally runs on the event loop . This falls out from the formal event loop processing model , in that you can eventually trace most algorithms back to a task queued there. The algorithm steps for any JavaScript method will be invoked by author code calling that method. And author code can only be run via queued tasks, usually originating somewhere in the script processing model From this starting point, the overriding guideline is that any work a specification needs to perform that would otherwise block the event loop must instead be performed in parallel with it. This includes (but is not limited to): performing heavy computation; displaying a user-facing prompt; performing operations which could require involving outside systems (i.e. "going out of process"). The next complication is that, in algorithm sections that are in parallel , you must not create or manipulate objects associated to a specific JavaScript realm global , or environment settings object . (Stated in more familiar terms, you must not directly access main-thread artifacts from a background thread.) Doing so would create data races observable to JavaScript code, since after all, your algorithm steps are running in parallel to the JavaScript code. You can, however, manipulate specification-level data structures and values from Infra , as those are realm-agnostic. They are never directly exposed to JavaScript without a specific conversion taking place (often via Web IDL ). [INFRA] [WEBIDL] To affect the world of observable JavaScript objects, then, you must queue a global task to perform any such manipulations. This ensures your steps are properly interleaved with respect to other things happening on the event loop . Furthermore, you must choose a task source when queuing a global task ; this governs the relative order of your steps versus others. If you are unsure which task source to use, pick one of the generic task sources that sounds most applicable. Finally, you must indicate which global object your queued task is associated with; this ensures that if that global object is inactive, the task does not run. The base primitive, on which queue a global task builds, is the queue a task algorithm. In general, queue a global task is better because it automatically picks the right event loop and, where appropriate, document . Older specifications often use queue a task combined with the implied event loop and implied document concepts, but this is discouraged. Putting this all together, we can provide a template for a typical algorithm that needs to do work asynchronously: Do any synchronous setup work, while still on the event loop . This may include converting realm -specific JavaScript values into realm-agnostic specification-level values. Perform a set of potentially-expensive steps in parallel , operating entirely on realm-agnostic values, and producing a realm-agnostic result. Queue a global task , on a specified task source and given an appropriate global object , to convert the realm-agnostic result back into observable effects on the observable world of JavaScript objects on the event loop The following is an algorithm that "encrypts" a passed-in list of scalar value strings input , after parsing them as URLs: Let urls be an empty list For each string of input Let parsed be the result of parsing string relative to the current settings object If parsed is failure, return a promise rejected with a SyntaxError DOMException Let serialized be the result of applying the URL serializer to parsed Append serialized to urls Let realm be the current Realm Record Let be a new promise. Run the following steps in parallel Let encryptedURLs be an empty list For each url of urls Wait 100 milliseconds, so that people think we're doing heavy-duty encryption. Let encrypted be a new string derived from url whose th code unit is equal to url 's th code unit plus 13. Append encrypted to encryptedURLs Queue a global task on the networking task source , given realm 's global object , to perform the following steps: Let array be the result of converting encryptedURLs to a JavaScript array, in realm Resolve with array Return Here are several things to notice about this algorithm: It does its URL parsing up front, on the event loop , before going to the in parallel steps. This is necessary, since parsing depends on the current settings object , which would no longer be current after going in parallel Alternately, it could have saved a reference to the current settings object 's API base URL and used it during the in parallel steps; that would have been equivalent. However, we recommend instead doing as much work as possible up front, as this example does. Attempting to save the correct values can be error prone; for example, if we'd saved just the current settings object , instead of its API base URL , there would have been a potential race. It implicitly passes a list of strings from the initial steps to the in parallel steps. This is OK, as both lists and strings are realm -agnostic. It performs "expensive computation" (waiting for 100 milliseconds per input URL) during the in parallel steps, thus not blocking the main event loop Promises, as observable JavaScript objects, are never created and manipulated during the in parallel steps. is created before entering those steps, and then is manipulated during a task that is queued specifically for that purpose. The creation of a JavaScript array object also happens during the queued task, and is careful to specify which realm it creates the array in since that is no longer obvious from context. (On these last two points, see also heycam/webidl issue #135 and heycam/webidl issue #371 , where we are still mulling over the subtleties of the above promise-resolution pattern.) Another thing to note is that, in the event this algorithm was called from a Web IDL-specified operation taking a sequence USVString >, there was an automatic conversion from realm -specific JavaScript objects provided by the author as input, into the realm-agnostic sequence USVString > Web IDL type, which we then treat as a list of scalar value strings . So depending on how your specification is structured, there may be other implicit steps happening on the main event loop that play a part in this whole process of getting you ready to go in parallel 8.1.7 Events 8.1.7.1 Event handlers Events/Event_handlers Many objects can have event handlers specified. These act as non-capture event listeners for the object on which they are specified. [DOM] An event handler is a struct with two items value , which is either null, a callback object, or an internal raw uncompiled handler . The EventHandler callback function type describes how this is exposed to scripts. Initially, an event handler 's value must be set to null. listener , which is either null or an event listener responsible for running the event handler processing algorithm . Initially, an event handler 's listener must be set to null. Event handlers are exposed in two ways. The first way, common to all event handlers, is as an event handler IDL attribute The second way is as an event handler content attribute . Event handlers on HTML elements and some of the event handlers on Window objects are exposed in this way. For both of these two ways, the event handler is exposed through a name , which is a string that always starts with on " and is followed by the name of the event for which the handler is intended. Most of the time, the object that exposes an event handler is the same as the object on which the corresponding event listener is added. However, the body and frameset elements expose several event handlers that act upon the element's Window object, if one exists. In either case, we call the object an event handler acts upon the target of that event handler To determine the target of an event handler , given an EventTarget object eventTarget on which the event handler is exposed, and an event handler name name , the following steps are taken: If eventTarget is not a body element or a frameset element, then return eventTarget If name is not the name of an attribute member of the WindowEventHandlers interface mixin and the Window -reflecting body element event handler set does not contain name , then return eventTarget If eventTarget 's node document is not an active document , then return null. This could happen if this object is a body element without a corresponding Window object, for example. This check does not necessarily prevent body and frameset elements that are not the body element of their node document from reaching the next step. In particular, a body element created in an active document (perhaps with document.createElement() ) but not connected will also have its corresponding Window object as the target of several event handlers exposed through it. Return eventTarget 's node document 's relevant global object Each EventTarget object that has one or more event handlers specified has an associated event handler map , which is a map of strings representing names of event handlers to event handlers When an EventTarget object that has one or more event handlers specified is created, its event handler map must be initialized such that it contains an entry for each event handler that has that object as target , with items in those event handlers set to their initial values. The order of the entries of event handler map could be arbitrary. It is not observable through any algorithms that operate on the map. Entries are not created in the event handler map of an object for event handlers that are merely exposed on that object, but have some other object as their targets An event handler IDL attribute is an IDL attribute for a specific event handler . The name of the IDL attribute is the same as the name of the event handler The getter of an event handler IDL attribute with name name , when called, must run these steps: Let eventTarget be the result of determining the target of an event handler given this object and name If eventTarget is null, then return null. Return the result of getting the current value of the event handler given eventTarget and name The setter of an event handler IDL attribute with name name , when called, must run these steps: Let eventTarget be the result of determining the target of an event handler given this object and name If eventTarget is null, then return. If the given value is null, then deactivate an event handler given eventTarget and name Otherwise: Let handlerMap be eventTarget 's event handler map Let eventHandler be handlerMap name ]. Set eventHandler 's value to the given value. Activate an event handler given eventTarget and name Certain event handler IDL attributes have additional requirements, in particular the onmessage attribute of MessagePort objects. An event handler content attribute is a content attribute for a specific event handler . The name of the content attribute is the same as the name of the event handler Event handler content attributes , when specified, must contain valid JavaScript code which, when parsed, would match the FunctionBody production after automatic semicolon insertion The following attribute change steps are used to synchronize between event handler content attributes and event handlers [DOM] If namespace is not null, or localName is not the name of an event handler content attribute on element , then return. Let eventTarget be the result of determining the target of an event handler given element and localName If eventTarget is null, then return. If value is null, then deactivate an event handler given eventTarget and localName Otherwise: If the Should element's inline behavior be blocked by Content Security Policy? algorithm returns " Blocked " when executed upon element , " script attribute ", and value , then return. [CSP] Let handlerMap be eventTarget 's event handler map Let eventHandler be handlerMap localName ]. Let location be the script location that triggered the execution of these steps. Set eventHandler 's value to the internal raw uncompiled handler value location Activate an event handler given eventTarget and localName Per the DOM Standard, these steps are run even if oldValue and value are identical (setting an attribute to its current value), but not if oldValue and value are both null (removing an attribute that doesn't currently exist). [DOM] To deactivate an event handler given an EventTarget object eventTarget and a string name that is the name of an event handler , run these steps: Let handlerMap be eventTarget 's event handler map Let eventHandler be handlerMap name ]. Set eventHandler 's value to null. Let listener be eventHandler 's listener If listener is not null, then remove an event listener with eventTarget and listener Set eventHandler 's listener to null. To erase all event listeners and handlers given an EventTarget object eventTarget , run these steps: If eventTarget has an associated event handler map , then for each name eventHandler of eventTarget 's associated event handler map deactivate an event handler given eventTarget and name Remove all event listeners given eventTarget This algorithm is used to define document.open() To activate an event handler given an EventTarget object eventTarget and a string name that is the name of an event handler , run these steps: Let handlerMap be eventTarget 's event handler map Let eventHandler be handlerMap name ]. If eventHandler 's listener is not null, then return. Let callback be the result of creating a Web IDL EventListener instance representing a reference to a function of one argument that executes the steps of the event handler processing algorithm given eventTarget name , and its argument. The EventListener 's callback context can be arbitrary; it does not impact the steps of the event handler processing algorithm [DOM] The callback is emphatically not the event handler itself. Every event handler ends up registering the same callback, the algorithm defined below, which takes care of invoking the right code, and processing the code's return value. Let listener be a new event listener whose type is the event handler event type corresponding to eventHandler and callback is callback To be clear, an event listener is different from an EventListener Add an event listener with eventTarget and listener Set eventHandler 's listener to listener The event listener registration happens only if the event handler 's value is being set to non-null, and the event handler is not already activated. Since listeners are called in the order they were registered, assuming no deactivation occurred, the order of event listeners for a particular event type will always be: the event listeners registered with addEventListener() before the first time the event handler 's value was set to non-null then the callback to which it is currently set, if any and finally the event listeners registered with addEventListener() after the first time the event handler 's value was set to non-null. This example demonstrates the order in which event listeners are invoked. If the button in this example is clicked by the user, the page will show four alerts, with the text "ONE", "TWO", "THREE", and "FOUR" respectively. button id "test" Start Demo button script var button document getElementById 'test' ); button addEventListener 'click' function () alert 'ONE' }, false ); button setAttribute 'onclick' "alert('NOT CALLED')" ); // event handler listener is registered here button addEventListener 'click' function () alert 'THREE' }, false ); button onclick function () alert 'TWO' ); }; button addEventListener 'click' function () alert 'FOUR' }, false ); script However, in the following example, the event handler is deactivated after its initial activation (and its event listener is removed), before being reactivated at a later time. The page will show five alerts with "ONE", "TWO", "THREE", "FOUR", and "FIVE" respectively, in order. button id "test" Start Demo button script var button document getElementById 'test' ); button addEventListener 'click' function () alert 'ONE' }, false ); button setAttribute 'onclick' "alert('NOT CALLED')" ); // event handler is activated here button addEventListener 'click' function () alert 'TWO' }, false ); button onclick null // but deactivated here button addEventListener 'click' function () alert 'THREE' }, false ); button onclick function () alert 'FOUR' ); }; // and re-activated here button addEventListener 'click' function () alert 'FIVE' }, false ); script The interfaces implemented by the event object do not influence whether an event handler is triggered or not. The event handler processing algorithm for an EventTarget object eventTarget , a string name representing the name of an event handler , and an Event object event is as follows: Let callback be the result of getting the current value of the event handler given eventTarget and name If callback is null, then return. Let special error event handling be true if event is an ErrorEvent object, event 's type is error , and event 's currentTarget implements the WindowOrWorkerGlobalScope mixin. Otherwise, let special error event handling be false. Process the Event object event as follows: If special error event handling is true Invoke callback with five arguments, the first one having the value of event 's message attribute, the second having the value of event 's filename attribute, the third having the value of event 's lineno attribute, the fourth having the value of event 's colno attribute, the fifth having the value of event 's error attribute, and with the callback this value set to event 's currentTarget . Let return value be the callback's return value. [WEBIDL] Otherwise Invoke callback with one argument, the value of which is the Event object event with the callback this value set to event 's currentTarget . Let return value be the callback's return value. [WEBIDL] If an exception gets thrown by the callback, end these steps and allow the exception to propagate. (It will propagate to the DOM event dispatch logic , which will then report the exception .) Process return value as follows: If event is a BeforeUnloadEvent object and event 's type is beforeunload In this case, the event handler IDL attribute 's type will be OnBeforeUnloadEventHandler , so return value will have been coerced into either null or a DOMString If return value is not null, then: Set event 's canceled flag If event 's returnValue attribute's value is the empty string, then set event 's returnValue attribute's value to return value If special error event handling is true If return value is true, then set event 's canceled flag Otherwise If return value is false, then set event 's canceled flag If we've gotten to this "Otherwise" clause because event 's type is beforeunload but event is not BeforeUnloadEvent object, then return value will never be false, since in such cases return value will have been coerced into either null or a DOMString The EventHandler callback function type represents a callback used for event handlers. It is represented in Web IDL as follows: LegacyTreatNonObjectAsNull callback EventHandlerNonNull any Event event ); typedef EventHandlerNonNull EventHandler In JavaScript, any Function object implements this interface. For example, the following document fragment: body onload "alert(this)" onclick "alert(this)" ...leads to an alert saying " [object Window] " when the document is loaded, and an alert saying " [object HTMLBodyElement] " whenever the user clicks something in the page. The return value of the function affects whether the event is canceled or not: as described above, if the return value is false, the event is canceled. There are two exceptions in the platform, for historical reasons: The onerror handlers on global objects, where returning true cancels the event The onbeforeunload handler, where returning any non-null and non-undefined value will cancel the event. For historical reasons, the onerror handler has different arguments: LegacyTreatNonObjectAsNull callback OnErrorEventHandlerNonNull any (( Event or DOMString event optional DOMString source optional unsigned long lineno optional unsigned long colno optional any error ); typedef OnErrorEventHandlerNonNull OnErrorEventHandler window onerror message source lineno colno error => }; Similarly, the onbeforeunload handler has a different return value: LegacyTreatNonObjectAsNull callback OnBeforeUnloadEventHandlerNonNull DOMString ? ( Event event ); typedef OnBeforeUnloadEventHandlerNonNull OnBeforeUnloadEventHandler An internal raw uncompiled handler is a tuple with the following information: An uncompiled script body A location where the script body originated, in case an error needs to be reported When the user agent is to get the current value of the event handler given an EventTarget object eventTarget and a string name that is the name of an event handler , it must run these steps: Let handlerMap be eventTarget 's event handler map Let eventHandler be handlerMap name ]. If eventHandler 's value is an internal raw uncompiled handler , then: If eventTarget is an element, then let element be eventTarget , and document be element 's node document . Otherwise, eventTarget is a Window object, let element be null, and document be eventTarget 's associated Document If scripting is disabled for document , then return null. Let body be the uncompiled script body in eventHandler 's value Let location be the location where the script body originated, as given by eventHandler 's value If element is not null and element has a form owner , let form owner be that form owner Otherwise, let form owner be null. Let settings object be the relevant settings object of document If body is not parsable as FunctionBody or if parsing detects an early error , then follow these substeps: Set eventHandler 's value to null. This does not deactivate the event handler, which additionally removes the event handler's listener (if present). Report the error for the appropriate script and with the appropriate position (line number and column number) given by location , using settings object 's global object . If the error is still not handled after this, then the error may be reported to a developer console. Return null. Push settings object 's realm execution context onto the JavaScript execution context stack ; it is now the running JavaScript execution context This is necessary so the subsequent invocation of OrdinaryFunctionCreate takes place in the correct JavaScript Realm Let function be the result of calling OrdinaryFunctionCreate , with arguments: functionPrototype %Function.prototype% sourceText If name is onerror and eventTarget is a Window object The string formed by concatenating " function ", name (event, source, lineno, colno, error) { ", U+000A LF, body , U+000A LF, and " ". Otherwise The string formed by concatenating " function ", name (event) { ", U+000A LF, body , U+000A LF, and " ". ParameterList If name is onerror and eventTarget is a Window object Let the function have five arguments, named event source lineno colno , and error Otherwise Let the function have a single argument called event body The result of parsing body above. thisMode non-lexical-this scope Let realm be settings object 's Realm Let scope be realm .[[GlobalEnv]]. If eventHandler is an element's event handler , then set scope to NewObjectEnvironment document , true, scope ). (Otherwise, eventHandler is a Window object's event handler .) If form owner is not null, then set scope to NewObjectEnvironment form owner , true, scope ). If element is not null, then set scope to NewObjectEnvironment element , true, scope ). Return scope Remove settings object 's realm execution context from the JavaScript execution context stack Set function .[[ScriptOrModule]] to null. This is done because the default behavior, of associating the created function with the nearest script on the stack, can lead to path-dependent results. For example, an event handler which is first invoked by user interaction would end up with null [[ScriptOrModule]] (since then this algorithm would be first invoked when the active script is null), whereas one that is first invoked by dispatching an event from script would have its [[ScriptOrModule]] set to that script. Instead, we just always set [[ScriptOrModule]] to null. This is more intuitive anyway; the idea that the first script which dispatches an event is somehow responsible for the event handler code is dubious. In practice, this only affects the resolution of relative URLs via import() which consult the base URL of the associated script. Nulling out [[ScriptOrModule]] means that HostResolveImportedModule and HostImportModuleDynamically will fall back to the current settings object 's API base URL Set eventHandler 's value to the result of creating a Web IDL EventHandler callback function object whose object reference is function and whose callback context is settings object Return eventHandler 's value 8.1.7.2 Event handlers on elements, Document objects, and Window objects The following are the event handlers (and their corresponding event handler event types ) that must be supported by all HTML elements , as both event handler content attributes and event handler IDL attributes ; and that must be supported by all Document and Window objects, as event handler IDL attributes Event handler Event handler event type onabort GlobalEventHandlers/onabort Support in all current engines. Firefox 9+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 9+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ abort onauxclick auxclick oncancel GlobalEventHandlers/oncancel Support in one engine only. Firefox No Safari No Chrome 32+ Opera 19+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android No Safari iOS No Chrome Android 32+ WebView Android 4.4.3+ Samsung Internet 2.0+ Opera Android 19+ cancel oncanplay GlobalEventHandlers/oncanplay Support in all current engines. Firefox 9+ Safari 9+ Chrome 32+ Opera 19+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 9+ Safari iOS 9+ Chrome Android 32+ WebView Android 4.4.3+ Samsung Internet 2.0+ Opera Android 19+ canplay oncanplaythrough GlobalEventHandlers/oncanplaythrough Support in all current engines. Firefox 9+ Safari 9+ Chrome 32+ Opera 19+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 9+ Safari iOS 9+ Chrome Android 32+ WebView Android 4.4.3+ Samsung Internet 2.0+ Opera Android 19+ canplaythrough onchange GlobalEventHandlers/onchange Support in all current engines. Firefox 1+ Safari 3+ Chrome 1+ Opera 9+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 10.1+ change onclick GlobalEventHandlers/onclick Support in all current engines. Firefox 1+ Safari 3+ Chrome 1+ Opera 9+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 10.1+ click onclose GlobalEventHandlers/onclose Firefox 53+ Safari No Chrome 32+ Opera 19+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 53+ Safari iOS No Chrome Android 32+ WebView Android 4.4.3+ Samsung Internet 2.0+ Opera Android 19+ close oncontextmenu GlobalEventHandlers/oncontextmenu Support in all current engines. Firefox 9+ Safari 4+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 5+ Firefox Android 9+ Safari iOS 3.2+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ contextmenu oncuechange GlobalEventHandlers/oncuechange Support in all current engines. Firefox 68+ Safari 10.1+ Chrome 32+ Opera 19+ Edge 79+ Edge (Legacy) 18 Internet Explorer No Firefox Android 68+ Safari iOS 10.3+ Chrome Android 32+ WebView Android 4.4.3+ Samsung Internet 2.0+ Opera Android 19+ cuechange ondblclick GlobalEventHandlers/ondblclick Support in all current engines. Firefox 9+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 9+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ dblclick ondrag drag ondragend dragend ondragenter dragenter ondragleave dragleave ondragover dragover ondragstart dragstart ondrop drop ondurationchange GlobalEventHandlers/ondurationchange Support in all current engines. Firefox 9+ Safari 9+ Chrome 32+ Opera 19+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 9+ Safari iOS 9+ Chrome Android 32+ WebView Android 4.4.3+ Samsung Internet 2.0+ Opera Android 19+ durationchange onemptied GlobalEventHandlers/onemptied Support in all current engines. Firefox 9+ Safari 9+ Chrome 32+ Opera 19+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 9+ Safari iOS 9+ Chrome Android 32+ WebView Android 4.4.3+ Samsung Internet 2.0+ Opera Android 19+ emptied onended GlobalEventHandlers/onended Support in all current engines. Firefox 9+ Safari 9+ Chrome 32+ Opera 19+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 9+ Safari iOS 9+ Chrome Android 32+ WebView Android 4.4.3+ Samsung Internet 2.0+ Opera Android 19+ ended onformdata GlobalEventHandlers/onformdata Firefox 72+ Safari No Chrome 77+ Opera 64+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 79+ Safari iOS No Chrome Android 77+ WebView Android 77+ Samsung Internet 12.0+ Opera Android 55+ formdata oninput GlobalEventHandlers/oninput Support in all current engines. Firefox 9+ Safari 4+ Chrome 1+ Opera 10+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 9+ Safari iOS 3.2+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 10.1+ input oninvalid GlobalEventHandlers/oninvalid Support in all current engines. Firefox 9+ Safari 5+ Chrome 4+ Opera 12.1+ Edge 79+ Edge (Legacy) 13+ Internet Explorer No Firefox Android 9+ Safari iOS 4+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 12.1+ invalid onkeydown GlobalEventHandlers/onkeydown Support in all current engines. Firefox 9+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 9+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ keydown onkeypress keypress onkeyup GlobalEventHandlers/onkeyup Support in all current engines. Firefox 9+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 9+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ keyup onloadeddata GlobalEventHandlers/onloadeddata Support in all current engines. Firefox 9+ Safari 9+ Chrome 32+ Opera 19+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 9+ Safari iOS 9+ Chrome Android 32+ WebView Android 4.4.3+ Samsung Internet 2.0+ Opera Android 19+ loadeddata onloadedmetadata GlobalEventHandlers/onloadedmetadata Support in all current engines. Firefox 9+ Safari 9+ Chrome 32+ Opera 19+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 9+ Safari iOS 9+ Chrome Android 32+ WebView Android 4.4.3+ Samsung Internet 2.0+ Opera Android 19+ loadedmetadata onloadstart GlobalEventHandlers/onloadstart Support in all current engines. Firefox 9+ Safari 9+ Chrome 32+ Opera 19+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 9+ Safari iOS 9+ Chrome Android 32+ WebView Android 4.4.3+ Samsung Internet 2.0+ Opera Android 19+ loadstart onmousedown GlobalEventHandlers/onmousedown Support in all current engines. Firefox 9+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 9+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ mousedown onmouseenter GlobalEventHandlers/onmouseenter Support in all current engines. Firefox 10+ Safari 6.1+ Chrome 30+ Opera 17+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 5.5+ Firefox Android 10+ Safari iOS 7+ Chrome Android 30+ WebView Android 4.4+ Samsung Internet 2.0+ Opera Android 18+ mouseenter onmouseleave GlobalEventHandlers/onmouseleave Support in all current engines. Firefox 10+ Safari 6.1+ Chrome 30+ Opera 17+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 5.5+ Firefox Android 10+ Safari iOS 7+ Chrome Android 30+ WebView Android 4.4+ Samsung Internet 2.0+ Opera Android 18+ mouseleave onmousemove GlobalEventHandlers/onmousemove Support in all current engines. Firefox 9+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 9+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ mousemove onmouseout GlobalEventHandlers/onmouseout Support in all current engines. Firefox 9+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 9+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ mouseout onmouseover GlobalEventHandlers/onmouseover Support in all current engines. Firefox 9+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 9+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ mouseover onmouseup GlobalEventHandlers/onmouseup Support in all current engines. Firefox 9+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 9+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ mouseup onpause GlobalEventHandlers/onpause Support in all current engines. Firefox 9+ Safari 9+ Chrome 32+ Opera 19+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 9+ Safari iOS 9+ Chrome Android 32+ WebView Android 4.4.3+ Samsung Internet 2.0+ Opera Android 19+ pause onplay GlobalEventHandlers/onplay Support in all current engines. Firefox 9+ Safari 9+ Chrome 32+ Opera 19+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 9+ Safari iOS 9+ Chrome Android 32+ WebView Android 4.4.3+ Samsung Internet 2.0+ Opera Android 19+ play onplaying GlobalEventHandlers/onplaying Support in all current engines. Firefox 9+ Safari 9+ Chrome 32+ Opera 19+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 9+ Safari iOS 9+ Chrome Android 32+ WebView Android 4.4.3+ Samsung Internet 2.0+ Opera Android 19+ playing onprogress progress onratechange ratechange onreset GlobalEventHandlers/onreset Support in all current engines. Firefox 9+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 9+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ reset onsecuritypolicyviolation securitypolicyviolation onseeked seeked onseeking seeking onselect GlobalEventHandlers/onselect Support in all current engines. Firefox 9+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 9+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ select onslotchange slotchange onstalled stalled onsubmit GlobalEventHandlers/onsubmit Support in all current engines. Firefox 9+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 9+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ submit onsuspend suspend ontimeupdate timeupdate ontoggle toggle onvolumechange volumechange onwaiting waiting onwebkitanimationend webkitAnimationEnd onwebkitanimationiteration webkitAnimationIteration onwebkitanimationstart webkitAnimationStart onwebkittransitionend webkitTransitionEnd onwheel GlobalEventHandlers/onwheel Support in all current engines. Firefox 17+ Safari 7+ Chrome 31+ Opera 18+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android 17+ Safari iOS 7+ Chrome Android 31+ WebView Android 4.4.3+ Samsung Internet 2.0+ Opera Android 18+ wheel The following are the event handlers (and their corresponding event handler event types ) that must be supported by all HTML elements other than body and frameset elements, as both event handler content attributes and event handler IDL attributes ; that must be supported by all Document objects, as event handler IDL attributes ; and that must be supported by all Window objects, as event handler IDL attributes on the Window objects themselves, and with corresponding event handler content attributes and event handler IDL attributes exposed on all body and frameset elements that are owned by that Window object's associated Document Event handler Event handler event type onblur GlobalEventHandlers/onblur Support in all current engines. Firefox 9+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 9+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ blur onerror GlobalEventHandlers/onerror Support in all current engines. Firefox 1+ Safari 6+ Chrome 10+ Opera 11.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 4+ Safari iOS 6+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 12+ HTMLMediaElement/onerror Support in all current engines. Firefox 3.5+ Safari 1.3+ Chrome Yes Opera Yes Edge Yes Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 4+ Safari iOS 1+ Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes error onfocus GlobalEventHandlers/onfocus Support in all current engines. Firefox 9+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 9+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ focus onload GlobalEventHandlers/onload Support in all current engines. Firefox 1+ Safari 3+ Chrome 1+ Opera 9+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 10.1+ load onresize GlobalEventHandlers/onresize Support in all current engines. Firefox 38+ Safari 10.1+ Chrome 34+ Opera 21+ Edge 79+ Edge (Legacy) No Internet Explorer 🔰 4+ Firefox Android 38+ Safari iOS 10.3+ Chrome Android 34+ WebView Android 37+ Samsung Internet 2.0+ Opera Android 21+ resize onscroll GlobalEventHandlers/onscroll Support in all current engines. Firefox 9+ Safari 1.3+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android 9+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12.1+ scroll We call the set of the names of the event handlers listed in the first column of this table the Window -reflecting body element event handler set The following are the event handlers (and their corresponding event handler event types ) that must be supported by Window objects, as event handler IDL attributes on the Window objects themselves, and with corresponding event handler content attributes and event handler IDL attributes exposed on all body and frameset elements that are owned by that Window object's associated Document Event handler Event handler event type onafterprint WindowEventHandlers/onafterprint Support in all current engines. Firefox 6+ Safari 13+ Chrome 63+ Opera 50+ Edge 79+ Edge (Legacy) 12+ Internet Explorer Yes Firefox Android Safari iOS 13+ Chrome Android 63+ WebView Android 63+ Samsung Internet 8.0+ Opera Android 46+ afterprint onbeforeprint WindowEventHandlers/onbeforeprint Support in all current engines. Firefox 6+ Safari 13+ Chrome 63+ Opera 50+ Edge 79+ Edge (Legacy) 12+ Internet Explorer Yes Firefox Android Safari iOS 13+ Chrome Android 63+ WebView Android 63+ Samsung Internet 8.0+ Opera Android 46+ beforeprint onbeforeunload WindowEventHandlers/onbeforeunload Support in all current engines. Firefox 1+ Safari 3+ Chrome 1+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 12+ beforeunload onhashchange WindowEventHandlers/onhashchange Support in all current engines. Firefox 3.6+ Safari 5+ Chrome 5+ Opera 10+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 8+ Firefox Android 4+ Safari iOS 5+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 10.1+ hashchange onlanguagechange WindowEventHandlers/onlanguagechange Firefox 32+ Safari Chrome 37+ Opera 24+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 4+ Safari iOS Chrome Android 37+ WebView Android 37+ Samsung Internet 4.0+ Opera Android 24+ languagechange onmessage WindowEventHandlers/onmessage Support in one engine only. Firefox Safari Chrome 60+ Opera 47+ Edge 79+ Edge (Legacy) No Internet Explorer Firefox Android Safari iOS Chrome Android 60+ WebView Android 60+ Samsung Internet 8.0+ Opera Android 44+ message onmessageerror WindowEventHandlers/onmessageerror Firefox 57+ Safari Chrome 60+ Opera 47+ Edge 79+ Edge (Legacy) No Internet Explorer Firefox Android 57+ Safari iOS Chrome Android 60+ WebView Android 60+ Samsung Internet 8.0+ Opera Android 44+ messageerror onoffline offline ononline online onpagehide pagehide onpageshow pageshow onpopstate WindowEventHandlers/onpopstate Support in all current engines. Firefox 4+ Safari 6+ Chrome 5+ Opera 11.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 5.1+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11.5+ popstate onrejectionhandled WindowEventHandlers/onrejectionhandled Support in all current engines. Firefox 69+ Safari 11+ Chrome 49+ Opera 36+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 🔰 68+ Safari iOS 11.3+ Chrome Android 49+ WebView Android 49+ Samsung Internet 5.0+ Opera Android No rejectionhandled onstorage WindowEventHandlers/onstorage Support in all current engines. Firefox 45+ Safari 4+ Chrome 1+ Opera 15+ Edge 79+ Edge (Legacy) 15+ Internet Explorer 9+ Firefox Android 45+ Safari iOS 4+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 14+ storage onunhandledrejection WindowEventHandlers/onunhandledrejection Support in all current engines. Firefox 69+ Safari 11+ Chrome 49+ Opera 36+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 🔰 68+ Safari iOS 11.3+ Chrome Android 49+ WebView Android 49+ Samsung Internet 5.0+ Opera Android No unhandledrejection onunload WindowEventHandlers/onunload Support in all current engines. Firefox Yes Safari Yes Chrome Yes Opera Yes Edge Yes Edge (Legacy) 12+ Internet Explorer Yes Firefox Android Yes Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes unload This list of event handlers is reified as event handler IDL attributes through the WindowEventHandlers interface mixin. The following are the event handlers (and their corresponding event handler event types ) that must be supported by all HTML elements , as both event handler content attributes and event handler IDL attributes ; and that must be supported by all Document objects, as event handler IDL attributes Event handler Event handler event type oncut cut oncopy copy onpaste paste This list of event handlers is reified as event handler IDL attributes through the DocumentAndElementEventHandlers interface mixin. The following are the event handlers (and their corresponding event handler event types ) that must be supported on Document objects as event handler IDL attributes Event handler Event handler event type onreadystatechange readystatechange 8.1.7.2.1 IDL definitions GlobalEventHandlers Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera Yes Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android Yes WindowEventHandlers Support in all current engines. Firefox Yes Safari Yes Chrome Yes Opera Yes Edge Yes Edge (Legacy) 12+ Internet Explorer Yes Firefox Android Yes Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes interface mixin GlobalEventHandlers attribute EventHandler onabort attribute EventHandler onauxclick attribute EventHandler onblur attribute EventHandler oncancel attribute EventHandler oncanplay attribute EventHandler oncanplaythrough attribute EventHandler onchange attribute EventHandler onclick attribute EventHandler onclose attribute EventHandler oncontextmenu attribute EventHandler oncuechange attribute EventHandler ondblclick attribute EventHandler ondrag attribute EventHandler ondragend attribute EventHandler ondragenter attribute EventHandler ondragleave attribute EventHandler ondragover attribute EventHandler ondragstart attribute EventHandler ondrop attribute EventHandler ondurationchange attribute EventHandler onemptied attribute EventHandler onended attribute OnErrorEventHandler onerror attribute EventHandler onfocus attribute EventHandler onformdata attribute EventHandler oninput attribute EventHandler oninvalid attribute EventHandler onkeydown attribute EventHandler onkeypress attribute EventHandler onkeyup attribute EventHandler onload attribute EventHandler onloadeddata attribute EventHandler onloadedmetadata attribute EventHandler onloadstart attribute EventHandler onmousedown LegacyLenientThis attribute EventHandler onmouseenter LegacyLenientThis attribute EventHandler onmouseleave attribute EventHandler onmousemove attribute EventHandler onmouseout attribute EventHandler onmouseover attribute EventHandler onmouseup attribute EventHandler onpause attribute EventHandler onplay attribute EventHandler onplaying attribute EventHandler onprogress attribute EventHandler onratechange attribute EventHandler onreset attribute EventHandler onresize attribute EventHandler onscroll attribute EventHandler onsecuritypolicyviolation attribute EventHandler onseeked attribute EventHandler onseeking attribute EventHandler onselect attribute EventHandler onslotchange attribute EventHandler onstalled attribute EventHandler onsubmit attribute EventHandler onsuspend attribute EventHandler ontimeupdate attribute EventHandler ontoggle attribute EventHandler onvolumechange attribute EventHandler onwaiting attribute EventHandler onwebkitanimationend attribute EventHandler onwebkitanimationiteration attribute EventHandler onwebkitanimationstart attribute EventHandler onwebkittransitionend attribute EventHandler onwheel }; interface mixin WindowEventHandlers attribute EventHandler onafterprint attribute EventHandler onbeforeprint attribute OnBeforeUnloadEventHandler onbeforeunload attribute EventHandler onhashchange attribute EventHandler onlanguagechange attribute EventHandler onmessage attribute EventHandler onmessageerror attribute EventHandler onoffline attribute EventHandler ononline attribute EventHandler onpagehide attribute EventHandler onpageshow attribute EventHandler onpopstate attribute EventHandler onrejectionhandled attribute EventHandler onstorage attribute EventHandler onunhandledrejection attribute EventHandler onunload }; interface mixin DocumentAndElementEventHandlers attribute EventHandler oncopy attribute EventHandler oncut attribute EventHandler onpaste }; 8.1.7.3 Event firing Certain operations and methods are defined as firing events on elements. For example, the click() method on the HTMLElement interface is defined as firing a click event on the element. [UIEVENTS] Firing a synthetic pointer event named at target , with an optional not trusted flag , means running these steps: Let event be the result of creating an event using PointerEvent Initialize event 's type attribute to Initialize event 's bubbles and cancelable attributes to true. Set event 's composed flag If the not trusted flag is set, initialize event 's isTrusted attribute to false. Initialize event 's ctrlKey shiftKey altKey , and metaKey attributes according to the current state of the key input device, if any (false for any keys that are not available). Initialize event 's view attribute to target 's node document 's Window object, if any, and null otherwise. event 's getModifierState() method is to return values appropriately describing the current state of the key input device. Return the result of dispatching event at target Firing a click event at target means firing a synthetic pointer event named click at target 8.2 The WindowOrWorkerGlobalScope mixin WindowOrWorkerGlobalScope Support in all current engines. Firefox 1+ Safari Yes Chrome 4+ Opera Yes Edge 79+ Edge (Legacy) 12+ Internet Explorer Yes Firefox Android 4+ Safari iOS Yes Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android Yes The WindowOrWorkerGlobalScope mixin is for use of APIs that are to be exposed on Window and WorkerGlobalScope objects. Other standards are encouraged to further extend it using partial interface mixin WindowOrWorkerGlobalScope { … }; along with an appropriate reference. typedef DOMString or Function TimerHandler interface mixin WindowOrWorkerGlobalScope Replaceable readonly attribute USVString origin readonly attribute boolean isSecureContext readonly attribute boolean crossOriginIsolated
// base64 utility methods DOMString btoa DOMString data ); ByteString atob DOMString data );
// timers long setTimeout TimerHandler handler optional long timeout = 0, any ... arguments ); undefined clearTimeout optional long handle = 0); long setInterval TimerHandler handler optional long timeout = 0, any ... arguments ); undefined clearInterval optional long handle = 0);
// microtask queuing undefined queueMicrotask VoidFunction callback );
// ImageBitmap Promise ImageBitmap createImageBitmap ImageBitmapSource image optional ImageBitmapOptions options = {}); Promise ImageBitmap createImageBitmap ImageBitmapSource image long sx long sy long sw long sh optional ImageBitmapOptions options = {}); }; Window includes WindowOrWorkerGlobalScope WorkerGlobalScope includes WindowOrWorkerGlobalScope self . isSecureContext Window/isSecureContext Support in all current engines. Firefox 49+ Safari 11.1+ Chrome 47+ Opera 34+ Edge 79+ Edge (Legacy) 15+ Internet Explorer No Firefox Android 49+ Safari iOS 11.3+ Chrome Android 47+ WebView Android 47+ Samsung Internet 5.0+ Opera Android 34+ WindowOrWorkerGlobalScope/isSecureContext Firefox 52+ Safari Chrome 55+ Opera Edge 79+ Edge (Legacy) No Internet Explorer Firefox Android 52+ Safari iOS Chrome Android 55+ WebView Android 55+ Samsung Internet 6.0+ Opera Android Returns whether or not this global object represents a secure context [SECURE-CONTEXTS] self . origin WindowOrWorkerGlobalScope/origin Support in all current engines. Firefox 54+ Safari 11+ Chrome 59+ Opera No Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 54+ Safari iOS 11+ Chrome Android 59+ WebView Android 59+ Samsung Internet 7.0+ Opera Android No Returns the global object's origin , serialized as string. self . crossOriginIsolated WindowOrWorkerGlobalScope/crossOriginIsolated Firefox 72+ Safari No Chrome 87+ Opera 73+ Edge 87+ Edge (Legacy) No Internet Explorer No Firefox Android No Safari iOS No Chrome Android 87+ WebView Android No Samsung Internet 14.0+ Opera Android No Returns whether scripts running in this global are allowed to use APIs that require cross-origin isolation. This depends on the ` Cross-Origin-Opener-Policy ` and Cross-Origin-Embedder-Policy ` HTTP response headers and the " cross-origin-isolated " feature. Developers are strongly encouraged to use self.origin over location.origin . The former returns the origin of the environment, the latter of the URL of the environment. Imagine the following script executing in a document on var frame document createElement "iframe" frame onload function () var frameWin frame contentWindow console log frameWin location origin // "null" console log frameWin origin // "https://stargate.example" document body appendChild frame self.origin is a more reliable security indicator. The isSecureContext getter steps are to return true if this 's relevant settings object is a secure context , or false otherwise. The origin getter steps are to return this 's relevant settings object 's origin serialized The crossOriginIsolated getter steps are to return this 's relevant settings object 's cross-origin isolated capability 8.3 Base64 utility methods WindowOrWorkerGlobalScope/atob Support in all current engines. Firefox 1+ Safari 3+ Chrome 4+ Opera 10.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android ≤37+ Samsung Internet 1.0+ Opera Android 11+ The atob() and btoa() methods allow developers to transform content to and from the base64 encoding. In these APIs, for mnemonic purposes, the "b" can be considered to stand for "binary", and the "a" for "ASCII". In practice, though, for primarily historical reasons, both the input and output of these functions are Unicode strings. result = self . btoa data WindowOrWorkerGlobalScope/btoa Support in all current engines. Firefox 1+ Safari 3+ Chrome 4+ Opera 10.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11+ Takes the input data, in the form of a Unicode string containing only characters in the range U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF respectively, and converts it to its base64 representation, which it returns. Throws an InvalidCharacterError DOMException exception if the input string contains any out-of-range characters. result = self . atob data WindowOrWorkerGlobalScope/atob Support in all current engines. Firefox 1+ Safari 3+ Chrome 4+ Opera 10.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11+ Takes the input data, in the form of a Unicode string containing base64-encoded binary data, decodes it, and returns a string consisting of characters in the range U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF respectively, corresponding to that binary data. Throws an InvalidCharacterError DOMException if the input string is not valid base64 data. The btoa( data method must throw an InvalidCharacterError DOMException if data contains any character whose code point is greater than U+00FF. Otherwise, the user agent must convert data to a byte sequence whose th byte is the eight-bit representation of the th code point of data , and then must apply forgiving-base64 encode to that byte sequence and return the result. The atob( data method, when invoked, must run the following steps: Let decodedData be the result of running forgiving-base64 decode on data If decodedData is failure, then throw an InvalidCharacterError DOMException Return decodedData 8.4 Dynamic markup insertion APIs for dynamically inserting markup into the document interact with the parser, and thus their behavior varies depending on whether they are used with HTML documents (and the HTML parser ) or XML documents (and the XML parser ). Document objects have a throw-on-dynamic-markup-insertion counter which is used in conjunction with the create an element for the token algorithm to prevent custom element constructors from being able to use document.open() document.close() , and document.write() when they are invoked by the parser. Initially, the counter must be set to zero. 8.4.1 Opening the input stream document document open ( ) Document/open Support in all current engines. Firefox 1+ Safari 11+ Chrome 64+ Opera 51+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 11+ Chrome Android 64+ WebView Android 64+ Samsung Internet 9.0+ Opera Android 47+ Causes the Document to be replaced in-place, as if it was a new Document object, but reusing the previous object, which is then returned. The resulting Document has an HTML parser associated with it, which can be given data to parse using document.write() The method has no effect if the Document is still being parsed. Throws an InvalidStateError DOMException if the Document is an XML document Throws an InvalidStateError DOMException if the parser is currently executing a custom element constructor window document open url name features Works like the window.open() method. Document objects have an active parser was aborted boolean, which is used to prevent scripts from invoking the document.open() and document.write() methods (directly or indirectly) after the document's active parser has been aborted. It is initially false. The document open steps , given a document , are as follows: If document is an XML document , then throw an InvalidStateError DOMException exception. If document 's throw-on-dynamic-markup-insertion counter is greater than 0, then throw an InvalidStateError DOMException Let entryDocument be the entry global object 's associated Document If document 's origin is not same origin to entryDocument 's origin , then throw a SecurityError DOMException If document has an active parser whose script nesting level is greater than 0, then return document This basically causes document.open() to be ignored when it's called in an inline script found during parsing, while still letting it have an effect when called from a non-parser task such as a timer callback or event handler. Similarly, if document 's unload counter is greater than 0, then return document This basically causes document.open() to be ignored when it's called from a beforeunload pagehide , or unload event handler while the Document is being unloaded. If document 's active parser was aborted is true, then return document This notably causes document.open() to be ignored if it is called after a has started, but only during the initial parse. See issue #4723 for more background. If document 's browsing context is non-null and there is an existing attempt to navigate document 's browsing context , then stop document loading given document Issue #3447 looks into the distinction between an ongoing instance of the navigate algorithm versus tasks to navigate that are still queued. For the purpose of implementing this step, both an ongoing instance of the navigate algorithm and tasks queued to navigate should be counted towards "an existing attempt to navigate ," at least until that issue is resolved. For each shadow-including inclusive descendant node of document erase all event listeners and handlers given node If document is the associated Document of document 's relevant global object , then erase all event listeners and handlers given document 's relevant global object Replace all with null within document , without firing any mutation events. If document is fully active , then: Let newURL be a copy of entryDocument 's URL If entryDocument is not document , then set newURL 's fragment to null. Run the URL and history update steps with document and newURL Set document 's is initial about:blank to false. If document 's iframe load in progress flag is set, then set document 's mute iframe load flag. Set document to no-quirks mode Create a new HTML parser and associate it with document . This is a script-created parser (meaning that it can be closed by the document.open() and document.close() methods, and that the tokenizer will wait for an explicit call to document.close() before emitting an end-of-file token). The encoding confidence is irrelevant Set the insertion point to point at just before the end of the input stream (which at this point will be empty). Update the current document readiness of document to " loading ". This causes a readystatechange event to fire, but the event is actually unobservable to author code, because of the previous step which erased all event listeners and handlers that could observe it. Return document The document open steps do not affect whether a Document is ready for post-load tasks or completely loaded The open( unused1 unused2 method must return the result of running the document open steps with this Document object. The unused1 and unused2 arguments are ignored, but kept in the IDL to allow code that calls the function with one or two arguments to continue working. They are necessary due to Web IDL overload resolution algorithm rules, which would throw a TypeError exception for such calls had the arguments not been there. heycam/webidl issue #581 investigates changing the algorithm to allow for their removal. [WEBIDL] The open( url name features method must run these steps: If this Document object is not an active document , then throw an InvalidAccessError DOMException exception. Return the result of running the window open steps with url name , and features 8.4.2 Closing the input stream document close () Document/close Support in all current engines. Firefox 1+ Safari 11+ Chrome 64+ Opera 51+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 11+ Chrome Android 64+ WebView Android 64+ Samsung Internet 9.0+ Opera Android 47+ Closes the input stream that was opened by the document.open() method. Throws an InvalidStateError DOMException if the Document is an XML document Throws an InvalidStateError DOMException if the parser is currently executing a custom element constructor The close() method must run the following steps: If the Document object is an XML document , then throw an InvalidStateError DOMException If the Document object's throw-on-dynamic-markup-insertion counter is greater than zero, then throw an InvalidStateError DOMException If there is no script-created parser associated with the document, then return. Insert an explicit "EOF" character at the end of the parser's input stream If there is a pending parsing-blocking script , then return. Run the tokenizer, processing resulting tokens as they are emitted, and stopping when the tokenizer reaches the explicit "EOF" character or spins the event loop 8.4.3 document.write() document write text ...) Document/write Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 3+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android 4+ Safari iOS 1+ Chrome Android 18+ WebView Android 1+ Samsung Internet 1.0+ Opera Android 10.1+ In general, adds the given string(s) to the Document 's input stream. This method has very idiosyncratic behavior. In some cases, this method can affect the state of the HTML parser while the parser is running, resulting in a DOM that does not correspond to the source of the document (e.g. if the string written is the string " or " script src "compose-mail.js" > script script var channel new MessageChannel (); composer addContactsProvider channel port1 ); contacts registerConsumer channel port2 ); script Here's what the "addContactsProvider()" function's implementation could look like: function addContactsProvider port port onmessage function event switch event data messageType 'search-result' handleSearchResult event data results ); break 'search-done' handleSearchDone (); break 'search-error' handleSearchError event data message ); break // ... }; }; Alternatively, it could be implemented as follows: function addContactsProvider port port addEventListener 'message' function event if event data messageType == 'search-result' handleSearchResult event data results ); }); port addEventListener 'message' function event if event data messageType == 'search-done' handleSearchDone (); }); port addEventListener 'message' function event if event data messageType == 'search-error' handleSearchError event data message ); }); // ... port start (); }; The key difference is that when using addEventListener() , the start() method must also be invoked. When using onmessage , the call to start() is implied. The start() method, whether called explicitly or implicitly (by setting onmessage ), starts the flow of messages: messages posted on message ports are initially paused, so that they don't get dropped on the floor before the script has had a chance to set up its handlers. 9.5.1.2 Ports as the basis of an object-capability model on the web This section is non-normative. Ports can be viewed as a way to expose limited capabilities (in the object-capability model sense) to other actors in the system. This can either be a weak capability system, where the ports are merely used as a convenient model within a particular origin, or as a strong capability model, where they are provided by one origin provider as the only mechanism by which another origin consumer can effect change in or obtain information from provider For example, consider a situation in which a social web site embeds in one iframe the user's email contacts provider (an address book site, from a second origin), and in a second iframe a game (from a third origin). The outer social site and the game in the second iframe cannot access anything inside the first iframe ; together they can only: Navigate the iframe to a new URL , such as the same URL but with a different fragment causing the Window in the iframe to receive a hashchange event. Resize the iframe , causing the Window in the iframe to receive a resize event. Send a message event to the Window in the iframe using the window.postMessage() API. The contacts provider can use these methods, most particularly the third one, to provide an API that can be accessed by other origins to manipulate the user's address book. For example, it could respond to a message " add-contact Guillaume Tell " by adding the given person and email address to the user's address book. To avoid any site on the web being able to manipulate the user's contacts, the contacts provider might only allow certain trusted sites, such as the social site, to do this. Now suppose the game wanted to add a contact to the user's address book, and that the social site was willing to allow it to do so on its behalf, essentially "sharing" the trust that the contacts provider had with the social site. There are several ways it could do this; most simply, it could just proxy messages between the game site and the contacts site. However, this solution has a number of difficulties: it requires the social site to either completely trust the game site not to abuse the privilege, or it requires that the social site verify each request to make sure it's not a request that it doesn't want to allow (such as adding multiple contacts, reading the contacts, or deleting them); it also requires some additional complexity if there's ever the possibility of multiple games simultaneously trying to interact with the contacts provider. Using message channels and MessagePort objects, however, all of these problems can go away. When the game tells the social site that it wants to add a contact, the social site can ask the contacts provider not for it to add a contact, but for the capability to add a single contact. The contacts provider then creates a pair of MessagePort objects, and sends one of them back to the social site, who forwards it on to the game. The game and the contacts provider then have a direct connection, and the contacts provider knows to only honor a single "add contact" request, nothing else. In other words, the game has been granted the capability to add a single contact. 9.5.1.3 Ports as the basis of abstracting out service implementations This section is non-normative. Continuing the example from the previous section, consider the contacts provider in particular. While an initial implementation might have simply used XMLHttpRequest objects in the service's iframe , an evolution of the service might instead want to use a shared worker with a single WebSocket connection. If the initial design used MessagePort objects to grant capabilities, or even just to allow multiple simultaneous independent sessions, the service implementation can switch from the XMLHttpRequest s-in-each- iframe model to the shared- WebSocket model without changing the API at all: the ports on the service provider side can all be forwarded to the shared worker without it affecting the users of the API in the slightest. 9.5.2 Message channels MessageChannel Support in all current engines. Firefox 41+ Safari 5+ Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 41+ Safari iOS 5.1+ Chrome Android 18+ WebView Android 4.4+ Samsung Internet 1.0+ Opera Android 11+ Exposed =( Window Worker )] interface MessageChannel constructor (); readonly attribute MessagePort port1 readonly attribute MessagePort port2 }; channel = new MessageChannel () MessageChannel/MessageChannel Support in all current engines. Firefox 41+ Safari 5+ Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 41+ Safari iOS 5.1+ Chrome Android 18+ WebView Android 4.4+ Samsung Internet 1.0+ Opera Android 11+ Returns a new MessageChannel object with two new MessagePort objects. channel port1 MessageChannel/port1 Support in all current engines. Firefox 41+ Safari 5+ Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 41+ Safari iOS 5.1+ Chrome Android 18+ WebView Android 4.4+ Samsung Internet 1.0+ Opera Android 11+ Returns the first MessagePort object. channel port2 MessageChannel/port2 Support in all current engines. Firefox 41+ Safari 5+ Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 41+ Safari iOS 5.1+ Chrome Android 18+ WebView Android 4.4+ Samsung Internet 1.0+ Opera Android 11+ Returns the second MessagePort object. MessageChannel object has an associated port 1 and an associated port 2 , both MessagePort objects. The new MessageChannel() constructor steps are: Set this 's port 1 to a new MessagePort in this 's relevant Realm Set this 's port 2 to a new MessagePort in this 's relevant Realm Entangle this 's port 1 and this 's port 2 The port1 getter steps are to return this 's port 1 The port2 getter steps are to return this 's port 2 9.5.3 Message ports MessagePort Support in all current engines. Firefox 41+ Safari 5+ Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 41+ Safari iOS 5.1+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11+ Each channel has two message ports. Data sent through one port is received by the other port, and vice versa. Exposed =( Window Worker AudioWorklet ), Transferable interface MessagePort EventTarget undefined postMessage any message sequence object transfer ); undefined postMessage any message optional PostMessageOptions options = {}); undefined start (); undefined close ();
// event handlers attribute EventHandler onmessage attribute EventHandler onmessageerror }; dictionary PostMessageOptions sequence object transfer = []; }; port postMessage message [, transfer ] ) MessagePort/postMessage Support in all current engines. Firefox 41+ Safari 5+ Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 41+ Safari iOS 5.1+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11+ port postMessage message [, { transfer }] ) Posts a message through the channel. Objects listed in transfer are transferred, not just cloned, meaning that they are no longer usable on the sending side. Throws a DataCloneError DOMException if transfer contains duplicate objects or port , or if message could not be cloned. port start () MessagePort/start Support in all current engines. Firefox 41+ Safari 5+ Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 41+ Safari iOS 5.1+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11+ Begins dispatching messages received on the port. port close () MessagePort/close Support in all current engines. Firefox 41+ Safari 5+ Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 41+ Safari iOS 5.1+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11+ Disconnects the port, so that it is no longer active. Each MessagePort object can be entangled with another (a symmetric relationship). Each MessagePort object also has a task source called the port message queue , initially empty. A port message queue can be enabled or disabled, and is initially disabled. Once enabled, a port can never be disabled again (though messages in the queue can get moved to another queue or removed altogether, which has much the same effect). A MessagePort also has a has been shipped flag, which must initially be false. When a port's port message queue is enabled, the event loop must use it as one of its task sources . When a port's relevant global object is a Window , all tasks queued on its port message queue must be associated with the port's relevant global object 's associated Document If the document is fully active , but the event listeners all have scripts whose settings objects specify responsible documents that are not fully active , then the messages will not be received unless and until the documents become fully active again. Each event loop has a task source called the unshipped port message queue . This is a virtual task source : it must act as if it contained the tasks of each port message queue of each MessagePort whose has been shipped flag is false, whose port message queue is enabled, and whose relevant agent 's event loop is that event loop , in the order in which they were added to their respective task source . When a task would be removed from the unshipped port message queue , it must instead be removed from its port message queue When a MessagePort 's has been shipped flag is false, its port message queue must be ignored for the purposes of the event loop . (The unshipped port message queue is used instead.) The has been shipped flag is set to true when a port, its twin, or the object it was cloned from, is or has been transferred. When a MessagePort 's has been shipped flag is true, its port message queue acts as a first-class task source , unaffected to any unshipped port message queue When the user agent is to entangle two MessagePort objects, it must run the following steps: If one of the ports is already entangled, then disentangle it and the port that it was entangled with. If those two previously entangled ports were the two ports of a MessageChannel object, then that MessageChannel object no longer represents an actual channel: the two ports in that object are no longer entangled. Associate the two ports to be entangled, so that they form the two parts of a new channel. (There is no MessageChannel object that represents this channel.) Two ports and that have gone through this step are now said to be entangled; one is entangled to the other, and vice versa. While this specification describes this process as instantaneous, implementations are more likely to implement it via message passing. As with all algorithms, the key is "merely" that the end result be indistinguishable, in a black-box sense, from the specification. MessagePort objects are transferable objects . Their transfer steps , given value and dataHolder , are: Set value 's has been shipped flag to true. Set dataHolder .[[PortMessageQueue]] to value 's port message queue If value is entangled with another port remotePort , then: Set remotePort 's has been shipped flag to true. Set dataHolder .[[RemotePort]] to remotePort Otherwise, set dataHolder .[[RemotePort]] to null. Their transfer-receiving steps , given dataHolder and value are: Set value 's has been shipped flag to true. Move all the tasks that are to fire message events in dataHolder .[[PortMessageQueue]] to the port message queue of value , if any, leaving value 's port message queue in its initial disabled state, and, if value 's relevant global object is a Window , associating the moved tasks with value 's relevant global object 's associated Document If dataHolder .[[RemotePort]] is not null, then entangle dataHolder .[[RemotePort]] and value . (This will disentangle dataHolder .[[RemotePort]] from the original port that was transferred.) The message port post message steps , given a targetPort message and options are as follows: Let transfer be options [" transfer "]. If transfer contains this MessagePort , then throw a DataCloneError DOMException Let doomed be false. If targetPort is not null and transfer contains targetPort , then set doomed to true and optionally report to a developer console that the target port was posted to itself, causing the communication channel to be lost. Let serializeWithTransferResult be StructuredSerializeWithTransfer message transfer ). Rethrow any exceptions. If targetPort is null, or if doomed is true, then return. Add a task that runs the following steps to the port message queue of targetPort Let finalTargetPort be the MessagePort in whose port message queue the task now finds itself. This can be different from targetPort , if targetPort itself was transferred and thus all its tasks moved along with it. Let targetRealm be finalTargetPort 's relevant Realm Let deserializeRecord be StructuredDeserializeWithTransfer serializeWithTransferResult targetRealm ). If this throws an exception, catch it, fire an event named messageerror at finalTargetPort , using MessageEvent , and then return. Let messageClone be deserializeRecord .[[Deserialized]]. Let newPorts be a new frozen array consisting of all MessagePort objects in deserializeRecord .[[TransferredValues]], if any, maintaining their relative order. Fire an event named message at finalTargetPort , using MessageEvent , with the data attribute initialized to messageClone and the ports attribute initialized to newPorts The postMessage( message options method, when invoked on a MessagePort object must run the following steps: Let targetPort be the port with which this MessagePort is entangled, if any; otherwise let it be null. Run the message port post message steps providing targetPort message and options The postMessage( message transfer method, when invoked on a MessagePort object must run the following steps: Let targetPort be the port with which this MessagePort is entangled, if any; otherwise let it be null. Let options be «[ " transfer " → transfer ]». Run the message port post message steps providing targetPort message and options The start() method, when invoked, must enable this MessagePort object's port message queue , if it is not already enabled. The close() method, when invoked, must run these steps: Set this MessagePort object's [[Detached]] internal slot value to true. If this MessagePort object is entangled, disentangle it. The following are the event handlers (and their corresponding event handler event types ) that must be supported, as event handler IDL attributes , by all objects implementing the MessagePort interface: Event handler Event handler event type onmessage MessagePort/onmessage Support in all current engines. Firefox 41+ Safari 5+ Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 41+ Safari iOS 5.1+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11+ message onmessageerror MessagePort/onmessageerror Firefox 57+ Safari No Chrome 60+ Opera 47+ Edge 79+ Edge (Legacy) 18 Internet Explorer No Firefox Android 57+ Safari iOS No Chrome Android 60+ WebView Android 60+ Samsung Internet 8.0+ Opera Android 44+ messageerror The first time a MessagePort object's onmessage IDL attribute is set, the port's port message queue must be enabled, as if the start() method had been called. 9.5.4 Broadcasting to many ports This section is non-normative. Broadcasting to many ports is in principle relatively simple: keep an array of MessagePort objects to send messages to, and iterate through the array to send a message. However, this has one rather unfortunate effect: it prevents the ports from being garbage collected, even if the other side has gone away. To avoid this problem, implement a simple protocol whereby the other side acknowledges it still exists. If it doesn't do so after a certain amount of time, assume it's gone, close the MessagePort object, and let it be garbage collected. 9.5.5 Ports and garbage collection When a MessagePort object is entangled, user agents must either act as if 's entangled MessagePort object has a strong reference to , or as if 's relevant global object has a strong reference to Thus, a message port can be received, given an event listener, and then forgotten, and so long as that event listener could receive a message, the channel will be maintained. Of course, if this was to occur on both sides of the channel, then both ports could be garbage collected, since they would not be reachable from live code, despite having a strong reference to each other. Furthermore, a MessagePort object must not be garbage collected while there exists an event referenced by a task in a task queue that is to be dispatched on that MessagePort object, or while the MessagePort object's port message queue is enabled and not empty. Authors are strongly encouraged to explicitly close MessagePort objects to disentangle them, so that their resources can be recollected. Creating many MessagePort objects and discarding them without closing them can lead to high transient memory usage since garbage collection is not necessarily performed promptly, especially for MessagePort s where garbage collection can involve cross-process coordination. 9.6 Broadcasting to other browsing contexts Broadcast_Channel_API Firefox 38+ Safari No Chrome 54+ Opera 41+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 38+ Safari iOS No Chrome Android 54+ WebView Android 54+ Samsung Internet 6.0+ Opera Android 41+ Pages on a single origin opened by the same user in the same user agent but in different unrelated browsing contexts sometimes need to send notifications to each other, for example "hey, the user logged in over here, check your credentials again". For elaborate cases, e.g. to manage locking of shared state, to manage synchronization of resources between a server and multiple local clients, to share a WebSocket connection with a remote host, and so forth, shared workers are the most appropriate solution. For simple cases, though, where a shared worker would be an unreasonable overhead, authors can use the simple channel-based broadcast mechanism described in this section. BroadcastChannel Firefox 38+ Safari No Chrome 54+ Opera 41+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 38+ Safari iOS No Chrome Android 54+ WebView Android 54+ Samsung Internet 6.0+ Opera Android 41+ Exposed =( Window Worker )] interface BroadcastChannel EventTarget constructor DOMString name ); readonly attribute DOMString name undefined postMessage any message ); undefined close (); attribute EventHandler onmessage attribute EventHandler onmessageerror }; broadcastChannel = new BroadcastChannel name BroadcastChannel/BroadcastChannel Firefox 38+ Safari No Chrome 54+ Opera 41+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 38+ Safari iOS No Chrome Android 54+ WebView Android 54+ Samsung Internet 6.0+ Opera Android 41+ Returns a new BroadcastChannel object via which messages for the given channel name can be sent and received. broadcastChannel name BroadcastChannel/name Firefox 38+ Safari No Chrome 54+ Opera 41+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 38+ Safari iOS No Chrome Android 54+ WebView Android 54+ Samsung Internet 6.0+ Opera Android 41+ Returns the channel name (as passed to the constructor). broadcastChannel postMessage message BroadcastChannel/postMessage Firefox 38+ Safari No Chrome 54+ Opera 41+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 38+ Safari iOS No Chrome Android 54+ WebView Android 54+ Samsung Internet 6.0+ Opera Android 41+ Sends the given message to other BroadcastChannel objects set up for this channel. Messages can be structured objects, e.g. nested objects and arrays. broadcastChannel close () BroadcastChannel/close Firefox 38+ Safari No Chrome 54+ Opera 41+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 38+ Safari iOS No Chrome Android 54+ WebView Android 54+ Samsung Internet 6.0+ Opera Android 41+ Closes the BroadcastChannel object, opening it up to garbage collection. BroadcastChannel object has a channel name and a closed flag The new BroadcastChannel( name constructor steps are: Set this 's channel name to name Set this 's closed flag to false. The name getter steps are to return this 's channel name The postMessage( message method steps are: If this 's closed flag is true, then throw an InvalidStateError DOMException Let serialized be StructuredSerialize message ). Rethrow any exceptions. Let sourceOrigin be this 's relevant settings object 's origin Let destinations be a list of BroadcastChannel objects that match the following criteria: Their relevant global object is either: Window object whose associated Document is fully active , or WorkerGlobalScope object whose closing flag is false and whose worker is not a suspendable worker Their relevant settings object 's origin is same origin with sourceOrigin Their channel name is this 's channel name Remove source from destinations Sort destinations such that all BroadcastChannel objects whose relevant agents are the same are sorted in creation order, oldest first. (This does not define a complete ordering. Within this constraint, user agents may sort the list in any implementation-defined manner.) For each destination in destinations queue a global task on the DOM manipulation task source given destination 's relevant global object to perform the following steps: If destination 's closed flag is true, then abort these steps. Let targetRealm be destination 's relevant Realm Let data be StructuredDeserialize serialized targetRealm ). If this throws an exception, catch it, fire an event named messageerror at destination , using MessageEvent , with the origin attribute initialized to the serialization of sourceOrigin , and then abort these steps. Fire an event named message at destination , using MessageEvent , with the data attribute initialized to data and the origin attribute initialized to the serialization of sourceOrigin While a BroadcastChannel object whose closed flag is false has an event listener registered for message or messageerror events, there must be a strong reference from the BroadcastChannel object's relevant global object to the BroadcastChannel object itself. The close() method steps are to set this 's closed flag to true. Authors are strongly encouraged to explicitly close BroadcastChannel objects when they are no longer needed, so that they can be garbage collected. Creating many BroadcastChannel objects and discarding them while leaving them with an event listener and without closing them can lead to an apparent memory leak, since the objects will continue to live for as long as they have an event listener (or until their page or worker is closed). The following are the event handlers (and their corresponding event handler event types ) that must be supported, as event handler IDL attributes , by all objects implementing the BroadcastChannel interface: Event handler Event handler event type onmessage BroadcastChannel/onmessage Firefox 38+ Safari No Chrome 54+ Opera 41+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 38+ Safari iOS No Chrome Android 54+ WebView Android 54+ Samsung Internet 6.0+ Opera Android 41+ message onmessageerror BroadcastChannel/onmessageerror Firefox 57+ Safari No Chrome 60+ Opera 47+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 57+ Safari iOS No Chrome Android 60+ WebView Android 60+ Samsung Internet 8.0+ Opera Android 44+ messageerror Suppose a page wants to know when the user logs out, even when the user does so from another tab at the same site: var authChannel new BroadcastChannel 'auth' ); authChannel onmessage function event if event data == 'logout' showLogout (); function logoutRequested () // called when the user asks us to log them out doLogout (); showLogout (); authChannel postMessage 'logout' ); function doLogout () // actually log the user out (e.g. clearing cookies) // ... function showLogout () // update the UI to indicate we're logged out // ... 10 Web workers Web_Workers_API Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 5.1+ Chrome Android 18+ WebView Android 4+ Samsung Internet 1.0+ Opera Android 11+ Web_Workers_API/Using_web_workers 10.1 Introduction 10.1.1 Scope This section is non-normative. This specification defines an API for running scripts in the background independently of any user interface scripts. This allows for long-running scripts that are not interrupted by scripts that respond to clicks or other user interactions, and allows long tasks to be executed without yielding to keep the page responsive. Workers (as these background scripts are called herein) are relatively heavy-weight, and are not intended to be used in large numbers. For example, it would be inappropriate to launch one worker for each pixel of a four megapixel image. The examples below show some appropriate uses of workers. Generally, workers are expected to be long-lived, have a high start-up performance cost, and a high per-instance memory cost. 10.1.2 Examples This section is non-normative. There are a variety of uses that workers can be put to. The following subsections show various examples of this use. 10.1.2.1 A background number-crunching worker This section is non-normative. The simplest use of workers is for performing a computationally expensive task without interrupting the user interface. In this example, the main document spawns a worker to (naïvely) compute prime numbers, and progressively displays the most recently found prime number. The main page is as follows: html lang "en" head meta charset "utf-8" title Worker example: One-core computation title head body The highest prime number discovered so far is: output id "result" > output > script var worker new Worker 'worker.js' ); worker onmessage function event document getElementById 'result' ). textContent event data }; script body html The Worker() constructor call creates a worker and returns a Worker object representing that worker, which is used to communicate with the worker. That object's onmessage event handler allows the code to receive messages from the worker. The worker itself is as follows: var while true += for var <= Math sqrt ); += if == continue // found a prime! postMessage ); The bulk of this code is simply an unoptimized search for a prime number. The postMessage() method is used to send a message back to the page when a prime is found. View this example online 10.1.2.2 Using a JavaScript module as a worker This section is non-normative. All of our examples so far show workers that run classic scripts . Workers can instead be instantiated using module scripts , which have the usual benefits: the ability to use the JavaScript import statement to import other modules; strict mode by default; and top-level declarations not polluting the worker's global scope. As the import statement is available, the importScripts() method will automatically fail inside module workers. In this example, the main document uses a worker to do off-main-thread image manipulation. It imports the filters used from another module. The main page is as follows: html lang "en" meta charset "utf-8" title Worker example: image decoding title label Type an image URL to decode input type "url" id "image-url" list "image-list" datalist id "image-list" option value "https://html.spec.whatwg.org/images/drawImage.png" option value "https://html.spec.whatwg.org/images/robots.jpeg" option value "https://html.spec.whatwg.org/images/arcTo2.png" datalist label label Choose a filter to apply select id "filter" option value "none" none option option value "grayscale" grayscale option option value "brighten" brighten by 20% option select label div id "output" > div script type "module" const worker new Worker "worker.js" type "module" }); worker onmessage receiveFromWorker const url document querySelector "#image-url" ); const filter document querySelector "#filter" ); const output document querySelector "#output" ); url oninput updateImage filter oninput sendToWorker let imageData context function updateImage () const img new Image (); img src url value img onload () => const canvas document createElement "canvas" ); canvas width img width canvas height img height context canvas getContext "2d" ); context drawImage img ); imageData context getImageData canvas width canvas height ); sendToWorker (); output replaceChildren canvas ); }; function sendToWorker () worker postMessage ({ imageData filter filter value }); function receiveFromWorker context putImageData data ); script The worker file is then: import as filters from "./filters.js" self onmessage => const imageData filter data filters filter ]( imageData ); self postMessage imageData imageData data buffer ]); }; Which imports the file filters.js export function none () {} export function grayscale ({ data }) for let length += const ], ], ]]; // CIE luminance for the RGB // The human eye is bad at seeing red and blue, so we de-emphasize them. 0.2126 0.7152 0.0722 }; export function brighten ({ data }) for let length ++ *= 1.2 }; View this example online 10.1.2.3 Shared workers introduction SharedWorker Firefox 29+ Safari 5–6.1 Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 33+ Safari iOS 5.1–7 Chrome Android No WebView Android No Samsung Internet 4.0–5.0 Opera Android 11–14 This section is non-normative. This section introduces shared workers using a Hello World example. Shared workers use slightly different APIs, since each worker can have multiple connections. This first example shows how you connect to a worker and how a worker can send a message back to the page when it connects to it. Received messages are displayed in a log. Here is the HTML page: html lang "en" meta charset "utf-8" title Shared workers: demo 1 title pre id "log" Log: pre script var worker new SharedWorker 'test.js' ); var log document getElementById 'log' ); worker port onmessage function // note: not worker.onmessage! log textContent += '\n' data script Here is the JavaScript worker: onconnect function var port ports ]; port postMessage 'Hello World!' ); View this example online This second example extends the first one by changing two things: first, messages are received using addEventListener() instead of an event handler IDL attribute , and second, a message is sent to the worker, causing the worker to send another message in return. Received messages are again displayed in a log. Here is the HTML page: html lang "en" meta charset "utf-8" title Shared workers: demo 2 title pre id "log" Log: pre script var worker new SharedWorker 'test.js' ); var log document getElementById 'log' ); worker port addEventListener 'message' function log textContent += '\n' data }, false ); worker port start (); // note: need this when using addEventListener worker port postMessage 'ping' ); script Here is the JavaScript worker: onconnect function var port ports ]; port postMessage 'Hello World!' ); port onmessage function port postMessage 'pong' ); // not e.ports[0].postMessage! // e.target.postMessage('pong'); would work also View this example online Finally, the example is extended to show how two pages can connect to the same worker; in this case, the second page is merely in an iframe on the first page, but the same principle would apply to an entirely separate page in a separate top-level browsing context Here is the outer HTML page: html lang "en" meta charset "utf-8" title Shared workers: demo 3 title pre id "log" Log: pre script var worker new SharedWorker 'test.js' ); var log document getElementById 'log' ); worker port addEventListener 'message' function log textContent += '\n' data }, false ); worker port start (); worker port postMessage 'ping' ); script iframe src "inner.html" > iframe Here is the inner HTML page: html lang "en" meta charset "utf-8" title Shared workers: demo 3 inner frame title pre id log Inner log: pre script var worker new SharedWorker 'test.js' ); var log document getElementById 'log' ); worker port onmessage function log textContent += '\n' data script Here is the JavaScript worker: var count onconnect function count += var port ports ]; port postMessage 'Hello World! You are connection #' count ); port onmessage function port postMessage 'pong' ); View this example online 10.1.2.4 Shared state using a shared worker This section is non-normative. In this example, multiple windows (viewers) can be opened that are all viewing the same map. All the windows share the same map information, with a single worker coordinating all the viewers. Each viewer can move around independently, but if they set any data on the map, all the viewers are updated. The main page isn't interesting, it merely provides a way to open the viewers: html lang "en" head meta charset "utf-8" title Workers example: Multiviewer title script function openViewer () window open 'viewer.html' ); script head body >< button type button onclick "openViewer()" Open a new viewer button > Each viewer opens in a new window. You can have as many viewers as you like, they all view the same data. body html The viewer is more involved: html lang "en" head meta charset "utf-8" title Workers example: Multiviewer viewer title script var worker new SharedWorker 'worker.js' 'core' ); // CONFIGURATION function configure event if event data substr != 'cfg ' return var name event data substr ). split ' ' )[ ]; // update display to mention our name is name document getElementsByTagName 'h1' )[ ]. textContent += ' ' name // no longer need this listener worker port removeEventListener 'message' configure false ); worker port addEventListener 'message' configure false ); // MAP function paintMap event if event data substr != 'map ' return var data event data substr ). split ',' ); // display tiles data[0] .. data[8] var canvas document getElementById 'map' ); var context canvas getContext '2d' ); for var += for var += var tile data ]; if tile == '0' context fillStyle 'green' else context fillStyle 'maroon' context fillRect 50 50 50 50 ); worker port addEventListener 'message' paintMap false ); // PUBLIC CHAT function updatePublicChat event if event data substr != 'txt ' return var name event data substr ). split ' ' )[ ]; var message event data substr name length ); // display " message" in public chat var public document getElementById 'public' ); var document createElement 'p' ); var document createElement 'button' ); textContent '<' name '> ' onclick function () worker port postMessage 'msg ' name ); }; appendChild ); var document createElement 'span' ); textContent message appendChild ); public appendChild ); worker port addEventListener 'message' updatePublicChat false ); // PRIVATE CHAT function startPrivateChat event if event data substr != 'msg ' return var name event data substr ). split ' ' )[ ]; var port event ports ]; // display a private chat UI var ul document getElementById 'private' ); var li document createElement 'li' ); var h3 document createElement 'h3' ); h3 textContent 'Private chat with ' name li appendChild h3 ); var div document createElement 'div' ); var addMessage function name message var document createElement 'p' ); var document createElement 'strong' ); textContent '<' name '> ' appendChild ); var document createElement 'span' ); textContent message appendChild ); div appendChild ); }; port onmessage function event addMessage name event data ); }; li appendChild div ); var form document createElement 'form' ); var document createElement 'p' ); var input document createElement 'input' ); input size 50 appendChild input ); appendChild document createTextNode ' ' )); var button document createElement 'button' ); button textContent 'Post' appendChild button ); form onsubmit function () port postMessage input value ); addMessage 'me' input value ); input value '' return false }; form appendChild ); li appendChild form ); ul appendChild li ); worker port addEventListener 'message' startPrivateChat false ); worker port start (); script head body h1 Viewer h1 h2 Map h2 >< canvas id "map" height 150 width 150 > canvas > button type button onclick "worker.port.postMessage('mov left')" Left button button type button onclick "worker.port.postMessage('mov up')" Up button button type button onclick "worker.port.postMessage('mov down')" Down button button type button onclick "worker.port.postMessage('mov right')" Right button button type button onclick "worker.port.postMessage('set 0')" Set 0 button button type button onclick "worker.port.postMessage('set 1')" Set 1 button h2 Public Chat h2 div id "public" > div form onsubmit "worker.port.postMessage('txt ' + message.value); message.value = ''; return false;" input type "text" name "message" size "50" button Post button form h2 Private Chat h2 ul id "private" > ul body html There are several key things worth noting about the way the viewer is written. Multiple listeners . Instead of a single message processing function, the code here attaches multiple event listeners, each one performing a quick check to see if it is relevant for the message. In this example it doesn't make much difference, but if multiple authors wanted to collaborate using a single port to communicate with a worker, it would allow for independent code instead of changes having to all be made to a single event handling function. Registering event listeners in this way also allows you to unregister specific listeners when you are done with them, as is done with the configure() method in this example. Finally, the worker: var nextName function getNextName () // this could use more friendly names // but for now just return a number return nextName ++ var map ], ], ], ], ], ], ], ]; function wrapX if return wrapX map ]. length ); if >= map ]. length return wrapX map ]. length ); return function wrapY if return wrapY map length ); if >= map ]. length return wrapY map length ); return function wrap val min max if val min return val max min if val max return val max min return val function sendMapData viewer var data '' for var viewer <= viewer += for var viewer <= viewer += if data != '' data += ',' data += map wrap map ]. length )][ wrap map length )]; viewer port postMessage 'map ' data ); var viewers {}; onconnect function event var name getNextName (); event ports ]. _data port event ports ], name name }; viewers name event ports ]. _data event ports ]. postMessage 'cfg ' name ); event ports ]. onmessage getMessage sendMapData event ports ]. _data ); }; function getMessage event switch event data substr )) case 'mov ' var direction event data substr ); var dx var dy switch direction case 'up' dy break case 'down' dy break case 'left' dx break case 'right' dx break event target _data wrapX event target _data dx ); event target _data wrapY event target _data dy ); sendMapData event target _data ); break case 'set ' var value event data substr ); map event target _data ][ event target _data value for var viewer in viewers sendMapData viewers viewer ]); break case 'txt ' var name event target _data name var message event data substr ); for var viewer in viewers viewers viewer ]. port postMessage 'txt ' name ' ' message ); break case 'msg ' var party1 event target _data var party2 viewers event data substr ). split ' ' )[ ]]; if party2 var channel new MessageChannel (); party1 port postMessage 'msg ' party2 name channel port1 ]); party2 port postMessage 'msg ' party1 name channel port2 ]); break Connecting to multiple pages . The script uses the onconnect event listener to listen for multiple connections. Direct channels . When the worker receives a "msg" message from one viewer naming another viewer, it sets up a direct connection between the two, so that the two viewers can communicate directly without the worker having to proxy all the messages. View this example online 10.1.2.5 Delegation This section is non-normative. With multicore CPUs becoming prevalent, one way to obtain better performance is to split computationally expensive tasks amongst multiple workers. In this example, a computationally expensive task that is to be performed for every number from 1 to 10,000,000 is farmed out to ten subworkers. The main page is as follows, it just reports the result: html lang "en" head meta charset "utf-8" title Worker example: Multicore computation title head body Result: output id "result" > output > script var worker new Worker 'worker.js' ); worker onmessage function event document getElementById 'result' ). textContent event data }; script body html The worker itself is as follows: // settings var num_workers 10 var items_per_worker 1000000 // start the workers var result var pending_workers num_workers for var num_workers += var worker new Worker 'core.js' ); worker postMessage items_per_worker ); worker postMessage (( items_per_worker ); worker onmessage storeResult // handle the results function storeResult event result += event data pending_workers -= if pending_workers <= postMessage result ); // finished! It consists of a loop to start the subworkers, and then a handler that waits for all the subworkers to respond. The subworkers are implemented as follows: var start onmessage getStart function getStart event start event data onmessage getEnd var end function getEnd event end event data onmessage null work (); function work () var result for var start end += // perform some complex calculation here result += postMessage result ); close (); They receive two numbers in two events, perform the computation for the range of numbers thus specified, and then report the result back to the parent. View this example online 10.1.2.6 Providing libraries This section is non-normative. Suppose that a cryptography library is made available that provides three tasks: Generate a public/private key pair Takes a port, on which it will send two messages, first the public key and then the private key. Given a plaintext and a public key, return the corresponding ciphertext Takes a port, to which any number of messages can be sent, the first giving the public key, and the remainder giving the plaintext, each of which is encrypted and then sent on that same channel as the ciphertext. The user can close the port when it is done encrypting content. Given a ciphertext and a private key, return the corresponding plaintext Takes a port, to which any number of messages can be sent, the first giving the private key, and the remainder giving the ciphertext, each of which is decrypted and then sent on that same channel as the plaintext. The user can close the port when it is done decrypting content. The library itself is as follows: function handleMessage if data == "genkeys" genkeys ports ]); else if data == "encrypt" encrypt ports ]); else if data == "decrypt" decrypt ports ]); function genkeys var keys _generateKeyPair (); postMessage keys ]); postMessage keys ]); function encrypt var key state onmessage function if state == key data state else postMessage _encrypt key data )); }; function decrypt var key state onmessage function if state == key data state else postMessage _decrypt key data )); }; // support being used as a shared worker as well as a dedicated worker if 'onmessage' in this // dedicated worker onmessage handleMessage else // shared worker onconnect function port onmessage handleMessage // the "crypto" functions: function _generateKeyPair () return Math random (), Math random ()]; function _encrypt return 'encrypted-' ' ' function _decrypt return substr indexOf ' ' ); Note that the crypto functions here are just stubs and don't do real cryptography. This library could be used as follows: html lang "en" head meta charset "utf-8" title Worker example: Crypto library title script const cryptoLib new Worker 'libcrypto-v1.js' ); // or could use 'libcrypto-v2.js' function startConversation source message const messageChannel new MessageChannel (); source postMessage message messageChannel port2 ]); return messageChannel port1 function getKeys () let state startConversation cryptoLib "genkeys" ). onmessage function if state === document getElementById 'public' ). value data else if state === document getElementById 'private' ). value data state += }; function enc () const port startConversation cryptoLib "encrypt" ); port postMessage document getElementById 'public' ). value ); port postMessage document getElementById 'input' ). value ); port onmessage function document getElementById 'input' ). value data port close (); }; function dec () const port startConversation cryptoLib "decrypt" ); port postMessage document getElementById 'private' ). value ); port postMessage document getElementById 'input' ). value ); port onmessage function document getElementById 'input' ). value data port close (); }; script style textarea display block style head body onload "getKeys()" fieldset legend Keys legend >< label Public Key: textarea id "public" > textarea > label > >< label Private Key: textarea id "private" > textarea > label > fieldset >< label Input: textarea id "input" > textarea > label > >< button onclick "enc()" Encrypt button button onclick "dec()" Decrypt button > body html A later version of the API, though, might want to offload all the crypto work onto subworkers. This could be done as follows: function handleMessage if data == "genkeys" genkeys ports ]); else if data == "encrypt" encrypt ports ]); else if data == "decrypt" decrypt ports ]); function genkeys var generator new Worker 'libcrypto-v2-generator.js' ); generator postMessage '' ]); function encrypt onmessage function var key data var encryptor new Worker 'libcrypto-v2-encryptor.js' ); encryptor postMessage key ]); }; function encrypt onmessage function var key data var decryptor new Worker 'libcrypto-v2-decryptor.js' ); decryptor postMessage key ]); }; // support being used as a shared worker as well as a dedicated worker if 'onmessage' in this // dedicated worker onmessage handleMessage else // shared worker onconnect function ports ]. onmessage handleMessage }; The little subworkers would then be as follows. For generating key pairs: onmessage function var _generateKeyPair (); ports ]. postMessage ]); ports ]. postMessage ]); close (); function _generateKeyPair () return Math random (), Math random ()]; For encrypting: onmessage function var key data ports ]. onmessage function var data postMessage _encrypt key )); function _encrypt return 'encrypted-' ' ' For decrypting: onmessage function var key data ports ]. onmessage function var data postMessage _decrypt key )); function _decrypt return substr indexOf ' ' ); Notice how the users of the API don't have to even know that this is happening — the API hasn't changed; the library can delegate to subworkers without changing its API, even though it is accepting data using message channels. View this example online 10.1.3 Tutorials 10.1.3.1 Creating a dedicated worker This section is non-normative. Creating a worker requires a URL to a JavaScript file. The Worker() constructor is invoked with the URL to that file as its only argument; a worker is then created and returned: var worker new Worker 'helper.js' ); If you want your worker script to be interpreted as a module script instead of the default classic script , you need to use a slightly different signature: var worker new Worker 'helper.mjs' type "module" }); 10.1.3.2 Communicating with a dedicated worker This section is non-normative. Dedicated workers use MessagePort objects behind the scenes, and thus support all the same features, such as sending structured data, transferring binary data, and transferring other ports. To receive messages from a dedicated worker, use the onmessage event handler IDL attribute on the Worker object: worker onmessage function event ... }; You can also use the addEventListener() method. The implicit MessagePort used by dedicated workers has its port message queue implicitly enabled when it is created, so there is no equivalent to the MessagePort interface's start() method on the Worker interface. To send data to a worker, use the postMessage() method. Structured data can be sent over this communication channel. To send ArrayBuffer objects efficiently (by transferring them rather than cloning them), list them in an array in the second argument. worker postMessage ({ operation 'find-edges' input buffer // an ArrayBuffer object threshold 0.6 }, buffer ]); To receive a message inside the worker, the onmessage event handler IDL attribute is used. onmessage function event ... }; You can again also use the addEventListener() method. In either case, the data is provided in the event object's data attribute. To send messages back, you again use postMessage() . It supports the structured data in the same manner. postMessage event data input event data input ]); // transfer the buffer back 10.1.3.3 Shared workers SharedWorker Firefox 29+ Safari 5–6.1 Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 33+ Safari iOS 5.1–7 Chrome Android No WebView Android No Samsung Internet 4.0–5.0 Opera Android 11–14 This section is non-normative. Shared workers are identified by the URL of the script used to create it, optionally with an explicit name. The name allows multiple instances of a particular shared worker to be started. Shared workers are scoped by origin . Two different sites using the same names will not collide. However, if a page tries to use the same shared worker name as another page on the same site, but with a different script URL, it will fail. Creating shared workers is done using the SharedWorker() constructor. This constructor takes the URL to the script to use for its first argument, and the name of the worker, if any, as the second argument. var worker new SharedWorker 'service.js' ); Communicating with shared workers is done with explicit MessagePort objects. The object returned by the SharedWorker() constructor holds a reference to the port on its port attribute. worker port onmessage function event ... }; worker port postMessage 'some message' ); worker port postMessage ({ foo 'structured' bar 'data' 'also' 'possible' ]}); Inside the shared worker, new clients of the worker are announced using the connect event. The port for the new client is given by the event object's source attribute. onconnect function event var newPort event source // set up a listener newPort onmessage function event ... }; // send a message back to the port newPort postMessage 'ready!' ); // can also send structured data, of course }; 10.2 Infrastructure This standard defines two kinds of workers: dedicated workers, and shared workers. Dedicated workers, once created, are linked to their creator, but message ports can be used to communicate from a dedicated worker to multiple other browsing contexts or workers. Shared workers, on the other hand, are named, and once created any script running in the same origin can obtain a reference to that worker and communicate with it. Service Workers defines a third kind. [SW] 10.2.1 The global scope The global scope is the "inside" of a worker. 10.2.1.1 The WorkerGlobalScope common interface WorkerGlobalScope Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 3.2+ Chrome Android Yes WebView Android 37+ Samsung Internet Yes Opera Android 11+ Exposed Worker interface WorkerGlobalScope EventTarget readonly attribute WorkerGlobalScope self readonly attribute WorkerLocation location readonly attribute WorkerNavigator navigator undefined importScripts USVString ... urls ); attribute OnErrorEventHandler onerror attribute EventHandler onlanguagechange attribute EventHandler onoffline attribute EventHandler ononline attribute EventHandler onrejectionhandled attribute EventHandler onunhandledrejection }; WorkerGlobalScope serves as the base class for specific types of worker global scope objects, including DedicatedWorkerGlobalScope SharedWorkerGlobalScope , and ServiceWorkerGlobalScope WorkerGlobalScope object has an associated owner set (a set of Document and WorkerGlobalScope objects). It is initially empty and populated when the worker is created or obtained. It is a set , instead of a single owner, to accommodate SharedWorkerGlobalScope objects. WorkerGlobalScope object has an associated type (" classic " or " module "). It is set during creation. WorkerGlobalScope object has an associated url (null or a URL ). It is initially null. WorkerGlobalScope object has an associated name (a string). It is set during creation. The name can have different semantics for each subclass of WorkerGlobalScope . For DedicatedWorkerGlobalScope instances, it is simply a developer-supplied name, useful mostly for debugging purposes. For SharedWorkerGlobalScope instances, it allows obtaining a reference to a common shared worker via the SharedWorker() constructor. For ServiceWorkerGlobalScope objects, it doesn't make sense (and as such isn't exposed through the JavaScript API at all). WorkerGlobalScope object has an associated policy container (a policy container ). It is initially a new policy container WorkerGlobalScope object has an associated referrer policy (a referrer policy ). It is initially the empty string. WorkerGlobalScope object has an associated embedder policy (an embedder policy ). WorkerGlobalScope object has an associated module map . It is a module map initially empty. WorkerGlobalScope object has an associated cross-origin isolated capability boolean. It is initially false. workerGlobal self WorkerGlobalScope/self Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 11.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer Yes Firefox Android 34+ Safari iOS 5.1+ Chrome Android 40+ WebView Android 37+ Samsung Internet 4.0+ Opera Android Yes Returns workerGlobal workerGlobal location WorkerGlobalScope/location Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 11.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer Yes Firefox Android 4+ Safari iOS 5.1+ Chrome Android 40+ WebView Android 37+ Samsung Internet 4.0+ Opera Android Yes Returns workerGlobal 's WorkerLocation object. workerGlobal navigator WorkerGlobalScope/navigator Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 11.5+ Edge 79+ Edge (Legacy) 17+ Internet Explorer Yes Firefox Android 4+ Safari iOS 5.1+ Chrome Android 40+ WebView Android 37+ Samsung Internet 4.0+ Opera Android Yes Returns workerGlobal 's WorkerNavigator object. workerGlobal importScripts urls ...) WorkerGlobalScope/importScripts Support in all current engines. Firefox 4+ Safari 4+ Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 3.2+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11+ Fetches each URL in urls , executes them one-by-one in the order they are passed, and then returns (or throws if something went amiss). The self attribute must return the WorkerGlobalScope object itself. The location attribute must return the WorkerLocation object whose associated WorkerGlobalScope object is the WorkerGlobalScope object. While the WorkerLocation object is created after the WorkerGlobalScope object, this is not problematic as it cannot be observed from script. The following are the event handlers (and their corresponding event handler event types ) that must be supported, as event handler IDL attributes , by objects implementing the WorkerGlobalScope interface: Event handler Event handler event type onerror WorkerGlobalScope/onerror Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 11.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer Yes Firefox Android 4+ Safari iOS 5.1+ Chrome Android 40+ WebView Android 37+ Samsung Internet 4.0+ Opera Android Yes error onlanguagechange WorkerGlobalScope/onlanguagechange Support in all current engines. Firefox 74+ Safari 4+ Chrome 4+ Opera 11.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer Yes Firefox Android No Safari iOS 5.1+ Chrome Android 40+ WebView Android 37+ Samsung Internet 4.0+ Opera Android Yes languagechange onoffline WorkerGlobalScope/onoffline Support in all current engines. Firefox 29+ Safari Yes Chrome 4+ Opera Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 29+ Safari iOS Yes Chrome Android 40+ WebView Android 40+ Samsung Internet 4.0+ Opera Android offline ononline WorkerGlobalScope/ononline Support in all current engines. Firefox 29+ Safari Yes Chrome 4+ Opera Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 29+ Safari iOS Yes Chrome Android 40+ WebView Android 40+ Samsung Internet 4.0+ Opera Android online onrejectionhandled rejectionhandled onunhandledrejection unhandledrejection 10.2.1.2 Dedicated workers and the DedicatedWorkerGlobalScope interface DedicatedWorkerGlobalScope Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 5.1+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11+ Global =( Worker DedicatedWorker ), Exposed DedicatedWorker interface DedicatedWorkerGlobalScope WorkerGlobalScope Replaceable readonly attribute DOMString name undefined postMessage any message sequence object transfer ); undefined postMessage any message optional PostMessageOptions options = {}); undefined close (); attribute EventHandler onmessage attribute EventHandler onmessageerror }; DedicatedWorkerGlobalScope objects act as if they had an implicit MessagePort associated with them. This port is part of a channel that is set up when the worker is created, but it is not exposed. This object must never be garbage collected before the DedicatedWorkerGlobalScope object. All messages received by that port must immediately be retargeted at the DedicatedWorkerGlobalScope object. dedicatedWorkerGlobal name DedicatedWorkerGlobalScope/name Support in all current engines. Firefox 55+ Safari 12.1+ Chrome Yes Opera Edge Yes Edge (Legacy) 18 Internet Explorer No Firefox Android 55+ Safari iOS 12.2+ Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Returns dedicatedWorkerGlobal 's name , i.e. the value given to the Worker constructor. Primarily useful for debugging. dedicatedWorkerGlobal postMessage message [, transfer ]) DedicatedWorkerGlobalScope/postMessage Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 5.1+ Chrome Android Yes WebView Android 37+ Samsung Internet Yes Opera Android 11+ dedicatedWorkerGlobal postMessage message [, { transfer } ]) Clones message and transmits it to the Worker object associated with dedicatedWorkerGlobal transfer can be passed as a list of objects that are to be transferred rather than cloned. dedicatedWorkerGlobal close () DedicatedWorkerGlobalScope/close Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 11.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 5.1+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11.5+ Aborts dedicatedWorkerGlobal The name attribute must return the DedicatedWorkerGlobalScope object's name . Its value represents the name given to the worker using the Worker constructor, used primarily for debugging purposes. The postMessage( message transfer and postMessage( message options methods on DedicatedWorkerGlobalScope objects act as if, when invoked, it immediately invoked the respective postMessage( message transfer and postMessage( message options on the port, with the same arguments, and returned the same return value. To close a worker , given a workerGlobal , run these steps: Discard any tasks that have been added to workerGlobal 's relevant agent 's event loop 's task queues Set workerGlobal 's closing flag to true. (This prevents any further tasks from being queued.) The close() method, when invoked, must close a worker with this DedicatedWorkerGlobalScope object. The following are the event handlers (and their corresponding event handler event types ) that must be supported, as event handler IDL attributes , by objects implementing the DedicatedWorkerGlobalScope interface: Event handler Event handler event type onmessage DedicatedWorkerGlobalScope/onmessage Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 5.1+ Chrome Android Yes WebView Android 37+ Samsung Internet Yes Opera Android 11+ message onmessageerror DedicatedWorkerGlobalScope/onmessageerror Firefox 57+ Safari Chrome 60+ Opera 47+ Edge 79+ Edge (Legacy) 18 Internet Explorer Firefox Android 57+ Safari iOS Chrome Android 60+ WebView Android 60+ Samsung Internet 8.0+ Opera Android 44+ messageerror 10.2.1.3 Shared workers and the SharedWorkerGlobalScope interface SharedWorkerGlobalScope Support in all current engines. Firefox 29+ Safari 5+ Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 4+ Safari iOS 7+ Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android 11+ Global =( Worker SharedWorker ), Exposed SharedWorker interface SharedWorkerGlobalScope WorkerGlobalScope Replaceable readonly attribute DOMString name undefined close (); attribute EventHandler onconnect }; SharedWorkerGlobalScope object has an associated constructor origin constructor url , and credentials . They are initialized when the SharedWorkerGlobalScope object is created, in the run a worker algorithm. Shared workers receive message ports through connect events on their SharedWorkerGlobalScope object for each connection. sharedWorkerGlobal name SharedWorkerGlobalScope/name Firefox 55+ Safari No Chrome Yes Opera 10.6+ Edge Yes Edge (Legacy) No Internet Explorer No Firefox Android 55+ Safari iOS No Chrome Android 40+ WebView Android Yes Samsung Internet 4.0+ Opera Android Yes Returns sharedWorkerGlobal 's name , i.e. the value given to the SharedWorker constructor. Multiple SharedWorker objects can correspond to the same shared worker (and SharedWorkerGlobalScope ), by reusing the same name. sharedWorkerGlobal close () SharedWorkerGlobalScope/close Support in all current engines. Firefox 29+ Safari 5+ Chrome 4+ Opera 11.5+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 29+ Safari iOS 7+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11+ Aborts sharedWorkerGlobal The name attribute must return the SharedWorkerGlobalScope object's name . Its value represents the name that can be used to obtain a reference to the worker using the SharedWorker constructor. The close() method, when invoked, must close a worker with this SharedWorkerGlobalScope object. The following are the event handlers (and their corresponding event handler event types ) that must be supported, as event handler IDL attributes , by objects implementing the SharedWorkerGlobalScope interface: Event handler Event handler event type onconnect SharedWorkerGlobalScope/onconnect Firefox 29+ Safari No Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 29+ Safari iOS Chrome Android 18+ WebView Android Yes Samsung Internet 1.0+ Opera Android Yes connect 10.2.2 The event loop worker event loop 's task queues only have events, callbacks, and networking activity as tasks . These worker event loops are created by the run a worker algorithm. Each WorkerGlobalScope object has a closing flag, which must be initially false, but which can get set to true by the algorithms in the processing model section below. Once the WorkerGlobalScope 's closing flag is set to true, the event loop 's task queues must discard any further tasks that would be added to them (tasks already on the queue are unaffected except where otherwise specified). Effectively, once the closing flag is true, timers stop firing, notifications for all pending background operations are dropped, etc. 10.2.3 The worker's lifetime Workers communicate with other workers and with browsing contexts through message channels and their MessagePort objects. Each WorkerGlobalScope object worker global scope has a list of the worker's ports , which consists of all the MessagePort objects that are entangled with another port and that have one (but only one) port owned by worker global scope . This list includes the implicit MessagePort in the case of dedicated workers Given an environment settings object when creating or obtaining a worker, the relevant owner to add depends on the type of global object specified by . If specifies a global object that is a WorkerGlobalScope object (i.e., if we are creating a nested dedicated worker), then the relevant owner is that global object. Otherwise, specifies a global object that is a Window object, and the relevant owner is the responsible document specified by A worker is said to be a permissible worker if its WorkerGlobalScope 's owner set is not empty or: its owner set has been empty for no more than a short implementation-defined timeout value, its WorkerGlobalScope object is a SharedWorkerGlobalScope object (i.e., the worker is a shared worker), and the user agent has a browsing context whose Document object is not completely loaded The second part of this definition allows a shared worker to survive for a short time while a page is loading, in case that page is going to contact the shared worker again. This can be used by user agents as a way to avoid the cost of restarting a shared worker used by a site when the user is navigating from page to page within that site. A worker is said to be an active needed worker if any its owners are either Document objects that are fully active or active needed workers A worker is said to be a protected worker if it is an active needed worker and either it has outstanding timers, database transactions, or network connections, or its list of the worker's ports is not empty, or its WorkerGlobalScope is actually a SharedWorkerGlobalScope object (i.e., the worker is a shared worker). A worker is said to be a suspendable worker if it is not an active needed worker but it is a permissible worker 10.2.4 Processing model When a user agent is to run a worker for a script with Worker or SharedWorker object worker URL url environment settings object outside settings MessagePort outside port , and a WorkerOptions dictionary options , it must run the following steps. Let is shared be true if worker is a SharedWorker object, and false otherwise. Let owner be the relevant owner to add given outside settings Let parent worker global scope be null. If owner is a WorkerGlobalScope object (i.e., we are creating a nested dedicated worker), then set parent worker global scope to owner Let agent be the result of obtaining a dedicated/shared worker agent given outside settings and is shared . Run the rest of these steps in that agent. For the purposes of timing APIs, this is the official moment of creation of the worker. Let realm execution context be the result of creating a new JavaScript realm given agent and the following customizations: For the global object, if is shared is true, create a new SharedWorkerGlobalScope object. Otherwise, create a new DedicatedWorkerGlobalScope object. Let worker global scope be the global object of realm execution context 's Realm component. This is the DedicatedWorkerGlobalScope or SharedWorkerGlobalScope object created in the previous step. Set up a worker environment settings object with realm execution context and outside settings , and let inside settings be the result. Set worker global scope 's name to the value of options 's name member. Append owner to worker global scope 's owner set If is shared is true, then: Set worker global scope 's constructor origin to outside settings 's origin Set worker global scope 's constructor url to url Set worker global scope 's type to the value of options 's type member. Set worker global scope 's credentials to the value of options 's credentials member. Let destination be " sharedworker " if is shared is true, and " worker " otherwise. Obtain script by switching on the value of options 's type member: classic Fetch a classic worker script given url outside settings destination , and inside settings module Fetch a module worker script graph given url outside settings destination , the value of the credentials member of options , and inside settings In both cases, to perform the fetch given request , perform the following steps if the is top-level flag is set: Set request 's reserved client to inside settings Fetch request , and asynchronously wait to run the remaining steps as part of fetch's process response for the response response Set worker global scope 's url to response 's url Initialize worker global scope's policy container given worker global scope , and response If the Run CSP initialization for a global object algorithm returns " Blocked " when executed upon worker global scope , set response to a network error [CSP] Set worker global scope 's referrer policy to the result of parsing the ` Referrer-Policy header of response If response 's url 's scheme is a local scheme , then set worker global scope 's embedder policy to owner 's embedder policy Otherwise, set worker global scope 's embedder policy to the result of obtaining an embedder policy from response and inside settings If worker global scope 's embedder policy is " require-corp " and is shared is true, then set agent 's agent cluster 's cross-origin isolation mode to " logical " or " concrete ". The one chosen is implementation-defined This really ought to be set when the agent cluster is created, which requires a redesign of this section. If the result of checking a global object's embedder policy with worker global scope outside settings , and response is false, then set response to a network error Set worker global scope 's cross-origin isolated capability to true if agent 's agent cluster 's cross-origin isolation mode is " concrete ". If is shared is false and owner 's cross-origin isolated capability is false, then set worker global scope 's cross-origin isolated capability to false. If is shared is false and response 's url 's scheme is " data ", then set worker global scope 's cross-origin isolated capability to false. This is a conservative default for now, while we figure out how workers in general, and data: URL workers in particular (which are cross-origin from their owner), will be treated in the context of permissions policies. See w3c/webappsec-permissions-policy issue #207 for more details. Asynchronously complete the perform the fetch steps with response If the algorithm asynchronously completes with null or with a script whose error to rethrow is non-null, then: Queue a global task on the DOM manipulation task source given worker 's relevant global object to fire an event named error at worker Run the environment discarding steps for inside settings Return. Otherwise, continue the rest of these steps after the algorithm's asynchronous completion, with script being the asynchronous completion value. Associate worker with worker global scope Let inside port be a new MessagePort object in inside settings 's Realm Associate inside port with worker global scope Entangle outside port and inside port Create a new WorkerLocation object and associate it with worker global scope Closing orphan workers : Start monitoring the worker such that no sooner than it stops being a protected worker , and no later than it stops being a permissible worker worker global scope 's closing flag is set to true. Suspending workers : Start monitoring the worker, such that whenever worker global scope 's closing flag is false and the worker is a suspendable worker , the user agent suspends execution of script in that worker until such time as either the closing flag switches to true or the worker stops being a suspendable worker Set inside settings 's execution ready flag If script is a classic script , then run the classic script script . Otherwise, it is a module script run the module script script In addition to the usual possibilities of returning a value or failing due to an exception, this could be prematurely aborted by the terminate a worker algorithm defined below. Enable outside port 's port message queue If is shared is false, enable the port message queue of the worker's implicit port. If is shared is true, then queue a global task on DOM manipulation task source given worker global scope to fire an event named connect at worker global scope , using MessageEvent , with the data attribute initialized to the empty string, the ports attribute initialized to a new frozen array containing inside port , and the source attribute initialized to inside port Enable the client message queue of the ServiceWorkerContainer object whose associated service worker client is worker global scope 's relevant settings object Event loop : Run the responsible event loop specified by inside settings until it is destroyed. The handling of events or the execution of callbacks by tasks run by the event loop might get prematurely aborted by the terminate a worker algorithm defined below. The worker processing model remains on this step until the event loop is destroyed, which happens after the closing flag is set to true, as described in the event loop processing model. Empty the worker global scope 's list of active timers Disentangle all the ports in the list of the worker's ports Empty worker global scope 's owner set When a user agent is to terminate a worker it must run the following steps in parallel with the worker's main loop (the " run a worker " processing model defined above): Set the worker's WorkerGlobalScope object's closing flag to true. If there are any tasks queued in the WorkerGlobalScope object's relevant agent 's event loop 's task queues , discard them without processing them. Abort the script currently running in the worker. If the worker's WorkerGlobalScope object is actually a DedicatedWorkerGlobalScope object (i.e. the worker is a dedicated worker), then empty the port message queue of the port that the worker's implicit port is entangled with. User agents may invoke the terminate a worker algorithm when a worker stops being an active needed worker and the worker continues executing even after its closing flag was set to true. 10.2.5 Runtime script errors Whenever an uncaught runtime script error occurs in one of the worker's scripts, if the error did not occur while handling a previous script error, the user agent must report the error for that script , with the position (line number and column number) where the error occurred, using the WorkerGlobalScope object as the target. For shared workers, if the error is still not handled afterwards, the error may be reported to a developer console. For dedicated workers, if the error is still not handled afterwards, the user agent must queue a task to run these steps: Let notHandled be the result of firing an event named error at the Worker object associated with the worker, using ErrorEvent , with the cancelable attribute initialized to true, the message filename lineno , and colno attributes initialized appropriately, and the error attribute initialized to null. If notHandled is true, then the user agent must act as if the uncaught runtime script error had occurred in the global scope that the Worker object is in, thus repeating the entire runtime script error reporting process one level up. If the implicit port connecting the worker to its Worker object has been disentangled (i.e. if the parent worker has been terminated), then the user agent must act as if the Worker object had no error event handler and as if that worker's onerror attribute was null, but must otherwise act as described above. Thus, error reports propagate up to the chain of dedicated workers up to the original Document , even if some of the workers along this chain have been terminated and garbage collected. The task source for the task mentioned above is the DOM manipulation task source 10.2.6 Creating workers 10.2.6.1 The AbstractWorker mixin AbstractWorker Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 5.1+ Chrome Android 18+ WebView Android 4.4+ Samsung Internet 1.0+ Opera Android 11+ interface mixin AbstractWorker attribute EventHandler onerror }; The following are the event handlers (and their corresponding event handler event types ) that must be supported, as event handler IDL attributes , by objects implementing the AbstractWorker interface: Event handler Event handler event type onerror AbstractWorker/onerror Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 5.1+ Chrome Android 18+ WebView Android 4.4+ Samsung Internet 1.0+ Opera Android 11+ error 10.2.6.2 Script settings for workers To set up a worker environment settings object , given a JavaScript execution context execution context and environment settings object outside settings Let inherited origin be outside settings 's origin Let realm be the value of execution context 's Realm component. Let worker global scope be realm 's global object Let settings object be a new environment settings object whose algorithms are defined as follows: The realm execution context Return execution context The module map Return worker global scope 's module map The responsible document Not applicable (the responsible event loop is not a window event loop ). The API URL character encoding Return UTF-8 The API base URL Return worker global scope 's url The origin Return a unique opaque origin if worker global scope 's url 's scheme is " data ", and inherited origin otherwise. The policy container Return worker global scope 's policy container The referrer policy Return worker global scope 's referrer policy The embedder policy Return worker global scope 's embedder policy The cross-origin isolated capability Return worker global scope 's cross-origin isolated capability Set settings object 's id to a new unique opaque string, creation URL to worker global scope 's url top-level creation URL to null, target browsing context to null, and active service worker to null. If worker global scope is a DedicatedWorkerGlobalScope object, then set settings object 's top-level origin to outside settings 's top-level origin Otherwise, set settings object 's top-level origin to an implementation-defined value. See Client-Side Storage Partitioning for the latest on properly defining this. Set realm 's [[HostDefined]] field to settings object Return settings object 10.2.6.3 Dedicated workers and the Worker interface Worker Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 5.1+ Chrome Android 18+ WebView Android 4+ Samsung Internet 1.0+ Opera Android 11+ Exposed =( Window DedicatedWorker SharedWorker )] interface Worker EventTarget constructor USVString scriptURL optional WorkerOptions options = {}); undefined terminate (); undefined postMessage any message sequence object transfer ); undefined postMessage any message optional PostMessageOptions options = {}); attribute EventHandler onmessage attribute EventHandler onmessageerror }; dictionary WorkerOptions WorkerType type = "classic"; RequestCredentials credentials = "same-origin"; // credentials is only used if type is "module" DOMString name = ""; }; enum WorkerType "classic" "module" }; Worker includes AbstractWorker worker = new Worker scriptURL [, options ]) Worker/Worker Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 5.1+ Chrome Android 18+ WebView Android 4+ Samsung Internet 1.0+ Opera Android 11+ Returns a new Worker object. scriptURL will be fetched and executed in the background, creating a new global environment for which worker represents the communication channel. options can be used to define the name of that global environment via the name option, primarily for debugging purposes. It can also ensure this new global environment supports JavaScript modules (specify type: "module" ), and if that is specified, can also be used to specify how scriptURL is fetched through the credentials option. worker terminate () Worker/terminate Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 5.1+ Chrome Android 18+ WebView Android 4+ Samsung Internet 1.0+ Opera Android 11+ Aborts worker 's associated global environment. worker postMessage message [, transfer ] ) Worker/postMessage Support in all current engines. Firefox Yes Safari Yes Chrome Yes Opera 47+ Edge Yes Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android Yes Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android 44+ worker postMessage message [, { transfer } ] ) Clones message and transmits it to worker 's global environment. transfer can be passed as a list of objects that are to be transferred rather than cloned. The terminate() method, when invoked, must cause the terminate a worker algorithm to be run on the worker with which the object is associated. Worker objects act as if they had an implicit MessagePort associated with them. This port is part of a channel that is set up when the worker is created, but it is not exposed. This object must never be garbage collected before the Worker object. All messages received by that port must immediately be retargeted at the Worker object. The postMessage( message transfer and postMessage( message options methods on Worker objects act as if, when invoked, they immediately invoked the respective postMessage( message transfer and postMessage( message options on the port, with the same arguments, and returned the same return value. The postMessage() method's first argument can be structured data: worker postMessage ({ opcode 'activate' device 1938 parameters 23 102 ]}); The following are the event handlers (and their corresponding event handler event types ) that must be supported, as event handler IDL attributes , by objects implementing the Worker interface: Event handler Event handler event type onmessage Worker/onmessage Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS 5.1+ Chrome Android 18+ WebView Android 4+ Samsung Internet 1.0+ Opera Android 11+ message onmessageerror Worker/onmessageerror Firefox 57+ Safari Chrome 60+ Opera 47+ Edge 79+ Edge (Legacy) 18 Internet Explorer No Firefox Android 57+ Safari iOS Chrome Android 60+ WebView Android 60+ Samsung Internet 8.0+ Opera Android 44+ messageerror When the Worker( scriptURL options constructor is invoked, the user agent must run the following steps: The user agent may throw a SecurityError DOMException if the request violates a policy decision (e.g. if the user agent is configured to not allow the page to start dedicated workers). Let outside settings be the current settings object Parse the scriptURL argument relative to outside settings If this fails, throw a SyntaxError DOMException Let worker URL be the resulting URL record Any same-origin URL (including blob: URLs) can be used. data: URLs can also be used, but they create a worker with an opaque origin Let worker be a new Worker object. Let outside port be a new MessagePort in outside settings 's Realm Associate the outside port with worker Run this step in parallel Run a worker given worker worker URL outside settings outside port , and options Return worker 10.2.6.4 Shared workers and the SharedWorker interface SharedWorker Firefox 29+ Safari 5–6.1 Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 33+ Safari iOS 5.1–7 Chrome Android No WebView Android No Samsung Internet 4.0–5.0 Opera Android 11–14 Exposed Window interface SharedWorker EventTarget constructor USVString scriptURL optional DOMString or WorkerOptions options = {}); readonly attribute MessagePort port }; SharedWorker includes AbstractWorker sharedWorker = new SharedWorker scriptURL [, name ]) SharedWorker/SharedWorker Firefox 29+ Safari 5–6.1 Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 33+ Safari iOS 5.1–7 Chrome Android No WebView Android No Samsung Internet 4.0–5.0 Opera Android 11–14 Returns a new SharedWorker object. scriptURL will be fetched and executed in the background, creating a new global environment for which sharedWorker represents the communication channel. name can be used to define the name of that global environment. sharedWorker = new SharedWorker scriptURL [, options ]) Returns a new SharedWorker object. scriptURL will be fetched and executed in the background, creating a new global environment for which sharedWorker represents the communication channel. options can be used to define the name of that global environment via the name option. It can also ensure this new global environment supports JavaScript modules (specify type: "module" ), and if that is specified, can also be used to specify how scriptURL is fetched through the credentials option. Note that attempting to construct a shared worker with options whose type or credentials values mismatch an existing shared worker will cause the returned sharedWorker to fire an error event and not connect to the existing shared worker. sharedWorker port SharedWorker/port Firefox 29+ Safari 5–6.1 Chrome 4+ Opera 10.6+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 33+ Safari iOS 5.1–7 Chrome Android No WebView Android No Samsung Internet 4.0–5.0 Opera Android 11–14 Returns sharedWorker 's MessagePort object which can be used to communicate with the global environment. The port attribute must return the value it was assigned by the object's constructor. It represents the MessagePort for communicating with the shared worker. A user agent has an associated shared worker manager which is the result of starting a new parallel queue Each user agent has a single shared worker manager for simplicity. Implementations could use one per origin ; that would not be observably different and enables more concurrency. When the SharedWorker( scriptURL options constructor is invoked: Optionally, throw a SecurityError DOMException if the request violates a policy decision (e.g. if the user agent is configured to not allow the page to start shared workers). If options is a DOMString , set options to a new WorkerOptions dictionary whose name member is set to the value of options and whose other members are set to their default values. Let outside settings be the current settings object Parse scriptURL relative to outside settings If this fails, throw a SyntaxError DOMException Otherwise, let urlRecord be the resulting URL record Any same-origin URL (including blob: URLs) can be used. data: URLs can also be used, but they create a worker with an opaque origin Let worker be a new SharedWorker object. Let outside port be a new MessagePort in outside settings 's Realm Assign outside port to the port attribute of worker Let callerIsSecureContext be true if outside settings is a secure context ; otherwise, false. Enqueue the following steps to the shared worker manager Let worker global scope be null. If there exists a SharedWorkerGlobalScope object whose closing flag is false, constructor origin is same origin with outside settings 's origin constructor url equals urlRecord , and name equals the value of options 's name member, then set worker global scope to that SharedWorkerGlobalScope object. data: URLs create a worker with an opaque origin . Both the constructor origin and constructor url are compared so the same data: URL can be used within an origin to get to the same SharedWorkerGlobalScope object, but cannot be used to bypass the same origin restriction. If worker global scope is not null, but the user agent has been configured to disallow communication between the worker represented by the worker global scope and the scripts whose settings object is outside settings , then set worker global scope to null. For example, a user agent could have a development mode that isolates a particular top-level browsing context from all other pages, and scripts in that development mode could be blocked from connecting to shared workers running in the normal browser mode. If worker global scope is not null, then check if worker global scope 's type and credentials match the options values. If not, queue a task to fire an event named error and abort these steps. If worker global scope is not null, then run these subsubsteps: Let settings object be the relevant settings object for worker global scope Let workerIsSecureContext be true if settings object is a secure context ; otherwise, false. If workerIsSecureContext is not callerIsSecureContext , then queue a task to fire an event named error at worker and abort these steps. [SECURE-CONTEXTS] Associate worker with worker global scope Let inside port be a new MessagePort in settings object 's Realm Entangle outside port and inside port Queue a task , using the DOM manipulation task source , to fire an event named connect at worker global scope using MessageEvent , with the data attribute initialized to the empty string, the ports attribute initialized to a new frozen array containing only inside port , and the source attribute initialized to inside port Append the relevant owner to add given outside settings to worker global scope 's owner set Otherwise, in parallel run a worker given worker urlRecord outside settings outside port , and options Return worker 10.2.7 Concurrent hardware capabilities NavigatorConcurrentHardware Firefox 48+ Safari 10.1–11 Chrome 37+ Opera 24+ Edge 79+ Edge (Legacy) 15+ Internet Explorer No Firefox Android 48+ Safari iOS 10.3–11 Chrome Android 37+ WebView Android 37+ Samsung Internet 3.0+ Opera Android 24+ interface mixin NavigatorConcurrentHardware readonly attribute unsigned long long hardwareConcurrency }; self navigator hardwareConcurrency NavigatorConcurrentHardware/hardwareConcurrency Firefox 48+ Safari 10.1–11 Chrome 37+ Opera 24+ Edge 79+ Edge (Legacy) 15+ Internet Explorer No Firefox Android 48+ Safari iOS 10.3–11 Chrome Android 37+ WebView Android 37+ Samsung Internet 3.0+ Opera Android 24+ Returns the number of logical processors potentially available to the user agent. The navigator.hardwareConcurrency attribute's getter must return a number between 1 and the number of logical processors potentially available to the user agent. If this cannot be determined, the getter must return 1. User agents should err toward exposing the number of logical processors available, using lower values only in cases where there are user-agent specific limits in place (such as a limitation on the number of workers that can be created) or when the user agent desires to limit fingerprinting possibilities. 10.3 APIs available to workers 10.3.1 Importing scripts and libraries When a script invokes the importScripts( urls method on WorkerGlobalScope object, the user agent must import scripts into worker global scope given this WorkerGlobalScope object and urls To import scripts into worker global scope , given a WorkerGlobalScope object worker global scope and a sequence urls , run these steps. The algorithm may optionally be customized by supplying custom perform the fetch hooks, which if provided will be used when invoking fetch a classic worker-imported script If worker global scope 's type is " module ", throw a TypeError exception. Let settings object be the current settings object If urls is empty, return. Parse each value in urls relative to settings object . If any fail, throw a SyntaxError DOMException For each url in the resulting URL records , run these substeps: Fetch a classic worker-imported script given url and settings object , passing along any custom perform the fetch steps provided. If this succeeds, let script be the result. Otherwise, rethrow the exception. Run the classic script script , with the rethrow errors argument set to true. script will run until it either returns, fails to parse, fails to catch an exception, or gets prematurely aborted by the terminate a worker algorithm defined above. If an exception was thrown or if the script was prematurely aborted , then abort all these steps, letting the exception or aborting continue to be processed by the calling script Service Workers is an example of a specification that runs this algorithm with its own options for the perform the fetch hook. [SW] 10.3.2 The WorkerNavigator interface WorkerNavigator Support in all current engines. Firefox 3.5+ Safari Yes Chrome 1+ Opera Yes Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android 4+ Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes The navigator attribute of the WorkerGlobalScope interface must return an instance of the WorkerNavigator interface, which represents the identity and state of the user agent (the client): Exposed Worker interface WorkerNavigator {}; WorkerNavigator includes NavigatorID WorkerNavigator includes NavigatorLanguage WorkerNavigator includes NavigatorOnLine WorkerNavigator includes NavigatorConcurrentHardware 10.3.3 The WorkerLocation interface WorkerLocation Support in all current engines. Firefox 3.5+ Safari Yes Chrome 1+ Opera Yes Edge 79+ Edge (Legacy) No Internet Explorer 10+ Firefox Android 4+ Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes WorkerLocation/toString Support in all current engines. Firefox 3.5+ Safari Yes Chrome 1+ Opera Yes Edge 79+ Edge (Legacy) No Internet Explorer Firefox Android 4+ Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes Exposed Worker interface WorkerLocation stringifier readonly attribute USVString href readonly attribute USVString origin readonly attribute USVString protocol readonly attribute USVString host readonly attribute USVString hostname readonly attribute USVString port readonly attribute USVString pathname readonly attribute USVString readonly attribute USVString hash }; WorkerLocation object has an associated WorkerGlobalScope object (a WorkerGlobalScope object). WorkerLocation/href Support in all current engines. Firefox 3.5+ Safari Yes Chrome 1+ Opera Yes Edge 79+ Edge (Legacy) No Internet Explorer Firefox Android 4+ Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes The href attribute's getter must return the associated WorkerGlobalScope object 's url serialized WorkerLocation/origin Support in all current engines. Firefox 3.5+ Safari Yes Chrome 1+ Opera Yes Edge 79+ Edge (Legacy) No Internet Explorer Firefox Android 4+ Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes The origin attribute's getter must return the serialization of the associated WorkerGlobalScope object 's url 's origin WorkerLocation/protocol Support in all current engines. Firefox 3.5+ Safari Yes Chrome 1+ Opera Yes Edge 79+ Edge (Legacy) No Internet Explorer Firefox Android 4+ Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes The protocol attribute's getter must return the associated WorkerGlobalScope object 's url 's scheme , followed by " ". WorkerLocation/host Support in all current engines. Firefox 3.5+ Safari Yes Chrome 1+ Opera Yes Edge 79+ Edge (Legacy) No Internet Explorer Firefox Android 4+ Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes The host attribute's getter must run these steps: Let url be the associated WorkerGlobalScope object 's url If url 's host is null, return the empty string. If url 's port is null, return url 's host serialized Return url 's host serialized , followed by " " and url 's port serialized WorkerLocation/hostname Support in all current engines. Firefox 3.5+ Safari Yes Chrome 1+ Opera Yes Edge 79+ Edge (Legacy) No Internet Explorer Firefox Android 4+ Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes The hostname attribute's getter must run these steps: Let host be the associated WorkerGlobalScope object 's url 's host If host is null, return the empty string. Return host serialized WorkerLocation/port Support in all current engines. Firefox 3.5+ Safari Yes Chrome 1+ Opera Yes Edge 79+ Edge (Legacy) No Internet Explorer Firefox Android 4+ Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes The port attribute's getter must run these steps: Let port be the associated WorkerGlobalScope object 's url 's port If port is null, return the empty string. Return port serialized WorkerLocation/pathname Support in all current engines. Firefox 3.5+ Safari Yes Chrome 1+ Opera Yes Edge 79+ Edge (Legacy) No Internet Explorer Firefox Android 4+ Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes The pathname attribute's getter must run these steps: Let url be the associated WorkerGlobalScope object 's url If url 's cannot-be-a-base-URL is true, then return url 's path [0]. Return " ", followed by the strings in url 's path (including empty strings), separated from each other by ". WorkerLocation/search Support in all current engines. Firefox 3.5+ Safari Yes Chrome 1+ Opera Yes Edge 79+ Edge (Legacy) No Internet Explorer Firefox Android 4+ Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes The attribute's getter must run these steps: Let query be the associated WorkerGlobalScope object 's url 's query If query is either null or the empty string, return the empty string. Return " ", followed by query WorkerLocation/hash Support in all current engines. Firefox 3.5+ Safari Yes Chrome 1+ Opera Yes Edge 79+ Edge (Legacy) No Internet Explorer Firefox Android 4+ Safari iOS Yes Chrome Android Yes WebView Android Yes Samsung Internet Yes Opera Android Yes The hash attribute's getter must run these steps: Let fragment be the associated WorkerGlobalScope object 's url 's fragment If fragment is either null or the empty string, return the empty string. Return " ", followed by fragment 11 Worklets 11.1 Introduction This section is non-normative. Worklets are a piece of specification infrastructure which can be used for running scripts independent of the main JavaScript execution environment, while not requiring any particular implementation model. The worklet infrastructure specified here cannot be used directly by web developers. Instead, other specifications build upon it to create directly-usable worklet types, specialized for running in particular parts of the browser implementation pipeline. 11.1.1 Motivations This section is non-normative. Allowing extension points to rendering, or other sensitive parts of the implementation pipeline such as audio output, is difficult. If extension points were done with full access to the APIs available on Window , engines would need to abandon previously-held assumptions for what could happen in the middle of those phases. For example, during the layout phase, rendering engines assume that no DOM will be modified. Additionally, defining extension points in the Window environment would restrict user agents to performing work in the same thread as the Window object. (Unless implementations added complex, high-overhead infrastructure to allow thread-safe APIs, as well as thread-joining guarantees.) Worklets are designed to allow extension points, while keeping guarantees that user agents currently rely on. This is done through new global environments, based on subclasses of WorkletGlobalScope Worklets are similar to web workers. However, they: Are thread-agnostic. That is, they are not designed to run on a dedicated separate thread, like each worker is. Implementations can run worklets wherever they choose (including on the main thread). Are able to have multiple duplicate instances of the global scope created, for the purpose of parallelism. Do not use an event-based API. Instead, classes are registered on the global scope, whose methods are invoked by the user agent. Have a reduced API surface on the global scope. Have a lifetime for their global object which is defined by other specifications, often in an implementation-defined manner. As worklets have relatively high overhead, they are best used sparingly. Due to this, a given WorkletGlobalScope is expected to be shared between multiple separate scripts. (This is similar to how a single Window is shared between multiple separate scripts.) Worklets are a general technology that serve different use cases. Some worklets, such as those defined in CSS Painting API , provide extension points intended for stateless, idempotent, and short-running computations, which have special considerations as described in the next couple of sections. Others, such as those defined in Web Audio API , are used for stateful, long-running operations. [CSSPAINT] [WEBAUDIO] 11.1.2 Code idempotence Some specifications which use worklets are intended to allow user agents to parallelize work over multiple threads, or to move work between threads as required. In these specifications, user agents might invoke methods on a web-developer-provided class in an implementation-defined order. As a result of this, to prevent interoperability issues, authors who register classes on such WorkletGlobalScope s should make their code idempotent. That is, a method or set of methods on the class should produce the same output given a particular input. This specification uses the following techniques in order to encourage authors to write code in an idempotent way: No reference to the global object is available (i.e., there is no counterpart to self on WorkletGlobalScope Although this was the intention when worklets were first specified, the introduction of globalThis has made it no longer true. See issue #6059 for more discussion. Code is loaded as a module script , which results in the code being executed in strict mode and with no shared this referencing the global proxy. Together, these restrictions help prevent two different scripts from sharing state using properties of the global object Additionally, specifications which use worklets and intend to allow implementation-defined behavior must obey the following: They must require user agents to always have at least two WorkletGlobalScope instances per Worklet , and randomly assign a method or set of methods on a class to a particular WorkletGlobalScope instance. These specifications may provide an opt-out under memory constraints. These specifications must allow user agents to create and destroy instances of their WorkletGlobalScope subclasses at any time. 11.1.3 Speculative evaluation Some specifications which use worklets can invoke methods on a web-developer-provided class based on the state of the user agent. To increase concurrency between threads, a user agent may invoke a method speculatively, based on potential future states. In these specifications, user agents might invoke such methods at any time, and with any arguments, not just ones corresponding to the current state of the user agent. The results of such speculative evaluations are not displayed immediately, but can be cached for use if the user agent state matches the speculated state. This can increase the concurrency between the user agent and worklet threads. As a result of this, to prevent interoperability risks between user agents, authors who register classes on such WorkletGlobalScope s should make their code stateless. That is, the only effect of invoking a method should be its result, and not any side effects such as updating mutable state. The same techniques which encourage code idempotence also encourage authors to write stateless code. 11.2 Examples This section is non-normative. For these examples, we'll use a fake worklet. The Window object provides two Worklet instances, which each run code in their own collection of FakeWorkletGlobalScope s: partial interface Window SameObject SecureContext readonly attribute Worklet fakeWorklet1 SameObject SecureContext readonly attribute Worklet fakeWorklet2 }; window . fakeWorklet1 Returns one of the fake worklets. window . fakeWorklet2 Returns another of the fake worklets. Each Window has two Worklet instances, fake worklet 1 and fake worklet 2 . Both of these have their worklet global scope type set to FakeWorkletGlobalScope , and their worklet destination type set to " fakeworklet ". User agents should create at least two FakeWorkletGlobalScope instances per worklet. fakeworklet " is not actually a valid destination per Fetch . But this illustrates how real worklets would generally have their own worklet-type-specific destination. [FETCH] The fakeWorklet1 getter steps are to return this 's fake worklet 1 The fakeWorklet2 getter steps are to return this 's fake worklet 2 Global =( Worklet FakeWorklet ), Exposed FakeWorklet SecureContext interface FakeWorkletGlobalScope WorkletGlobalScope undefined registerFake DOMString type Function classConstructor ); }; Inside a FakeWorkletGlobalScope , the following global method is available: registerFake( type classConstructor Registers the JavaScript class given by classConstructor for use when the user agent later wants to do some operation specified by type Each FakeWorkletGlobalScope has a registered class constructors map which is an ordered map , initially empty. The registerFake( type classConstructor method steps are to set this 's registered class constructors map type ] to classConstructor 11.2.1 Loading scripts This section is non-normative. To load scripts into fake worklet 1 , a web developer would write: window fakeWorklet1 addModule 'script1.mjs' ); window fakeWorklet1 addModule 'script2.mjs' ); Note that which script finishes fetching and runs first is dependent on network timing: it could be either script1.mjs or script2.mjs . This generally won't matter for well-written scripts intended to be loaded in worklets, if they follow the suggestions about preparing for speculative evaluation If a web developer wants to perform a task only after the scripts have successfully run and loaded into some worklets, they could write: Promise all ([ window fakeWorklet1 addModule 'script1.mjs' ), window fakeWorklet2 addModule 'script2.mjs' ]). then (() => // Do something which relies on those scripts being loaded. }); Another important point about script-loading is that loaded scripts can be run in multiple WorkletGlobalScope s per Worklet , as discussed in the section on code idempotence . In particular, the specification above for fake worklet 1 and fake worklet 2 require this. So, consider a scenario such as the following: // script.mjs console log "Hello from a FakeWorkletGlobalScope!" ); // app.mjs window fakeWorklet1 addModule "script.mjs" ); This could result in output such as the following from a user agent's console: [fakeWorklet1#1] Hello from a FakeWorkletGlobalScope! [fakeWorklet1#4] Hello from a FakeWorkletGlobalScope! [fakeWorklet1#2] Hello from a FakeWorkletGlobalScope! [fakeWorklet1#3] Hello from a FakeWorkletGlobalScope! If the user agent at some point decided to kill and restart the third instance of FakeWorkletGlobalScope , the console would again print [fakeWorklet1#3] Hello from a FakeWorkletGlobalScope! when this occurs. 11.2.2 Registering a class and invoking its methods This section is non-normative. Let's say that one of the intended usages of our fake worklet by web developers is to allow them to customize the highly-complex process of boolean negation. They might register their customization as follows: // script.mjs registerFake 'negation-processor' class process arg return arg }); // app.mjs window fakeWorklet1 addModule "script.mjs" ); To make use of such registered classes, the specification for fake worklets could define a find the opposite of true algorithm, given a Worklet worklet , which invokes the process method on any class registered to one of worklet 's global scopes as having type " negation-processor ", with true as the argument, and then uses the result in some way.: Optionally, create a worklet global scope for worklet Let workletGlobalScope be one of worklet 's global scopes , chosen in an implementation-defined manner. Let classConstructor be workletGlobalScope 's registered class constructors map [" negation-processor "]. Let classInstance be the result of constructing classConstructor , with no arguments. Let function be Get classInstance process "). Rethrow any exceptions. Let callback be the result of converting function to a Web IDL Function instance. Return the result of invoking callback with the arguments « true » and with classInstance as the callback this value Another, perhaps better, specification architecture would be to extract the " process " property and convert it into a Function at registration time, as part of the registerFake() method steps. 11.3 Infrastructure 11.3.1 The global scope Subclasses of WorkletGlobalScope are used to create global objects wherein code loaded into a particular Worklet can execute. Exposed Worklet SecureContext interface WorkletGlobalScope {}; Other specifications are intended to subclass WorkletGlobalScope adding APIs to register a class, as well as other APIs specific for their worklet type. Each WorkletGlobalScope has an associated module map . It is a module map initially empty. 11.3.1.1 Agents and event loops This section is non-normative. Each WorkletGlobalScope is contained in its own worklet agent , which has its corresponding event loop . However, in practice, implementation of these agents and event loops is expected to be different from most others. worklet agent exists for each WorkletGlobalScope since, in theory, an implementation could use a separate thread for each WorkletGlobalScope instance, and allowing this level of parallelism is best done using agents. However, because their [[CanBlock]] value is false, there is no requirement that agents and threads are one-to-one. This allows implementations the freedom to execute scripts loaded into a worklet on any thread, including one running code from other agents with [[CanBlock]] of false, such as the thread of a similar-origin window agent ("the main thread"). Contrast this with dedicated worker agents , whose true value for [[CanBlock]] effectively requires them to get a dedicated operating system thread. Worklet event loops are also somewhat special. They are only used for tasks associated with addModule() , tasks wherein the user agent invokes author-defined methods, and microtasks . Thus, even though the event loop processing model specifies that all event loops run continuously, implementations can achieve observably-equivalent results using a simpler strategy, which just invokes author-provided methods and then relies on that process to perform a microtask checkpoint 11.3.1.2 Creation and termination To create a worklet global scope for a Worklet worklet Let outsideSettings be worklet 's relevant settings object Let agent be the result of obtaining a worklet agent given outsideSettings . Run the rest of these steps in that agent. Let realmExecutionContext be the result of creating a new JavaScript realm given agent and the following customizations: For the global object, create a new object of the type given by worklet 's worklet global scope type Let workletGlobalScope be the global object of realmExecutionContext 's Realm component. Let insideSettings be the result of setting up a worklet environment settings object given realmExecutionContext and outsideSettings For each moduleURL of worklet 's added modules list Fetch a worklet script graph given moduleURL insideSettings worklet 's worklet destination type what credentials mode? insideSettings , and worklet 's module responses map . Wait until the algorithm asynchronously completes with script This will not actually perform a network request, as it will just reuse responses from worklet 's module responses map . The main purpose of this step is to create a new workletGlobalScope -specific module script from the response Assert: script is not null, since the fetch succeeded and the source text was successfully parsed when worklet 's module responses map was initially populated with moduleURL Run a module script given script Append workletGlobalScope to outsideSettings 's global object 's associated Document 's worklet global scopes Append workletGlobalScope to worklet 's global scopes Run the responsible event loop specified by insideSettings To terminate a worklet global scope given a WorkletGlobalScope workletGlobalScope Let eventLoop be workletGlobalScope 's relevant agent 's event loop If there are any tasks queued in eventLoop 's task queues , discard them without processing them. Wait for eventLoop to complete the currently running task If the previous step doesn't complete within an implementation-defined period of time, then abort the script currently running in the worklet. Destroy eventLoop Remove workletGlobalScope from the global scopes of the Worklet whose global scopes contains workletGlobalScope Remove workletGlobalScope from the worklet global scopes of the Document whose worklet global scopes contains workletGlobalScope 11.3.1.3 Script settings for worklets To set up a worklet environment settings object , given a JavaScript execution context executionContext and an environment settings object outsideSettings Let origin be a unique opaque origin Let inheritedAPIBaseURL be outsideSettings 's API base URL Let inheritedPolicyContainer be a clone of outsideSettings 's policy container Let inheritedReferrerPolicy be outsideSettings 's referrer policy Let inheritedEmbedderPolicy be outsideSettings 's embedder policy Let realm be the value of executionContext 's Realm component. Let workletGlobalScope be realm 's global object Let settingsObject be a new environment settings object whose algorithms are defined as follows: The realm execution context Return executionContext The module map Return workletGlobalScope 's module map The responsible document Not applicable (the responsible event loop is not a window event loop ). The API URL character encoding Return UTF-8 The API base URL Return inheritedAPIBaseURL Unlike workers or other globals derived from a single resource, worklets have no primary resource; instead, multiple scripts, each with their own URL, are loaded into the global scope via worklet.addModule() . So this API base URL is rather unlike that of other globals. However, so far this doesn't matter, as no APIs available to worklet code make use of the API base URL The origin Return origin The policy container Return inheritedPolicyContainer The referrer policy Return inheritedReferrerPolicy The embedder policy Return inheritedEmbedderPolicy The cross-origin isolated capability Return TODO Set settingsObject 's id to a new unique opaque string, creation URL to inheritedAPIBaseURL top-level creation URL to null, top-level origin to outsideSettings 's top-level origin target browsing context to null, and active service worker to null. Set realm 's [[HostDefined]] field to settingsObject Return settingsObject 11.3.2 The Worklet class Worklet Support in all current engines. Firefox 76+ Safari 14.1+ Chrome 65+ Opera 52+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 79+ Safari iOS 14.5+ Chrome Android 65+ WebView Android 65+ Samsung Internet 9.0+ Opera Android 47+ The Worklet class provides the capability to add module scripts into its associated WorkletGlobalScope s. The user agent can then create classes registered on the WorkletGlobalScope s and invoke their methods. Exposed Window SecureContext interface Worklet NewObject Promise undefined addModule USVString moduleURL optional WorkletOptions options = {}); }; dictionary WorkletOptions RequestCredentials credentials = "same-origin"; }; Specifications that create Worklet instances must specify the following for a given instance: its worklet global scope type , which must be a Web IDL type that inherits from WorkletGlobalScope ; and its worklet destination type , which must be a destination , and is used when fetching scripts. await worklet addModule moduleURL [, { credentials }]) Worklet/addModule Firefox 76+ Safari No Chrome 65+ Opera 52+ Edge 79+ Edge (Legacy) No Internet Explorer No Firefox Android 79+ Safari iOS No Chrome Android 65+ WebView Android 65+ Samsung Internet 9.0+ Opera Android 47+ Loads and executes the module script given by moduleURL into all of worklet 's global scopes . It can also create additional global scopes as part of this process, depending on the worklet type. The returned promise will fulfill once the script has been successfully loaded and run in all global scopes. The credentials option can be set to a credentials mode to modify the script-fetching process. It defaults to " same-origin ". Any failures in fetching the script or its dependencies will cause the returned promise to be rejected with an AbortError DOMException . Any errors in parsing the script or its dependencies will cause the returned promise to be rejected with the exception generated during parsing. Worklet has a list of global scopes , which contains instances of the Worklet 's worklet global scope type . It is initially empty. Worklet has an added modules list , which is a list of URLs , initially empty. Access to this list should be thread-safe. Worklet has a module responses map , which is an ordered map from URLs to responses , initially empty. Access to this map should be thread-safe. The added modules list and module responses map exist to ensure that WorkletGlobalScope s created at different times get equivalent module scripts run in them, based on the same source text. This allows the creation of additional WorkletGlobalScope s to be transparent to the author. In practice, user agents are not expected to implement these data structures, and the algorithms that consult them, using thread-safe programming techniques. Instead, when addModule() is called, user agents can fetch the module graph on the main thread, and send the fetched source text (i.e., the important data contained in the module responses map ) to each thread which has a WorkletGlobalScope Then, when a user agent creates a new WorkletGlobalScope for a given Worklet , it can simply send the map of fetched source text and the list of entry points from the main thread to the thread containing the new WorkletGlobalScope The addModule( moduleURL options method steps are: Let outsideSettings be the relevant settings object of this Parse moduleURL relative to outsideSettings If this fails, then return a promise rejected with a SyntaxError DOMException Let moduleURLRecord be the resulting URL record Let promise be a new promise. Run the following steps in parallel If this 's global scopes is empty , then: Create a worklet global scope given this Optionally, create additional global scope instances given this , depending on the specific worklet in question and its specification. Wait for all steps of the creation process(es) — including those taking place within the worklet agents — to complete, before moving on. Let pendingTasks be this 's global scopes 's size Let addedSuccessfully be false. For each workletGlobalScope of this 's global scopes queue a global task on the networking task source given workletGlobalScope to perform the following steps: Fetch a worklet script graph given moduleURLRecord outsideSettings this 's worklet destination type options [" credentials "], workletGlobalScope 's relevant settings object , and this 's module responses map . Wait until the algorithm asynchronously completes with script Only the first of these fetches will actually perform a network request; the ones for other WorkletGlobalScope s will reuse reuse responses from this 's module responses map If script is null, then: Queue a global task on the networking task source given this 's relevant global object to perform the following steps: If pendingTasks is not −1, then: Set pendingTasks to −1. Reject promise with an AbortError DOMException Abort these steps. If script 's error to rethrow is not null, then: Queue a global task on the networking task source given this 's relevant global object to perform the following steps: If pendingTasks is not −1, then: Set pendingTasks to −1. Reject promise with script 's error to rethrow Abort these steps. If addedSuccessfully is false, then: Append moduleURLRecord to this 's added modules list Set addedSuccessfully to true. Run a module script given script Queue a global task on the networking task source given this 's relevant global object to perform the following steps: If pendingTasks is not −1, then: Set pendingTasks to pendingTasks − 1. If pendingTasks is 0, then resolve promise Return promise 11.3.3 The worklet's lifetime The lifetime of a Worklet has no special considerations; it is tied to the object it belongs to, such as the Window Each Document has a worklet global scopes , which is a set of WorkletGlobalScope s, initially empty. The lifetime of a WorkletGlobalScope is, at a minimum, tied to the Document whose worklet global scopes contain it. In particular, discarding the Document will terminate the corresponding WorkletGlobalScope and allow it to be garbage-collected. Additionally, user agents may, at any time, terminate a given WorkletGlobalScope , unless the specification defining the corresponding worklet type says otherwise. For example, they might terminate them if the worklet agent 's event loop has no tasks queued, or if the user agent has no pending operations planning to make use of the worklet, or if the user agent detects abnormal operations such as infinite loops or callbacks exceeding imposed time limits. Finally, specifications for specific worklet types can give more specific details on when to create WorkletGlobalScope s for a given worklet type. For example, they might create them during specific processes that call upon worklet code, as in the example 12 Web storage Web_Storage_API Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 10.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 8+ Firefox Android 6+ Safari iOS 3.2+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11+ Web_Storage_API/Using_the_Web_Storage_API 12.1 Introduction This section is non-normative. This specification introduces two related mechanisms, similar to HTTP session cookies, for storing name-value pairs on the client side. [COOKIES] The first is designed for scenarios where the user is carrying out a single transaction, but could be carrying out multiple transactions in different windows at the same time. Cookies don't really handle this case well. For example, a user could be buying plane tickets in two different windows, using the same site. If the site used cookies to keep track of which ticket the user was buying, then as the user clicked from page to page in both windows, the ticket currently being purchased would "leak" from one window to the other, potentially causing the user to buy two tickets for the same flight without really noticing. To address this, this specification introduces the sessionStorage getter. Sites can add data to the session storage, and it will be accessible to any page from the same site opened in that window. For example, a page could have a checkbox that the user ticks to indicate that they want insurance: label input type "checkbox" onchange "sessionStorage.insurance = checked ? 'true' : ''" I want insurance on this trip. label A later page could then check, from script, whether the user had checked the checkbox or not: if sessionStorage insurance ... If the user had multiple windows opened on the site, each one would have its own individual copy of the session storage object. The second storage mechanism is designed for storage that spans multiple windows, and lasts beyond the current session. In particular, web applications might wish to store megabytes of user data, such as entire user-authored documents or a user's mailbox, on the client side for performance reasons. Again, cookies do not handle this case well, because they are transmitted with every request. The localStorage getter is used to access a page's local storage area. The site at example.com can display a count of how many times the user has loaded its page by putting the following at the bottom of its page: You have viewed this page span id "count" an untold number of span time(s). script if localStorage pageLoadCount localStorage pageLoadCount localStorage pageLoadCount parseInt localStorage pageLoadCount document getElementById 'count' ). textContent localStorage pageLoadCount script Each site has its own separate storage area. The localStorage getter provides access to shared state. This specification does not define the interaction with other browsing contexts in a multiprocess user agent, and authors are encouraged to assume that there is no locking mechanism. A site could, for instance, try to read the value of a key, increment its value, then write it back out, using the new value as a unique identifier for the session; if the site does this twice in two different browser windows at the same time, it might end up using the same "unique" identifier for both sessions, with potentially disastrous effects. 12.2 The API Storage Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 10.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 8+ Firefox Android 6+ Safari iOS 3.2+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11+ 12.2.1 The Storage interface Exposed Window interface Storage readonly attribute unsigned long length DOMString key unsigned long index ); getter DOMString getItem DOMString key ); setter undefined setItem DOMString key DOMString value ); deleter undefined removeItem DOMString key ); undefined clear (); }; storage length Storage/length Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 10.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 8+ Firefox Android 6+ Safari iOS 3.2+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11+ Returns the number of key/value pairs. storage key Storage/key Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 10.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 8+ Firefox Android 6+ Safari iOS 3.2+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11+ Returns the name of the th key, or null if is greater than or equal to the number of key/value pairs. value storage getItem key Storage/getItem Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 10.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 8+ Firefox Android 6+ Safari iOS 3.2+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11+ value storage key Returns the current value associated with the given key , or null if the given key does not exist. storage setItem key value Storage/setItem Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 10.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 8+ Firefox Android 6+ Safari iOS 3.2+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11+ storage key ] = value Sets the value of the pair identified by key to value , creating a new key/value pair if none existed for key previously. Throws a QuotaExceededError DOMException exception if the new value couldn't be set. (Setting could fail if, e.g., the user has disabled storage for the site, or if the quota has been exceeded.) Dispatches a storage event on Window objects holding an equivalent Storage object. storage removeItem key Storage/removeItem Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 10.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 8+ Firefox Android 6+ Safari iOS 3.2+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11+ delete storage key Removes the key/value pair with the given key , if a key/value pair with the given key exists. Dispatches a storage event on Window objects holding an equivalent Storage object. storage clear () Storage/clear Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 10.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 8+ Firefox Android 6+ Safari iOS 3.2+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11+ Removes all key/value pairs, if there are any. Dispatches a storage event on Window objects holding an equivalent Storage object. Storage object has an associated: map storage proxy map type local " or " session ". To reorder Storage object storage , reorder storage 's map 's entries in an implementation-defined manner. Unfortunate as it is, iteration order is not defined and can change upon most mutations. To broadcast Storage object storage , given a key oldValue , and newValue , run these steps: Let url be storage 's relevant global object 's associated Document 's URL Let remoteStorages be all Storage objects excluding storage whose: type is storage 's type relevant settings object 's origin is same origin with storage 's relevant settings object 's origin and, if type is " session ", whose relevant settings object 's browsing session is storage 's relevant settings object 's browsing session For each remoteStorage of remoteStorages queue a global task on the DOM manipulation task source given remoteStorage 's relevant global object to fire an event named storage at remoteStorage 's relevant global object , using StorageEvent , with key initialized to key oldValue initialized to oldValue newValue initialized to newValue url initialized to url , and storageArea initialized to remoteStorage The Document object associated with the resulting task is not necessarily fully active , but events fired on such objects are ignored by the event loop until the Document becomes fully active again. The length getter steps are to return this 's map 's size The key( method steps are: If is greater than or equal to this 's map 's size , then return null. Let keys be the result of running get the keys on this 's map Return keys ]. The supported property names on a Storage object storage are the result of running get the keys on storage 's map The getItem( key method steps are: If this 's map key ] does not exist , then return null. Return this 's map key ]. The setItem( key value method are: Let oldValue be null. Let reorder be true. If this 's map key exists Set oldValue to this 's map key ]. If oldValue is value , then return. Set reorder to false. If value cannot be stored, then throw a QuotaExceededError DOMException exception. Set this 's map key ] to value If reorder is true, then reorder this Broadcast this with key oldValue , and value The removeItem( key method steps are: If this 's map key ] does not exist , then return null. Set oldValue to this 's map key ]. Remove this 's map key ]. Reorder this Broadcast this with key oldValue , and null. The clear() method steps are: Clear this 's map Broadcast this with null, null, and null. 12.2.2 The sessionStorage getter interface mixin WindowSessionStorage readonly attribute Storage sessionStorage }; Window includes WindowSessionStorage window sessionStorage Window/sessionStorage Support in all current engines. Firefox 2+ Safari 4+ Chrome 5+ Opera 10.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 8+ Firefox Android 4+ Safari iOS 3.2+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11+ Returns the Storage object associated with that window 's origin's session storage area. Throws a SecurityError DOMException if the Document 's origin is an opaque origin or if the request violates a policy decision (e.g., if the user agent is configured to not allow the page to persist data). Document object has an associated session storage holder , which is null or a Storage object. It is initially null. The sessionStorage getter steps are: If this 's associated Document 's session storage holder is non-null, then return this 's associated Document 's session storage holder Let map be the result of running obtain a session storage bottle map with this 's relevant settings object and " sessionStorage ". If map is failure, then throw a SecurityError DOMException Let storage be a new Storage object whose map is map Set this 's associated Document 's session storage holder to storage Return storage While creating a new auxiliary browsing context , the session storage is copied over. 12.2.3 The localStorage getter interface mixin WindowLocalStorage readonly attribute Storage localStorage }; Window includes WindowLocalStorage window localStorage Window/localStorage Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 4+ Opera 10.5+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 8+ Firefox Android 4+ Safari iOS 3.2+ Chrome Android 18+ WebView Android 37+ Samsung Internet 1.0+ Opera Android 11+ Returns the Storage object associated with window 's origin's local storage area. Throws a SecurityError DOMException if the Document 's origin is an opaque origin or if the request violates a policy decision (e.g., if the user agent is configured to not allow the page to persist data). Document object has an associated local storage holder , which is null or a Storage object. It is initially null. The localStorage getter steps are: If this 's associated Document 's local storage holder is non-null, then return this 's associated Document 's local storage holder Let map be the result of running obtain a local storage bottle map with this 's relevant settings object and " localStorage ". If map is failure, then throw a SecurityError DOMException Let storage be a new Storage object whose map is map Set this 's associated Document 's local storage holder to storage Return storage 12.2.4 The StorageEvent interface StorageEvent Support in all current engines. Firefox Yes Safari Yes Chrome 1+ Opera Yes Edge 79+ Edge (Legacy) 12+ Internet Explorer Firefox Android Yes Safari iOS Yes Chrome Android Yes WebView Android 1+ Samsung Internet Yes Opera Android Yes Exposed Window interface StorageEvent Event constructor DOMString type optional StorageEventInit eventInitDict = {}); readonly attribute DOMString key readonly attribute DOMString oldValue readonly attribute DOMString newValue readonly attribute USVString url readonly attribute Storage storageArea undefined initStorageEvent DOMString type optional boolean bubbles false optional boolean cancelable false optional DOMString key null optional DOMString oldValue null optional DOMString newValue null optional USVString url = "", optional Storage storageArea null ); }; dictionary StorageEventInit EventInit DOMString key null DOMString oldValue null DOMString newValue null USVString url = ""; Storage storageArea null }; event key Returns the key of the storage item being changed. event oldValue Returns the old value of the key of the storage item whose value is being changed. event newValue Returns the new value of the key of the storage item whose value is being changed. event url Returns the URL of the document whose storage item changed. event storageArea Returns the Storage object that was affected. The key oldValue newValue url , and storageArea attributes must return the values they were initialized to. The initStorageEvent() method must initialize the event in a manner analogous to the similarly-named initEvent() method. [DOM] 12.3 12.3.1 User tracking A third-party advertiser (or any entity capable of getting content distributed to multiple sites) could use a unique identifier stored in its local storage area to track a user across multiple sessions, building a profile of the user's interests to allow for highly targeted advertising. In conjunction with a site that is aware of the user's real identity (for example an e-commerce site that requires authenticated credentials), this could allow oppressive groups to target individuals with greater accuracy than in a world with purely anonymous web usage. There are a number of techniques that can be used to mitigate the risk of user tracking: Blocking third-party storage User agents may restrict access to the localStorage objects to scripts originating at the domain of the active document of the top-level browsing context , for instance denying access to the API for pages from other domains running in iframe s. Expiring stored data User agents may, possibly in a manner configured by the user, automatically delete stored data after a period of time. For example, a user agent could be configured to treat third-party local storage areas as session-only storage, deleting the data once the user had closed all the browsing contexts that could access it. This can restrict the ability of a site to track a user, as the site would then only be able to track the user across multiple sessions when they authenticate with the site itself (e.g. by making a purchase or logging in to a service). However, this also reduces the usefulness of the API as a long-term storage mechanism. It can also put the user's data at risk, if the user does not fully understand the implications of data expiration. Treating persistent storage as cookies If users attempt to protect their privacy by clearing cookies without also clearing data stored in the local storage area, sites can defeat those attempts by using the two features as redundant backup for each other. User agents should present the interfaces for clearing these in a way that helps users to understand this possibility and enables them to delete data in all persistent storage features simultaneously. [COOKIES] Site-specific safelisting of access to local storage areas User agents may allow sites to access session storage areas in an unrestricted manner, but require the user to authorize access to local storage areas. Origin-tracking of stored data User agents may record the origins of sites that contained content from third-party origins that caused data to be stored. If this information is then used to present the view of data currently in persistent storage, it would allow the user to make informed decisions about which parts of the persistent storage to prune. Combined with a blocklist ("delete this data and prevent this domain from ever storing data again"), the user can restrict the use of persistent storage to sites that they trust. Shared blocklists User agents may allow users to share their persistent storage domain blocklists. This would allow communities to act together to protect their privacy. While these suggestions prevent trivial use of this API for user tracking, they do not block it altogether. Within a single domain, a site can continue to track the user during a session, and can then pass all this information to the third party along with any identifying information (names, credit card numbers, addresses) obtained by the site. If a third party cooperates with multiple sites to obtain such information, a profile can still be created. However, user tracking is to some extent possible even with no cooperation from the user agent whatsoever, for instance by using session identifiers in URLs, a technique already commonly used for innocuous purposes but easily repurposed for user tracking (even retroactively). This information can then be shared with other sites, using visitors' IP addresses and other user-specific data (e.g. user-agent headers and configuration settings) to combine separate sessions into coherent user profiles. 12.3.2 Sensitivity of data User agents should treat persistently stored data as potentially sensitive; it's quite possible for emails, calendar appointments, health records, or other confidential documents to be stored in this mechanism. To this end, user agents should ensure that when deleting data, it is promptly deleted from the underlying storage. 12.4 Security 12.4.1 DNS spoofing attacks Because of the potential for DNS spoofing attacks, one cannot guarantee that a host claiming to be in a certain domain really is from that domain. To mitigate this, pages can use TLS. Pages using TLS can be sure that only the user, software working on behalf of the user, and other pages using TLS that have certificates identifying them as being from the same domain, can access their storage areas. 12.4.2 Cross-directory attacks Different authors sharing one host name, for example users hosting content on the now defunct geocities.com , all share one local storage object. There is no feature to restrict the access by pathname. Authors on shared hosts are therefore urged to avoid using these features, as it would be trivial for other authors to read the data and overwrite it. Even if a path-restriction feature was made available, the usual DOM scripting security model would make it trivial to bypass this protection and access the data from any path. 12.4.3 Implementation risks The two primary risks when implementing these persistent storage features are letting hostile sites read information from other domains, and letting hostile sites write information that is then read from other domains. Letting third-party sites read data that is not supposed to be read from their domain causes information leakage , For example, a user's shopping wishlist on one domain could be used by another domain for targeted advertising; or a user's work-in-progress confidential documents stored by a word-processing site could be examined by the site of a competing company. Letting third-party sites write data to the persistent storage of other domains can result in information spoofing , which is equally dangerous. For example, a hostile site could add items to a user's wishlist; or a hostile site could set a user's session identifier to a known ID that the hostile site can then use to track the user's actions on the victim site. Thus, strictly following the origin model described in this specification is important for user security. 13 The HTML syntax This section only describes the rules for resources labeled with an HTML MIME type . Rules for XML resources are discussed in the section below entitled " The XML syntax ". 13.1 Writing HTML documents This section only applies to documents, authoring tools, and markup generators. In particular, it does not apply to conformance checkers; conformance checkers must use the requirements given in the next section ("parsing HTML documents"). Documents must consist of the following parts, in the given order: Optionally, a single U+FEFF BYTE ORDER MARK (BOM) character. Any number of comments and ASCII whitespace DOCTYPE Any number of comments and ASCII whitespace The document element , in the form of an html element Any number of comments and ASCII whitespace The various types of content mentioned above are described in the next few sections. In addition, there are some restrictions on how character encoding declarations are to be serialized, as discussed in the section on that topic. ASCII whitespace before the html element, at the start of the html element and before the head element, will be dropped when the document is parsed; ASCII whitespace after the html element will be parsed as if it were at the end of the body element. Thus, ASCII whitespace around the document element does not round-trip. It is suggested that newlines be inserted after the DOCTYPE, after any comments that are before the document element, after the html element's start tag (if it is not omitted ), and after any comments that are inside the html element but before the head element. Many strings in the HTML syntax (e.g. the names of elements and their attributes) are case-insensitive, but only for ASCII upper alphas and ASCII lower alphas . For convenience, in this section this is just referred to as "case-insensitive". 13.1.1 The DOCTYPE DOCTYPE is a required preamble. DOCTYPEs are required for legacy reasons. When omitted, browsers tend to use a different rendering mode that is incompatible with some specifications. Including the DOCTYPE in a document ensures that the browser makes a best-effort attempt at following the relevant specifications. A DOCTYPE must consist of the following components, in this order: A string that is an ASCII case-insensitive match for the string " ". One or more ASCII whitespace A string that is an ASCII case-insensitive match for the string " html ". Optionally, a DOCTYPE legacy string Zero or more ASCII whitespace A U+003E GREATER-THAN SIGN character (>). In other words, , case-insensitively. For the purposes of HTML generators that cannot output HTML markup with the short DOCTYPE ", a DOCTYPE legacy string may be inserted into the DOCTYPE (in the position defined above). This string must consist of: One or more ASCII whitespace A string that is an ASCII case-insensitive match for the string " SYSTEM ". One or more ASCII whitespace A U+0022 QUOTATION MARK or U+0027 APOSTROPHE character (the quote mark ). The literal string " about:legacy-compat ". A matching U+0022 QUOTATION MARK or U+0027 APOSTROPHE character (i.e. the same character as in the earlier step labeled quote mark ). In other words, or , case-insensitively except for the part in single or double quotes. The DOCTYPE legacy string should not be used unless the document is generated from a system that cannot output the shorter string. 13.1.2 Elements There are six different kinds of elements void elements the template element raw text elements escapable raw text elements foreign elements , and normal elements Void elements area base br col embed hr img input link meta param source track wbr The template element template Raw text elements script style Escapable raw text elements textarea title Foreign elements Elements from the MathML namespace and the SVG namespace Normal elements All other allowed HTML elements are normal elements. Tags are used to delimit the start and end of elements in the markup. Raw text escapable raw text , and normal elements have start tag to indicate where they begin, and an end tag to indicate where they end. The start and end tags of certain normal elements can be omitted , as described below in the section on optional tags . Those that cannot be omitted must not be omitted. Void elements only have a start tag; end tags must not be specified for void elements Foreign elements must either have a start tag and an end tag, or a start tag that is marked as self-closing, in which case they must not have an end tag. The contents of the element must be placed between just after the start tag (which might be implied, in certain cases ) and just before the end tag (which again, might be implied in certain cases ). The exact allowed contents of each individual element depend on the content model of that element, as described earlier in this specification. Elements must not contain content that their content model disallows. In addition to the restrictions placed on the contents by those content models, however, the five types of elements have additional syntactic requirements. Void elements can't have any contents (since there's no end tag, no content can be put between the start tag and the end tag). The template element can have template contents , but such template contents are not children of the template element itself. Instead, they are stored in a DocumentFragment associated with a different Document — without a browsing context — so as to avoid the template contents interfering with the main Document The markup for the template contents of a template element is placed just after the template element's start tag and just before template element's end tag (as with other elements), and may consist of any text character references elements , and comments , but the text must not contain the character U+003C LESS-THAN SIGN (<) or an ambiguous ampersand Raw text elements can have text , though it has restrictions described below. Escapable raw text elements can have text and character references , but the text must not contain an ambiguous ampersand . There are also further restrictions described below. Foreign elements whose start tag is marked as self-closing can't have any contents (since, again, as there's no end tag, no content can be put between the start tag and the end tag). Foreign elements whose start tag is not marked as self-closing can have text character references CDATA sections , other elements , and comments , but the text must not contain the character U+003C LESS-THAN SIGN (<) or an ambiguous ampersand The HTML syntax does not support namespace declarations, even in foreign elements For instance, consider the following HTML fragment: svg metadata cdr:license xmlns:cdr "https://www.example.com/cdr/metadata" name "MIT" /> metadata svg The innermost element, cdr:license , is actually in the SVG namespace, as the " xmlns:cdr " attribute has no effect (unlike in XML). In fact, as the comment in the fragment above says, the fragment is actually non-conforming. This is because SVG 2 does not define any elements called " cdr:license " in the SVG namespace. Normal elements can have text character references , other elements , and comments , but the text must not contain the character U+003C LESS-THAN SIGN (<) or an ambiguous ampersand . Some normal elements also have yet more restrictions on what content they are allowed to hold, beyond the restrictions imposed by the content model and those described in this paragraph. Those restrictions are described below. Tags contain a tag name , giving the element's name. HTML elements all have names that only use ASCII alphanumerics . In the HTML syntax, tag names, even those for foreign elements may be written with any mix of lower- and uppercase letters that, when converted to all-lowercase, matches the element's tag name; tag names are case-insensitive. 13.1.2.1 Start tags Start tags must have the following format: The first character of a start tag must be a U+003C LESS-THAN SIGN character (<). The next few characters of a start tag must be the element's tag name If there are to be any attributes in the next step, there must first be one or more ASCII whitespace Then, the start tag may have a number of attributes, the syntax for which is described below. Attributes must be separated from each other by one or more ASCII whitespace After the attributes, or after the tag name if there are no attributes, there may be one or more ASCII whitespace . (Some attributes are required to be followed by a space. See the attributes section below.) Then, if the element is one of the void elements , or if the element is a foreign element , then there may be a single U+002F SOLIDUS character (/). This character has no effect on void elements , but on foreign elements it marks the start tag as self-closing. Finally, start tags must be closed by a U+003E GREATER-THAN SIGN character (>). 13.1.2.2 End tags End tags must have the following format: The first character of an end tag must be a U+003C LESS-THAN SIGN character (<). The second character of an end tag must be a U+002F SOLIDUS character (/). The next few characters of an end tag must be the element's tag name After the tag name, there may be one or more ASCII whitespace Finally, end tags must be closed by a U+003E GREATER-THAN SIGN character (>). 13.1.2.3 Attributes Attributes for an element are expressed inside the element's start tag. Attributes have a name and a value. Attribute names must consist of one or more characters other than controls U+0020 SPACE, U+0022 ("), U+0027 ('), U+003E (>), U+002F (/), U+003D (=), and noncharacters . In the HTML syntax, attribute names, even those for foreign elements , may be written with any mix of ASCII lower and ASCII upper alphas Attribute values are a mixture of text and character references except with the additional restriction that the text cannot contain an ambiguous ampersand Attributes can be specified in four different ways: Empty attribute syntax Just the attribute name . The value is implicitly the empty string. In the following example, the disabled attribute is given with the empty attribute syntax: input disabled If an attribute using the empty attribute syntax is to be followed by another attribute, then there must be ASCII whitespace separating the two. Unquoted attribute value syntax The attribute name , followed by zero or more ASCII whitespace , followed by a single U+003D EQUALS SIGN character, followed by zero or more ASCII whitespace , followed by the attribute value , which, in addition to the requirements given above for attribute values, must not contain any literal ASCII whitespace any U+0022 QUOTATION MARK characters ("), U+0027 APOSTROPHE characters ('), U+003D EQUALS SIGN characters (=), U+003C LESS-THAN SIGN characters (<), U+003E GREATER-THAN SIGN characters (>), or U+0060 GRAVE ACCENT characters (`), and must not be the empty string. In the following example, the value attribute is given with the unquoted attribute value syntax: input value yes If an attribute using the unquoted attribute syntax is to be followed by another attribute or by the optional U+002F SOLIDUS character (/) allowed in step 6 of the start tag syntax above, then there must be ASCII whitespace separating the two. Single-quoted attribute value syntax The attribute name , followed by zero or more ASCII whitespace , followed by a single U+003D EQUALS SIGN character, followed by zero or more ASCII whitespace , followed by a single U+0027 APOSTROPHE character ('), followed by the attribute value , which, in addition to the requirements given above for attribute values, must not contain any literal U+0027 APOSTROPHE characters ('), and finally followed by a second single U+0027 APOSTROPHE character ('). In the following example, the type attribute is given with the single-quoted attribute value syntax: input type 'checkbox' If an attribute using the single-quoted attribute syntax is to be followed by another attribute, then there must be ASCII whitespace separating the two. Double-quoted attribute value syntax The attribute name , followed by zero or more ASCII whitespace , followed by a single U+003D EQUALS SIGN character, followed by zero or more ASCII whitespace , followed by a single U+0022 QUOTATION MARK character ("), followed by the attribute value , which, in addition to the requirements given above for attribute values, must not contain any literal U+0022 QUOTATION MARK characters ("), and finally followed by a second single U+0022 QUOTATION MARK character ("). In the following example, the name attribute is given with the double-quoted attribute value syntax: input name "be evil" If an attribute using the double-quoted attribute syntax is to be followed by another attribute, then there must be ASCII whitespace separating the two. There must never be two or more attributes on the same start tag whose names are an ASCII case-insensitive match for each other. When a foreign element has one of the namespaced attributes given by the local name and namespace of the first and second cells of a row from the following table, it must be written using the name given by the third cell from the same row. Local name Namespace Attribute name actuate XLink namespace xlink:actuate arcrole XLink namespace xlink:arcrole href XLink namespace xlink:href role XLink namespace xlink:role show XLink namespace xlink:show title XLink namespace xlink:title type XLink namespace xlink:type lang XML namespace xml:lang space XML namespace xml:space xmlns XMLNS namespace xmlns xlink XMLNS namespace xmlns:xlink No other namespaced attribute can be expressed in the HTML syntax Whether the attributes in the table above are conforming or not is defined by other specifications (e.g. SVG 2 and MathML ); this section only describes the syntax rules if the attributes are serialized using the HTML syntax. 13.1.2.4 Optional tags Certain tags can be omitted Omitting an element's start tag in the situations described below does not mean the element is not present; it is implied, but it is still there. For example, an HTML document always has a root html element, even if the string doesn't appear anywhere in the markup. An html element's start tag may be omitted if the first thing inside the html element is not a comment For example, in the following case it's ok to remove the " tag: html head title Hello title head body Welcome to this example. body html Doing so would make the document look like this: head title Hello title head body Welcome to this example. body html This has the exact same DOM. In particular, note that whitespace around the document element is ignored by the parser. The following example would also have the exact same DOM: head title Hello title head body Welcome to this example. body html However, in the following example, removing the start tag moves the comment to before the html element: html head title Hello title head body Welcome to this example. body html With the tag removed, the document actually turns into the same as this: html head title Hello title head body Welcome to this example. body html This is why the tag can only be removed if it is not followed by a comment: removing the tag when there is a comment there changes the document's resulting parse tree. Of course, if the position of the comment does not matter, then the tag can be omitted, as if the comment had been moved to before the start tag in the first place. An html element's end tag may be omitted if the html element is not immediately followed by a comment head element's start tag may be omitted if the element is empty, or if the first thing inside the head element is an element. head element's end tag may be omitted if the head element is not immediately followed by ASCII whitespace or a comment body element's start tag may be omitted if the element is empty, or if the first thing inside the body element is not ASCII whitespace or a comment , except if the first thing inside the body element is a meta link script style , or template element. body element's end tag may be omitted if the body element is not immediately followed by a comment Note that in the example above, the head element start and end tags, and the body element start tag, can't be omitted, because they are surrounded by whitespace: html head title Hello title head body Welcome to this example. body html (The body and html element end tags could be omitted without trouble; any spaces after those get parsed into the body element anyway.) Usually, however, whitespace isn't an issue. If we first remove the whitespace we don't care about: html >< head >< title Hello title > head >< body >< Welcome to this example. > body > html Then we can omit a number of tags without affecting the DOM: title Hello title >< Welcome to this example. At that point, we can also add some whitespace back: title Hello title Welcome to this example. This would be equivalent to this document, with the omitted tags shown in their parser-implied positions; the only whitespace text node that results from this is the newline at the end of the head element: html >< head title Hello title head >< body Welcome to this example. body > html An li element's end tag may be omitted if the li element is immediately followed by another li element or if there is no more content in the parent element. dt element's end tag may be omitted if the dt element is immediately followed by another dt element or a dd element. dd element's end tag may be omitted if the dd element is immediately followed by another dd element or a dt element, or if there is no more content in the parent element. element's end tag may be omitted if the element is immediately followed by an address article aside blockquote details div dl fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hgroup hr main nav ol pre section table , or ul element, or if there is no more content in the parent element and the parent element is an HTML element that is not an audio del ins map noscript or video element, or an autonomous custom element We can thus simplify the earlier example further: title Hello title >< Welcome to this example. An rt element's end tag may be omitted if the rt element is immediately followed by an rt or rp element, or if there is no more content in the parent element. An rp element's end tag may be omitted if the rp element is immediately followed by an rt or rp element, or if there is no more content in the parent element. An optgroup element's end tag may be omitted if the optgroup element is immediately followed by another optgroup element, or if there is no more content in the parent element. An option element's end tag may be omitted if the option element is immediately followed by another option element, or if it is immediately followed by an optgroup element, or if there is no more content in the parent element. colgroup element's start tag may be omitted if the first thing inside the colgroup element is a col element, and if the element is not immediately preceded by another colgroup element whose end tag has been omitted. (It can't be omitted if the element is empty.) colgroup element's end tag may be omitted if the colgroup element is not immediately followed by ASCII whitespace or a comment caption element's end tag may be omitted if the caption element is not immediately followed by ASCII whitespace or a comment thead element's end tag may be omitted if the thead element is immediately followed by a tbody or tfoot element. tbody element's start tag may be omitted if the first thing inside the tbody element is a tr element, and if the element is not immediately preceded by a tbody thead , or tfoot element whose end tag has been omitted. (It can't be omitted if the element is empty.) tbody element's end tag may be omitted if the tbody element is immediately followed by a tbody or tfoot element, or if there is no more content in the parent element. tfoot element's end tag may be omitted if there is no more content in the parent element. tr element's end tag may be omitted if the tr element is immediately followed by another tr element, or if there is no more content in the parent element. td element's end tag may be omitted if the td element is immediately followed by a td or th element, or if there is no more content in the parent element. th element's end tag may be omitted if the th element is immediately followed by a td or th element, or if there is no more content in the parent element. The ability to omit all these table-related tags makes table markup much terser. Take this example: table caption 37547 TEE Electric Powered Rail Car Train Functions (Abbreviated) caption colgroup >< col >< col >< col > colgroup thead tr th Function th th Control Unit th th Central Station th tr thead tbody tr td Headlights td td td td td tr tr td Interior Lights td td td td td tr tr td Electric locomotive operating sounds td td td td td tr tr td Engineer's cab lighting td td > td td td tr tr td Station Announcements - Swiss td td > td td td tr tbody table The exact same table, modulo some whitespace differences, could be marked up as follows: table caption 37547 TEE Electric Powered Rail Car Train Functions (Abbreviated) colgroup >< col >< col >< col thead tr th Function th Control Unit th Central Station tbody tr td Headlights td td tr td Interior Lights td td tr td Electric locomotive operating sounds td td tr td Engineer's cab lighting td td tr td Station Announcements - Swiss td td table Since the cells take up much less room this way, this can be made even terser by having each row on one line: table caption 37547 TEE Electric Powered Rail Car Train Functions (Abbreviated) colgroup >< col >< col >< col thead tr th Function th Control Unit th Central Station tbody tr td Headlights td td tr td Interior Lights td td tr td Electric locomotive operating sounds td td tr td Engineer's cab lighting td td tr td Station Announcements - Swiss td td table The only differences between these tables, at the DOM level, is with the precise position of the (in any case semantically-neutral) whitespace. However , a start tag must never be omitted if it has any attributes. Returning to the earlier example with all the whitespace removed and then all the optional tags removed: title Hello title >< Welcome to this example. If the body element in this example had to have a class attribute and the html element had to have a lang attribute, the markup would have to become: html lang "en" >< title Hello title >< body class "demo" >< Welcome to this example. This section assumes that the document is conforming, in particular, that there are no content model violations. Omitting tags in the fashion described in this section in a document that does not conform to the content models described in this specification is likely to result in unexpected DOM differences (this is, in part, what the content models are designed to avoid). 13.1.2.5 Restrictions on content models For historical reasons, certain elements have extra restrictions beyond even the restrictions given by their content model. table element must not contain tr elements, even though these elements are technically allowed inside table elements according to the content models described in this specification. (If a tr element is put inside a table in the markup, it will in fact imply a tbody start tag before it.) A single newline may be placed immediately after the start tag of pre and textarea elements. This does not affect the processing of the element. The otherwise optional newline must be included if the element's contents themselves start with a newline (because otherwise the leading newline in the contents would be treated like the optional newline, and ignored). The following two pre blocks are equivalent: pre Hello pre pre Hello pre 13.1.2.6 Restrictions on the contents of raw text and escapable raw text elements The text in raw text and escapable raw text elements must not contain any occurrences of the string " (U+003C LESS-THAN SIGN, U+002F SOLIDUS) followed by characters that case-insensitively match the tag name of the element followed by one of U+0009 CHARACTER TABULATION (tab), U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), U+0020 SPACE, U+003E GREATER-THAN SIGN (>), or U+002F SOLIDUS (/). 13.1.3 Text Text is allowed inside elements, attribute values, and comments. Extra constraints are placed on what is and what is not allowed in text based on where the text is to be put, as described in the other sections. 13.1.3.1 Newlines Newlines in HTML may be represented either as U+000D CARRIAGE RETURN (CR) characters, U+000A LINE FEED (LF) characters, or pairs of U+000D CARRIAGE RETURN (CR), U+000A LINE FEED (LF) characters in that order. Where character references are allowed, a character reference of a U+000A LINE FEED (LF) character (but not a U+000D CARRIAGE RETURN (CR) character) also represents a newline 13.1.4 Character references In certain cases described in other sections, text may be mixed with character references . These can be used to escape characters that couldn't otherwise legally be included in text Character references must start with a U+0026 AMPERSAND character (&). Following this, there are three possible kinds of character references: Named character references The ampersand must be followed by one of the names given in the named character references section, using the same case. The name must be one that is terminated by a U+003B SEMICOLON character (;). Decimal numeric character reference The ampersand must be followed by a U+0023 NUMBER SIGN character (#), followed by one or more ASCII digits , representing a base-ten integer that corresponds to a code point that is allowed according to the definition below. The digits must then be followed by a U+003B SEMICOLON character (;). Hexadecimal numeric character reference The ampersand must be followed by a U+0023 NUMBER SIGN character (#), which must be followed by either a U+0078 LATIN SMALL LETTER X character (x) or a U+0058 LATIN CAPITAL LETTER X character (X), which must then be followed by one or more ASCII hex digits representing a hexadecimal integer that corresponds to a code point that is allowed according to the definition below. The digits must then be followed by a U+003B SEMICOLON character (;). The numeric character reference forms described above are allowed to reference any code point excluding U+000D CR, noncharacters , and controls other than ASCII whitespace An ambiguous ampersand is a U+0026 AMPERSAND character (&) that is followed by one or more ASCII alphanumerics , followed by a U+003B SEMICOLON character (;), where these characters do not match any of the names given in the named character references section. 13.1.5 CDATA sections CDATA sections must consist of the following components, in this order: The string " ". Optionally, text , with the additional restriction that the text must not contain the string " ]]> ". The string " ]]> ". CDATA sections can only be used in foreign content (MathML or SVG). In this example, a CDATA section is used to escape the contents of a MathML ms element: You can add a string to a number, but this stringifies the number: math ms ms mo mo mn mn mo mo ms ms math 13.1.6 Comments Comments must have the following format: The string " ", or " --!> ", nor end with the string " ". The string " --> ". The text is allowed to end with the string ", as in 13.2 Parsing HTML documents This section only applies to user agents, data mining tools, and conformance checkers. The rules for parsing XML documents into DOM trees are covered by the next section, entitled " The XML syntax ". User agents must use the parsing rules described in this section to generate the DOM trees from text/html resources. Together, these rules define what is referred to as the HTML parser While the HTML syntax described in this specification bears a close resemblance to SGML and XML, it is a separate language with its own parsing rules. Some earlier versions of HTML (in particular from HTML2 to HTML4) were based on SGML and used SGML parsing rules. However, few (if any) web browsers ever implemented true SGML parsing for HTML documents; the only user agents to strictly handle HTML as an SGML application have historically been validators. The resulting confusion — with validators claiming documents to have one representation while widely deployed web browsers interoperably implemented a different representation — has wasted decades of productivity. This version of HTML thus returns to a non-SGML basis. Authors interested in using SGML tools in their authoring pipeline are encouraged to use XML tools and the XML serialization of HTML. For the purposes of conformance checkers, if a resource is determined to be in the HTML syntax , then it is an HTML document As stated in the terminology section , references to element types that do not explicitly specify a namespace always refer to elements in the HTML namespace . For example, if the spec talks about "a element", then that is an element with the local name " ", the namespace " ", and the interface HTMLMenuElement Where possible, references to such elements are hyperlinked to their definition. 13.2.1 Overview of the parsing model The input to the HTML parsing process consists of a stream of code points , which is passed through a tokenization stage followed by a tree construction stage. The output is a Document object. Implementations that do not support scripting do not have to actually create a DOM Document object, but the DOM tree in such cases is still used as the model for the rest of the specification. In the common case, the data handled by the tokenization stage comes from the network, but it can also come from script running in the user agent, e.g. using the document.write() API. There is only one set of states for the tokenizer stage and the tree construction stage, but the tree construction stage is reentrant, meaning that while the tree construction stage is handling one token, the tokenizer might be resumed, causing further tokens to be emitted and processed before the first token's processing is complete. In the following example, the tree construction stage will be called upon to handle a "p" start tag token while handling the "script" end tag token: ... script document write '' ); script ... To handle these cases, parsers have a script nesting level , which must be initially set to zero, and a parser pause flag , which must be initially set to false. 13.2.2 Parse errors This specification defines the parsing rules for HTML documents, whether they are syntactically correct or not. Certain points in the parsing algorithm are said to be parse errors . The error handling for parse errors is well-defined (that's the processing rules described throughout this specification), but user agents, while parsing an HTML document, may abort the parser at the first parse error that they encounter for which they do not wish to apply the rules described in this specification. Conformance checkers must report at least one parse error condition to the user if one or more parse error conditions exist in the document and must not report parse error conditions if none exist in the document. Conformance checkers may report more than one parse error condition if more than one parse error condition exists in the document. Parse errors are only errors with the syntax of HTML. In addition to checking for parse errors, conformance checkers will also verify that the document obeys all the other conformance requirements described in this specification. Some parse errors have dedicated codes outlined in the table below that should be used by conformance checkers in reports. Error descriptions in the table below are non-normative. Code Description abrupt-closing-of-empty-comment This error occurs if the parser encounters an empty comment that is abruptly closed by a U+003E (>) code point (i.e., or ). The parser behaves as if the comment is closed correctly. abrupt-doctype-public-identifier This error occurs if the parser encounters a U+003E (>) code point in the DOCTYPE public identifier (e.g., ). In such a case, if the DOCTYPE is correctly placed as a document preamble, the parser sets the Document to quirks mode absence-of-digits-in-numeric-character-reference This error occurs if the parser encounters a numeric character reference that doesn't contain any digits (e.g., qux; ). In this case the parser doesn't resolve the character reference. cdata-in-html-content This error occurs if the parser encounters a CDATA section outside of foreign content (SVG or MathML). The parser treats such CDATA sections (including leading " [CDATA[ " and trailing " ]] " strings) as comments. character-reference-outside-unicode-range This error occurs if the parser encounters a numeric character reference that references a code point that is greater than the valid Unicode range. The parser resolves such a character reference to a U+FFFD REPLACEMENT CHARACTER. control-character-in-input-stream This error occurs if the input stream contains a control code point that is not ASCII whitespace or U+0000 NULL. Such code points are parsed as-is and usually, where parsing rules don't apply any additional restrictions, make their way into the DOM. control-character-reference This error occurs if the parser encounters a numeric character reference that references a control code point that is not ASCII whitespace or is a U+000D CARRIAGE RETURN. The parser resolves such character references as-is except C1 control references that are replaced according to the numeric character reference end state end-tag-with-attributes This error occurs if the parser encounters an end tag with attributes . Attributes in end tags are completely ignored and do not make their way into the DOM. duplicate-attribute This error occurs if the parser encounters an attribute in a tag that already has an attribute with the same name. The parser ignores all such duplicate occurrences of the attribute. end-tag-with-trailing-solidus This error occurs if the parser encounters an end tag that has a U+002F (/) code point right before the closing U+003E (>) code point (e.g.,