, then draw using the current filter in the same manner as SVG. 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 , composite within the clipping region over the current output bitmap using the current compositing and blending operator Composite within the clipping region over the current output bitmap using the current compositing and blending operator When compositing onto the output bitmap , pixels that would fall outside of the output bitmap must be discarded. 4.12.5.1.23 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. 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.24 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 Support in all current engines. Firefox 46+ Safari 11.1+ Chrome 66+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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 Support in all current engines. Firefox 50+ Safari 11.1+ Chrome 66+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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 compositing operator. 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 a natural width equal to the numeric value of canvas 's width attribute and a natural 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( bitmap method, when invoked, must run these steps: Let bitmapContext be the ImageBitmapRenderingContext object on which the transferFromImageBitmap() method was called. If bitmap 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 bitmap '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 bitmap 's underlying bitmap data Set the value of bitmap 's [[Detached]] internal slot to true. Unset bitmap 's bitmap data 4.12.5.3 The OffscreenCanvas interface OffscreenCanvas Support in all current engines. Firefox 105+ Safari 16.4+ Chrome 69+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android typedef OffscreenCanvasRenderingContext2D or ImageBitmapRenderingContext or WebGLRenderingContext or WebGL2RenderingContext or GPUCanvasContext OffscreenRenderingContext dictionary ImageEncodeOptions DOMString type = "image/png"; unrestricted double quality }; enum OffscreenRenderingContextId 2d bitmaprenderer webgl webgl2 webgpu };
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 = {}); attribute EventHandler oncontextlost attribute EventHandler oncontextrestored }; OffscreenCanvas is an EventTarget , so both OffscreenCanvasRenderingContext2D and WebGL can fire events at it. OffscreenCanvasRenderingContext2D can fire contextlost and contextrestored , and WebGL can fire webglcontextlost and webglcontextrestored [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 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 as part of the OffscreenCanvas 's relevant agent 's event loop 's update the rendering steps. offscreenCanvas = new OffscreenCanvas width height OffscreenCanvas/OffscreenCanvas Support in all current engines. Firefox 105+ Safari 16.4+ Chrome 69+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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 all current engines. Firefox 105+ Safari 16.4+ Chrome 69+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android Returns an object that exposes an API for drawing on the OffscreenCanvas object. contextId specifies the desired API: " 2d ", " bitmaprenderer ", " webgl ", " webgl2 ", or " webgpu ". 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. WebGPU defines the webgpu " context. [WEBGL] [WEBGPU] 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 has an internal inherited language and inherited direction set when the OffscreenCanvas is created. 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 webgpu , or detached by algorithms defined in this specification. The new OffscreenCanvas( width height constructor steps are: Initialize the bitmap of this to a rectangular array of transparent black pixels of the dimensions specified by width and height Initialize the width of this to width Initialize the height of this to height Set this 's inherited language to explicitly unknown Set this 's inherited direction to " ltr ". Let global be the relevant global object of this If global is a Window object: Let element be the document element of global 's associated Document If element is not null: Set the inherited language of this to element 's language Set the inherited direction of this to element 's directionality 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 Let language and direction be the values of value 's inherited language and inherited direction Unset value 's bitmap Set dataHolder .[[Width]] to width and dataHolder .[[Height]] to height Set dataHolder .[[Language]] to language and dataHolder .[[Direction]] to direction 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]]. Set value 's inherited language to dataHolder .[[Language]] and its inherited direction to dataHolder .[[Direction]]. 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 webgpu detached 2d Let context be the result of running the offscreen 2D context creation algorithm given this and options Set this 's context mode to 2d Return context Return the same object as was returned the last time the method was invoked with this same first argument. Return null. Return null. Return null. Throw an InvalidStateError DOMException bitmaprenderer Let context be the result of running the ImageBitmapRenderingContext creation algorithm given this and options Set this 's context mode to bitmaprenderer Return context Return null. 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 webgl " or " webgl2 Let context be the result of following the instructions given in the WebGL specifications' Context Creation sections. [WEBGL] If context is null, then return null; otherwise set this 's context mode to webgl or webgl2 Return context Return null. Return null. Return the same value as was returned the last time the method was invoked with this same first argument. Return null. Throw an InvalidStateError DOMException webgpu Let context be the result of following the instructions given in WebGPU 's Canvas Rendering section. [WEBGPU] If context is null, then return null; otherwise set this 's context mode to webgpu Return context Return null. 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 all current engines. Firefox 105+ Safari 16.4+ Chrome 69+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android offscreenCanvas height value OffscreenCanvas/height Support in all current engines. Firefox 105+ Safari 16.4+ Chrome 69+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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] The resizing behavior for " webgpu " context is defined in WebGPU [WEBGPU] If an OffscreenCanvas object whose dimensions were changed has placeholder canvas element , then the placeholder canvas element 's natural size will only be updated during the OffscreenCanvas 's relevant agent 's event loop 's update the rendering steps. promise offscreenCanvas convertToBlob ([ options ]) OffscreenCanvas/convertToBlob Support in all current engines. Firefox 105+ Safari 16.4+ Chrome 69+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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 all current engines. Firefox 105+ Safari 16.4+ Chrome 69+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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 steps are: If the value of this 's [[Detached]] internal slot is true, then return a promise rejected with an InvalidStateError DOMException If this 's context mode is 2d and the rendering context's output bitmap 's origin-clean flag is set to false, then return a promise rejected with SecurityError DOMException If this 's bitmap has no pixels (i.e., either its horizontal dimension or its vertical dimension is zero), then return promise rejected with an IndexSizeError DOMException Let bitmap be a copy of this 's bitmap Let result be a new promise object. Let global be this 's relevant global object Run these steps in parallel Let file be serialization of bitmap as a file , with options 's type and quality if present. Queue a global task on the canvas blob serialization task source given global 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 global 's relevant realm , 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 is false. This means that if the rendering context of this OffscreenCanvas is WebGLRenderingContext , the value of preserveDrawingBuffer will have no effect. [WEBGL] Return image 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 OffscreenCanvas interface: Event handler Event handler event type oncontextlost contextlost oncontextrestored contextrestored 4.12.5.3.1 The offscreen 2D rendering context OffscreenCanvasRenderingContext2D Support in all current engines. Firefox 105+ Safari 16.4+ Chrome 69+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android Exposed =( Window Worker )] interface OffscreenCanvasRenderingContext2D readonly attribute OffscreenCanvas canvas }; OffscreenCanvasRenderingContext2D includes CanvasSettings 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; An OffscreenCanvasRenderingContext2D object has an associated OffscreenCanvas object , which is the OffscreenCanvas object from which the OffscreenCanvasRenderingContext2D object was created. 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 Run the canvas settings output bitmap initialization algorithm , given context and settings Set context 's output 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 output bitmap to transparent black . Otherwise, initialize the pixels to opaque black Return context 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 bitmap contents are copied 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 OffscreenCanvas is updated from a worker event loop and the window event loop of the placeholder canvas element is busy. However, such shortcuts cannot 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 enum PredefinedColorSpace srgb srgb-linear display-p3 display-p3-linear }; The PredefinedColorSpace enumeration is used to specify the color space of the canvas's backing store. The " srgb " value indicates the 'srgb' color space. The " srgb-linear " value indicates the 'srgb-linear' color space. The " display-p3 " value indicates the 'display-p3' color space. The " display-p3-linear " value indicates the 'display-p3-linear' color space. Color space conversion must be applied to the canvas's backing store when rendering the canvas to the output device. The algorithm for converting between color spaces can be found in the Converting Colors section of CSS Color . This color space conversion is 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. [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 component, the serialized image must be the bitmap image composited onto an opaque black background using the source-over compositing 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. For image types that support multiple bit depths, the serialized image must use the bit depth that best preserves content of the underlying bitmap. For example, when serializing a 2D context that has color type of float16 to type image/png ", the resulting image would have 16 bits per sample. This serialization will still lose significant detail (all values less than 0.5/65535 would be clamped to 0, and all values greater than 1 would be clamped to 1). 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 quality is a Number 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, OffscreenCanvas objects, 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'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 components of a pixel represent that pixel's color, and its alpha component represents that pixel's opacity. Under premultiplied alpha, however, the red, green, and blue components of a pixel represent the amounts of color that the pixel adds to the image, and its alpha component represents the amount that the pixel obscures whatever is behind it. For instance, assuming the color components 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 components by its alpha component (remapping the range of the alpha component 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 components by its alpha component. 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 using finite precision entails a loss of accuracy, 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 output 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 Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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 observedAttributes "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 formAssociated true static observedAttributes '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 hasAttribute '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 formAssociated true static observedAttributes '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 hasAttribute '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 observedAttributes "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.1.7 Scoped custom element registries To allow multiple libraries to co-exist without explicit coordination, CustomElementRegistry can be used in a scoped fashion as well. const scoped new CustomElementRegistry (); scoped define "example-element" ExampleElement ); const element document createElement "example-element" customElementRegistry scoped }); A node with an associated scoped CustomElementRegistry will use that registry for all its operations, such as when invoking setHTMLUnsafe() 4.13.1.8 Exposing custom element states Built-in elements provided by user agents have certain states that can change over time depending on user interaction and other factors, and are exposed to web authors through pseudo-classes . For example, some form controls have the "invalid" state, which is exposed through the :invalid pseudo-class Like built-in elements, custom elements can have various states to be in too, and custom element authors want to expose these states in a similar fashion as the built-in elements. This is done via the :state() pseudo-class. A custom element author can use the states property of ElementInternals to add and remove such custom states, which are then exposed as arguments to the :state() pseudo-class. The following shows how :state() can be used to style a custom checkbox element. Assume that LabeledCheckbox doesn't expose its "checked" state via a content attribute. script class LabeledCheckbox extends HTMLElement constructor () super (); this _internals this attachInternals (); this addEventListener 'click' this _onClick bind this )); const shadowRoot this attachShadow ({ mode 'closed' }); shadowRoot innerHTML `Label ` get checked () return this _internals states has 'checked' ); set checked flag if flag this _internals states add 'checked' ); else this _internals states delete 'checked' ); _onClick event this checked this checked customElements define 'labeled-checkbox' LabeledCheckbox ); script style labeled-checkbox border dashed red labeled-checkbox state checked border solid style labeled-checkbox You need to check this labeled-checkbox Custom pseudo-classes can even target shadow parts. An extension of the above example shows this: script class QuestionBox extends HTMLElement constructor () super (); const shadowRoot this attachShadow ({ mode 'closed' }); shadowRoot innerHTML `Question
Yes ` customElements define 'question-box' QuestionBox ); script style question-box :: part checkbox color red question-box :: part checkbox state checked color green style question-box Continue? question-box 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.2.1 Preserving custom element state when moved This section is non-normative. When manipulating the DOM tree, an element can be moved in the tree while connected. This applies to custom elements as well. By default, the " disconnectedCallback " and " connectedCallback " would be called on the element, one after the other. This is done to maintain compatibility with existing custom elements that predate the moveBefore() method. This means that by default, custom elements reset their state as if they were removed and re-inserted. In the example above , the impact would be that the observer would be disconnected and re-connected, and the tab index would be reset. To opt in to a state-preserving behavior while moving , the author can implement a " connectedMoveCallback ". The existence of this callback, even if empty, would supersede the default behavior of calling " disconnectedCallback " and " connectedCallback ". " connectedMoveCallback " can also be an appropriate place to execute logic that depends on the element's ancestors. For example: class TacoButton extends HTMLElement static observedAttributes "disabled" ]; constructor () super (); this _internals this attachInternals (); this _internals role "button" this _observer new MutationObserver (() => this _internals ariaLabel this textContent }); _notifyMain () if this parentElement tagName === "MAIN" // Execute logic that depends on ancestors. connectedCallback () this setAttribute "tabindex" "0" ); this _observer observe this childList true characterData true subtree true }); this _notifyMain (); disconnectedCallback () this _observer disconnect (); // Implementing this function would avoid resetting the tab index or re-registering the // mutation observer when this element is moved inside the DOM without being disconnected. connectedMoveCallback () // The parent can change during a state-preserving move. this _notifyMain (); 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 Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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 a valid attribute local name 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 « ». A string name is a valid custom element name if all of the following are true: name is a valid element local name This ensures the custom element can be created with createElement() name 's 0th code point is an ASCII lower alpha This ensures the HTML parser will treat the name as a tag name instead of as text. name does not contain any ASCII upper alphas This ensures the user agent can always treat HTML elements ASCII-case-insensitively. name contains a U+002D (-); and This is used for namespacing and to ensure forward compatibility (since no elements will be added to HTML, SVG, or MathML with hyphen-containing local names going forward). name is not one 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] 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 ", " connectedMoveCallback ", " 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 null or a CustomElementRegistry object registry , string-or-null namespace , string localName , and string-or-null is , perform the following steps. They will return either a custom element definition or null: If registry is null, then return null. If namespace is not the HTML namespace , then return null. If registry 's custom element definition set contains an item with name and local name both equal to localName , then return that item. If registry 's custom element definition set contains an item with name equal to is and local name equal to localName , then return that item. Return null. 4.13.4 The CustomElementRegistry interface CustomElementRegistry Support in all current engines. Firefox 63+ Safari 10.1+ Chrome 54+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android Each similar-origin window agent has an associated active custom element constructor map , which is a map of constructors to CustomElementRegistry objects. Window/customElements Support in all current engines. Firefox 63+ Safari 10.1+ Chrome 54+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android The Window customElements getter steps are: Assert this 's associated Document 's custom element registry is a CustomElementRegistry object. Window 's associated Document is always created with a new CustomElementRegistry object. Return this 's associated Document 's custom element registry Exposed Window interface CustomElementRegistry constructor ();
CEReactions undefined define DOMString name CustomElementConstructor constructor optional ElementDefinitionOptions options = {}); CustomElementConstructor or undefined get DOMString name ); DOMString getName CustomElementConstructor constructor ); Promise CustomElementConstructor whenDefined DOMString name ); CEReactions undefined upgrade Node root ); CEReactions undefined initialize Node root ); }; callback CustomElementConstructor HTMLElement (); dictionary ElementDefinitionOptions DOMString extends }; Every CustomElementRegistry has an is scoped , a boolean, initially false. Every CustomElementRegistry has a scoped document set , a set of Document objects, initially « ». Every CustomElementRegistry has a custom element definition set , a set of custom element definitions initially « ». Lookup of items in this set uses their name local name , or constructor Every CustomElementRegistry also has an element definition is running boolean which is used to prevent reentrant invocations of element definition . It is initially false. Every CustomElementRegistry also has a when-defined promise map , a map of valid custom element names to promises. It is used to implement the whenDefined() method. To look up a custom element registry , given a Node object node If node is an Element object, then return node 's custom element registry If node is a ShadowRoot object, then return node 's custom element registry If node is a Document object, then return node 's custom element registry Return null. registry window customElements Returns the global's associated Document 's CustomElementRegistry object. registry = new CustomElementRegistry () Constructs a new CustomElementRegistry object, for scoped usage. registry define name constructor CustomElementRegistry/define Support in all current engines. Firefox 63+ Safari 10.1+ Chrome 54+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android Defines a new custom element , mapping the given name to the given constructor as an autonomous custom element registry 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, or when registry is not a global CustomElementRegistry object. registry get name CustomElementRegistry/get Support in all current engines. Firefox 63+ Safari 10.1+ Chrome 54+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android Retrieves the custom element constructor defined for the given name . Returns undefined if there is no custom element definition with the given name registry getName constructor Retrieves the given name for a custom element defined for the given constructor . Returns null if there is no custom element definition with the given constructor registry whenDefined name CustomElementRegistry/whenDefined Support in all current engines. Firefox 63+ Safari 10.1+ Chrome 54+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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 registry upgrade root CustomElementRegistry/upgrade Support in all current engines. Firefox 63+ Safari 12.1+ Chrome 68+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android Tries to upgrade all shadow-including inclusive descendant elements of root , even if they are not connected registry initialize root Each inclusive descendant of root with a null registry will have it updated to this CustomElementRegistry object. A NotSupportedError DOMException will be thrown if this CustomElementRegistry object is not for scoped usage and either root is a Document node or root 's node document 's custom element registry is not this CustomElementRegistry object. The new CustomElementRegistry() constructor steps are to set this 's is scoped to true. Element definition is a process of adding a custom element definition to the CustomElementRegistry . This is accomplished by the define() method. The define( name constructor options method steps are: 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 's custom element definition set contains an item with name name , then throw a NotSupportedError DOMException If this 's custom element definition set contains an item with constructor constructor then throw a NotSupportedError DOMException Let localName be name Let extends be options [" extends "] if it exists ; otherwise null. If extends is not null: If this 's is scoped is true, then throw a NotSupportedError DOMException 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 's element definition is running is true, then throw NotSupportedError DOMException Set this 's element definition is running to true. Let formAssociated be false. Let disableInternals be false. Let disableShadow be false. Let observedAttributes be an empty sequence Run the following steps while catching any exceptions: Let prototype be ? Get constructor "prototype"). If prototype is not an Object , then throw a TypeError exception. Let lifecycleCallbacks be the ordered map «[ " connectedCallback " → null, " disconnectedCallback " → null, " connectedMoveCallback " → null, " adoptedCallback " → null, " attributeChangedCallback " → null ]». For each callbackName of the keys of lifecycleCallbacks Let callbackValue be ? Get prototype callbackName ). If callbackValue is not undefined, then set lifecycleCallbacks callbackName ] to the result of converting callbackValue to the Web IDL Function callback type. If lifecycleCallbacks [" attributeChangedCallback "] is not null: Let observedAttributesIterable be ? Get constructor , "observedAttributes"). 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"). If disabledFeaturesIterable is not undefined, then set disabledFeatures to the result of converting disabledFeaturesIterable to a sequence . Rethrow any exceptions from the conversion. If disabledFeatures contains internals ", then set disableInternals to true. If disabledFeatures contains shadow ", then set disableShadow to true. Let formAssociatedValue be ? Get constructor , "formAssociated"). Set formAssociated to the result of converting formAssociatedValue to a boolean If formAssociated is true, then for each callbackName of « " formAssociatedCallback ", " formResetCallback ", " formDisabledCallback ", " formStateRestoreCallback »: Let callbackValue be ? Get prototype callbackName ). If callbackValue is not undefined, then set lifecycleCallbacks callbackName ] to the result of converting callbackValue to the Web IDL Function callback type. Then, regardless of whether the above steps threw an exception or not: set this 's element definition is running to false. Finally, if the steps threw an exception, rethrow that exception. 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 Append definition to this 's custom element definition set If this 's is scoped is true, then for each document of this 's scoped document set upgrade particular elements within a document given this document definition , and localName Otherwise, upgrade particular elements within a document given this this 's relevant global object 's associated Document definition localName , and name If this 's when-defined promise map name exists Resolve this 's when-defined promise map name ] with constructor Remove this 's when-defined promise map name ]. To upgrade particular elements within a document given a CustomElementRegistry object registry , a Document object document , a custom element definition definition , a string localName , and optionally a string name (default localName ): Let upgradeCandidates be all elements that are shadow-including descendants of document , whose custom element registry is registry whose namespace is the HTML namespace , and whose local name is localName in shadow-including tree order . Additionally, if name is not localName , only include elements whose is value is equal to name For each element element of upgradeCandidates enqueue a custom element upgrade reaction given element and definition The get( name method steps are: If this 's custom element definition set contains an item with name name , then return that item's constructor Return undefined. CustomElementRegistry/getName Firefox 116+ Safari 🔰 preview+ Chrome 117+ Opera Edge 117+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android The getName( constructor method steps are: If this 's custom element definition set contains an item with constructor constructor , then return that item's name Return null. The whenDefined( name method steps are: If name is not a valid custom element name , then return promise rejected with SyntaxError DOMException If this 's custom element definition set contains an item with name name , then return promise resolved with that item's constructor If this 's when-defined promise map name ] does not exist , then set this 's when-defined promise map name ] to a new promise. Return this 's when-defined promise map name ]. 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 }); The upgrade( root method steps are: For each shadow-including inclusive descendant candidate of root , in shadow-including tree order If candidate is not an Element node, then continue If candidate 's custom element registry is not this , then continue 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! The initialize( root method steps are: If this 's is scoped is false and either root is a Document node or root 's node document 's custom element registry is not this , then throw a NotSupportedError DOMException If root is a Document node whose custom element registry is null, then set root 's custom element registry to this Otherwise, if root is a ShadowRoot node whose custom element registry is null, then set root 's custom element registry to this For each inclusive descendant inclusiveDescendant of root in tree order If inclusiveDescendant is not an Element node, then continue If inclusiveDescendant 's custom element registry is null: Set inclusiveDescendant 's custom element registry to this If this 's is scoped is true, then append inclusiveDescendant 's node document to this 's scoped document set If inclusiveDescendant 's custom element registry is not this , then continue Try to upgrade inclusiveDescendant Once the custom element registry of a node is initialized to a CustomElementRegistry object, it intentionally cannot be changed any further. This simplifies reasoning about code and allows implementations to optimize. 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 « attribute 's local name, null, attribute 's value, attribute 's namespace ». If element is connected , then enqueue a custom element callback reaction with element , callback name " connectedCallback ", and « ». Add element to the end of definition 's construction stack Let be definition 's constructor Set the surrounding agent 's active custom element constructor map ] to element 's custom element registry Run the following steps 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 steps, regardless of whether the above steps threw an exception or not: Remove the surrounding agent 's active custom element constructor map ]. This is a no-op if immediately calls super() as it ought to do. 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 an element element Let definition be the result of looking up a custom element definition given element 's custom element registry 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 moved , its connectedMoveCallback 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 the user agent updates a form-associated custom element 's value on behalf of a user or as part of navigation , its formStateRestoreCallback is called, given the new state and a string indicating a reason, " autocomplete " or " restore ", 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 is 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 callbackName is " connectedMoveCallback " and callback is null: Let disconnectedCallback be the value of the entry in definition 's lifecycle callbacks with key " disconnectedCallback ". Let connectedCallback be the value of the entry in definition 's lifecycle callbacks with key " connectedCallback ". If connectedCallback and disconnectedCallback are null, then return. Set callback to the following steps: If disconnectedCallback is not null, then call disconnectedCallback with no arguments. If connectedCallback is not null, then call connectedCallback with no arguments. If callback is null, then return. If callbackName is " attributeChangedCallback ": 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 If this throws an exception, catch it, and report it for reaction 's custom element definition 's constructor 's corresponding JavaScript object's associated realm 's global object callback reaction Invoke reaction 's callback function with reaction 's arguments and " report ", and callback this value set to element 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 (null or an ElementInternals object), initially null. HTMLElement/attachInternals Support in all current engines. Firefox 93+ Safari 16.4+ Chrome 77+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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 custom element registry this 's namespace this 's local name , and null. If definition is null, then throw a NotSupportedError DOMException If definition 's disable internals is true, then throw a NotSupportedError DOMException If this 's attached internals is non-null, then throw a NotSupportedError DOMException If this 's custom element state is not " precustomized " or " custom ", then throw a NotSupportedError DOMException Set this 's attached internals to a new ElementInternals instance whose target element is this Return this 's attached internals 4.13.7.1 The ElementInternals interface ElementInternals Support in all current engines. Firefox 93+ Safari 16.4+ Chrome 77+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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
// Custom state pseudo-class SameObject readonly attribute CustomStateSet states };
// 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. ElementInternals/shadowRoot Support in all current engines. Firefox 93+ Safari 16.4+ Chrome 88+ Opera Edge 88+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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 « the state to be restored, " 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 a form-associated custom element , callback name " formStateRestoreCallback ", and « the state value determined by history of state value and some heuristics, " 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" ElementInternals/setFormValue Support in all current engines. Firefox 98+ Safari 16.4+ Chrome 77+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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 element 's submission value to value if value is not a FormData object, or to a clone of value 's entry list 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 a clone of state 's entry list 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. ElementInternals/setValidity Support in all current engines. Firefox 98+ Safari 16.4+ Chrome 77+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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. If anchor is not given, then set it to element Otherwise, if anchor is not a shadow-including inclusive descendant of element , then throw a NotFoundError DOMException Set element 's validation anchor to anchor ElementInternals/validationMessage Support in all current engines. Firefox 98+ Safari 16.4+ Chrome 77+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android The validationMessage getter steps are: Let element be this 's target element If element is not a form-associated custom element , then throw a NotSupportedError DOMException Return element 's validation message The entry construction algorithm for a form-associated custom element , given an element element and an entry 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, create an entry with the name attribute value and the submission value , and append it to entry list 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. Each custom element has an internal content attribute map , which is a map , initially empty. See the Requirements related to ARIA and to platform accessibility APIs section for information on how this impacts platform accessibility APIs. 4.13.7.5 Custom state pseudo-class internals states .add( value Adds the string value to the element's states set to be exposed as a pseudo-class. internals states .has( value Returns true if value is in the element's states set , otherwise false. internals states .delete( value If the element's states set has value , then it will be removed and true will be returned. Otherwise, false will be returned. internals states .clear() Removes all values from the element's states set for (const stateName of internals states for (const stateName of internals states .entries()) for (const stateName of internals states .keys()) for (const stateName of internals states .values()) Iterates over all values in the element's states set internals states .forEach( callback Iterates over all values in the element's states set by calling callback once for each value. internals states .size Returns the number of values in the element's states set Each custom element has a states set , which is a CustomStateSet , initially empty. Exposed Window interface CustomStateSet setlike DOMString >; }; The states getter steps are to return this 's target element 's states set The states set can expose boolean states represented by existence/non-existence of string values. If an author wants to expose a state which can have three values, it can be converted to three exclusive boolean states. For example, a state called readyState with "loading" "interactive" , and "complete" values can be mapped to three exclusive boolean states, "loading" "interactive" , and "complete" // Change the readyState from anything to "complete". this _readyState "complete" this _internals states delete "loading" ); this _internals states delete "interactive" ); this _internals states add "complete" ); 4.14 Common idioms without dedicated elements 4.14.1 Breadcrumb navigation This specification does not provide a machine-readable way of describing breadcrumb 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 Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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 Safari iOS 3.2+ Chrome Android WebView Android 1.5+ Samsung Internet Opera Android :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 Safari iOS Chrome Android WebView Android Samsung Internet 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 Safari iOS Chrome Android WebView Android Samsung Internet 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 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 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 focusable The element is being activated if it is in a formal activation state 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 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 released; for a finger in a multitouch environment, while the finger is touching the display surface). Per the definition in Selectors :active also matches flat tree ancestors of elements that are being activated [SELECTORS] Additionally, any element that is the labeled control of a label element that is currently matching :active , also matches :active . (But, it does not count as being being activated .) :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 Safari iOS 1+ Chrome Android WebView Android Samsung Internet 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. Per the definition in Selectors :hover also matches flat tree ancestors of elements that are designated [SELECTORS] Additionally, any element that is the labeled control of a label element that is currently matching :hover , also matches :hover . (But, it does not count as being designated .) 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 by being designated ; the label and elements match it because of the condition in Selectors about flat tree ancestors; and the element with ID " " matches it through the additional condition above on labeled controls (i.e., its label element matches :hover ). However, the element with ID " " does not match :hover : its flat tree descendant is not designated, even though that flat tree descendant 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 Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 10.1+ For the purposes of the CSS :focus pseudo-class , an element has the focus when: it is not itself a navigable container ; and any of the following are true: it is one of the elements listed in the current focus chain of the top-level traversable ; 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 Safari iOS 2+ Chrome Android WebView Android 2+ Samsung Internet 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] :popover-open :popover-open Support in all current engines. Firefox 🔰 114+ Safari preview+ Chrome 114+ Opera Edge 114+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android The :popover-open pseudo-class is defined to match any HTML element whose popover attribute is not in the No Popover state and whose popover visibility state is showing :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 Safari iOS Chrome Android WebView Android 2+ Samsung Internet 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 Safari iOS Chrome Android WebView Android 2+ Samsung Internet 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 Chrome Android 18+ WebView Android 2+ Samsung Internet 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 Safari iOS 1+ Chrome Android WebView Android 37+ Samsung Internet 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) Internet Explorer No Firefox Android Safari iOS 5+ Chrome Android WebView Android 37+ Samsung Internet 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 Safari iOS 5+ Chrome Android WebView Android 37+ Samsung Internet 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 Safari iOS 5+ Chrome Android WebView Android 37+ Samsung Internet 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 :user-valid The :user-valid pseudo-class must match input textarea , and select elements whose user validity is true, are candidates for constraint validation and that satisfy their constraints :user-invalid The :user-invalid pseudo-class must match input textarea , and select elements whose user validity is true, 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 Chrome Android WebView Android 2.2+ 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 Chrome Android WebView Android 2.2+ Samsung Internet 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 Safari iOS 5+ Chrome Android WebView Android 4.4.3+ Samsung Internet 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 Safari iOS 5+ Chrome Android WebView Android 37+ Samsung Internet 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 Firefox 86+ Safari 15+ Chrome 🔰 1+ Opera Edge 🔰 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS 15+ Chrome Android WebView Android Samsung Internet Opera Android :-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 Chrome Android WebView Android 37+ Samsung Internet 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 Chrome Android WebView Android 37+ Samsung Internet 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 :modal The :modal pseudo-class must match any element falling into one of the following categories: dialog elements whose is modal is true elements whose fullscreen flag is true :dir(ltr) :dir Firefox 49+ Safari 16.4+ Chrome No Opera Edge No Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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 '. Custom state pseudo-class The :state( identifier pseudo-class must match all custom element s whose states set 's set entries contains identifier :heading The :heading pseudo-class must match all h1 h2 h3 h4 h5 , and h6 elements. :heading( integer #) The :heading( integer #) pseudo-class must match all h1 h2 h3 h4 h5 , and h6 elements that have a heading level of integer [CSSSYNTAX] [CSSVALUES] :playing The :playing pseudo-class must match all media elements whose paused attribute is false. :paused The :paused pseudo-class must match all media elements whose paused attribute is true. :seeking The :seeking pseudo-class must match all media elements whose seeking attribute is true. :buffering The :buffering pseudo-class must match all media elements whose paused attribute is false, networkState attribute is NETWORK_LOADING , and ready state is HAVE_CURRENT_DATA or less. :stalled The :stalled pseudo-class must match all media elements that match the :buffering pseudo-class and whose is currently stalled is true. This pseudo-class is intended for displaying player state UI when video playback has been buffering for too long. Unlike the stalled event, which fires whenever the network download has stalled regardless of playback or ready state. :muted The :muted pseudo-class must match all media elements that are muted :volume-locked The :volume-locked pseudo-class must match all media elements when the user agent's volume locked is true. :open The :open pseudo-class must match any element falling into one of the following categories: details elements that have an open attribute dialog elements that have an open attribute select elements that are a drop-down box and whose drop-down boxes are open input elements that support a picker and whose pickers are open 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 Edge Yes Edge (Legacy) 12+ Internet Explorer Yes Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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 Edge Yes Edge (Legacy) 12+ Internet Explorer Yes Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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 Edge Yes Edge (Legacy) 12+ Internet Explorer Yes Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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 parsing it returns failure, 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 Edge Yes Edge (Legacy) 12+ Internet Explorer Yes Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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 Edge Yes Edge (Legacy) 12+ Internet Explorer Yes Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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 result of encoding-parsing-and-serializing a URL given the element's src attribute's value, relative to the element's node document , at the time the attribute is set, or the empty string if there is no such attribute or the result is failure. If the element is an area , or link element The value is the result of encoding-parsing-and-serializing a URL given the element's href attribute's value, relative to the element's node document , at the time the attribute is set, or the empty string if there is no such attribute or the result is failure. If the element is an object element The value is the result of encoding-parsing-and-serializing a URL given the element's data attribute's value, relative to the element's node document , at the time the attribute is set, or the empty string if there is no such attribute or the result is failure. 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 alphanumerics , 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 canceled 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 one engine only. Firefox No Safari No Chrome 102+ Opera No Edge 102+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android Global_attributes/hidden Support in all current engines. Firefox 4+ Safari 5.1+ Chrome 10+ Opera Edge 79+ Edge (Legacy) 12+ Internet Explorer 11 Firefox Android Safari iOS Chrome Android WebView Android 4+ Samsung Internet Opera Android All HTML elements may have the hidden content attribute set. The hidden attribute is an enumerated attribute with the following keywords and states: Keyword State Brief description hidden Hidden Will not be rendered. until-found Hidden Until Found Will not be rendered, but content inside will be accessible to find-in-page and fragment navigation The attribute's missing value default is the Not Hidden state, and its invalid value default and empty value default are both the Hidden state. When an element has the hidden attribute in the Hidden state, 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 are in the Hidden state. The requirement for user agents not to render elements that are in the Hidden state can be implemented indirectly through the style layer. For example, a web browser could implement these requirements using the rules suggested in the Rendering section When an element has the hidden attribute in the Hidden Until Found state, it indicates that the element is hidden like the Hidden state but the content inside the element will be accessible to find-in-page and fragment navigation . When these features attempt to scroll to a target which is in the element's subtree, the user agent will remove the hidden attribute in order to reveal the content before scrolling to it by running the ancestor revealing algorithm on the target node. Web browsers will use 'content-visibility: hidden' instead of 'display: none' when the hidden attribute is in the Hidden Until Found state, as specified 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 state. Authors therefore have to take care when writing their style sheets to make sure that the attribute is still styled as expected. In addition, legacy user agents which don't support the Hidden Until Found state will have 'display: none' instead of 'content-visibility: hidden', so authors are encouraged to make sure that their style sheets don't change the 'display' or 'content-visibility' properties of Hidden Until Found elements. Since elements with the hidden attribute in the Hidden Until Found state use 'content-visibility: hidden' instead of 'display: none', there are two caveats of the Hidden Until Found state that make it different from the Hidden state: The element needs to be affected by layout containment in order to be revealed by find-in-page. This means that if the element in the Hidden Until Found state has a 'display' value of 'none', 'contents', or 'inline', then the element will not be revealed by find-in-page. The element will still have a generated box when in the Hidden Until Found state, which means that borders, margin, and padding will still be rendered around the element. 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 4+ Safari 5.1+ Chrome 6+ Opera 11.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 11 Firefox Android Safari iOS Chrome Android WebView Android 3+ Samsung Internet Opera Android 12+ The hidden getter steps are: If the hidden attribute is in the Hidden Until Found state, then return " until-found ". If the hidden attribute is set, then return true. Return false. The hidden setter steps are: If the given value is a string that is an ASCII case-insensitive match for until-found ", then set the hidden attribute to " until-found ". Otherwise, if the given value is false, then remove the hidden attribute. Otherwise, if the given value is the empty string, then remove the hidden attribute. Otherwise, if the given value is null, then remove the hidden attribute. Otherwise, if the given value is 0, then remove the hidden attribute. Otherwise, if the given value is NaN, then remove the hidden attribute. Otherwise, set the hidden attribute to the empty string. An ancestor reveal pair is a tuple consisting of a node and a string The ancestor revealing algorithm given a node target is: Let ancestorsToReveal be « ». Let ancestor be target While ancestor has a parent node within the flat tree If ancestor has a hidden attribute in the Hidden Until Found state, then append ancestor , " until-found ") to ancestorsToReveal If ancestor is slotted into the second slot of a details element which does not have an open attribute, then append ancestor 's parent node, " details ") to ancestorsToReveal Set ancestor to the parent node of ancestor within the flat tree For each ( ancestorToReveal revealType ) of ancestorsToReveal If ancestorToReveal is not connected , then return. If revealType is " until-found ": If ancestorToReveal 's hidden attribute is not in the Hidden Until Found state, then return. Fire an event named beforematch at ancestorToReveal with the bubbles attribute initialized to true. If ancestorToReveal is not connected , then return. If ancestorToReveal 's hidden attribute is not in the Hidden Until Found state, then return. Remove the hidden attribute from ancestorToReveal Otherwise: Assert revealType is " details ". If ancestorToReveal has an open attribute, then return. Set ancestorToReveal 's open attribute to the empty string. 6.2 Page visibility traversable navigable 's system visibility state , including its initial value upon creation, is determined by the user agent. It represents, for example, whether the browser window is minimized, a browser tab is currently in the background, or a system element such as a task switcher obscures the page. When a user agent determines that the system visibility state for traversable navigable traversable has changed to newState , it must run the following steps: Let navigables be the inclusive descendant navigables of traversable 's active document For each navigable of navigables in what order? Let document be navigable 's active document Queue a global task on the user interaction task source given document 's relevant global object to update the visibility state of document with newState Document has a visibility state , which is either " hidden " or " visible ", initially set to hidden ". Document/visibilityState Support in all current engines. Firefox 18+ Safari 7+ Chrome 33+ Opera 20+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android Safari iOS Chrome Android WebView Android 4.4.3+ Samsung Internet Opera Android 20+ The visibilityState getter steps are to return this 's visibility state Document/hidden Support in all current engines. Firefox 18+ Safari 7+ Chrome 33+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android Safari iOS Chrome Android WebView Android 4.4.3+ Samsung Internet Opera Android 12.1+ The hidden getter steps are to return true if this 's visibility state is hidden ", otherwise false. To update the visibility state of Document document to visibilityState If document 's visibility state equals visibilityState then return. Set document 's visibility state to visibilityState Queue a new VisibilityStateEntry whose visibility state is visibilityState and whose timestamp is the current high resolution time given document 's relevant global object Run the screen orientation change steps with document [SCREENORIENTATION] Run the view transition page visibility change steps with document Run any page visibility change steps which may be defined in other specifications, with visibility state and document It would be better if specification authors sent a pull request to add calls from here into their specifications directly, instead of using the page visibility change steps hook, to ensure well-defined cross-specification call order. As of the time of this writing the following specifications are known to have page visibility change steps , which will be run in an unspecified order: Device Posture API and Web NFC [DEVICEPOSTURE] [WEBNFC] Fire an event named visibilitychange at document , with its bubbles attribute initialized to true. To set the initial visibility state of Document document to visibilityState Set document 's visibility state to visibilityState Queue a new VisibilityStateEntry whose visibility state is document 's visibility state and whose timestamp is 0. 6.2.1 The VisibilityStateEntry interface VisibilityStateEntry Support in one engine only. Firefox No Safari No Chrome 115+ Opera Edge 115+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android The VisibilityStateEntry interface exposes visibility changes to the document, from the moment the document becomes active. For example, this allows JavaScript code in the page to examine correlation between visibility changes and paint timing: function wasHiddenBeforeFirstContentfulPaint () const fcpEntry performance getEntriesByName "first-contentful-paint" )[ ]; const visibilityStateEntries performance getEntriesByType "visibility-state" ); return visibilityStateEntries some => startTime fcpEntry startTime && name === "hidden" ); Since hiding a page can cause throttling of rendering and other user-agent operations, it is common to use visibility changes as an indication that such throttling has occurred. However, other things could also cause throttling in different browsers, such as long periods of inactivity. Exposed =( Window )] interface VisibilityStateEntry PerformanceEntry readonly attribute DOMString name ; // shadows inherited name readonly attribute DOMString entryType ; // shadows inherited entryType readonly attribute DOMHighResTimeStamp startTime ; // shadows inherited startTime readonly attribute unsigned long duration ; // shadows inherited duration }; The VisibilityStateEntry has an associated DOMHighResTimeStamp timestamp The VisibilityStateEntry has an associated " visible " or hidden visibility state The name getter steps are to return this 's visibility state The entryType getter steps are to return visibility-state ". The startTime getter steps are to return this 's timestamp The duration getter steps are to return zero. 6.3 Inert subtrees See also inert for an explanation of the attribute of the same name. A node (in particular elements and text nodes) can be inert . When a node is inert Hit-testing must act as if the 'pointer-events' CSS property were set to 'none'. Text selection functionality must act as if the 'user-select' CSS property were set to 'none'. If it is editable , the node behaves as if it were non-editable. The user agent should ignore the node for the purposes of find-in-page Inert nodes generally cannot be focused, and user agents do not expose the inert nodes to accessibility APIs or assistive technologies. Inert nodes that are commands will become inoperable to users, in the manner described above. User agents may allow the user to override the restrictions on find-in-page and text selection, however. By default, a node is not inert 6.3.1 Modal dialogs and inert subtrees 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 flat tree descendants, must become inert subject can additionally become inert via the inert attribute, but only if specified on subject itself (i.e., subject escapes inertness of ancestors); subject 's flat tree descendants can become inert in a similar fashion. 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.2 The inert attribute Global_attributes/inert Support in all current engines. Firefox 112+ Safari 15.5+ Chrome 102+ Opera Edge 102+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android The inert attribute is a boolean attribute that indicates, by its presence, that the element and all its flat tree descendants which don't otherwise escape inertness (such as modal dialogs) are to be made inert by the user agent. An inert subtree should not contain any content or controls which are critical to understanding or using aspects of the page which are not in the inert state. Content in an inert subtree will not be perceivable by all users, or interactive. Authors should not specify elements as inert unless the content they represent are also visually obscured in some way. In most cases, authors should not specify the inert attribute on individual form controls. In these instances, the disabled attribute is probably more appropriate. The following example shows how to mark partially loaded content, visually obscured by a "loading" message, as inert. section aria-labelledby s1 h3 id s1 Population by City h3 div class container div class loading >< Loading... > div div inert form fieldset legend Date range legend div label for start Start label input type date id start div div label for end End label input type date id end div div button Apply button div fieldset form table caption From 20-- to 20-- caption thead tr th City th th State th th 20-- Population th th 20-- Population th th Percentage change th tr thead tbody tbody table div div section The "loading" overlay obscures the inert content, making it visually apparent that the inert content is not presently accessible. Notice that the heading and "loading" text are not descendants of the element with the inert attribute. This will ensure this text is accessible to all users, while the inert content cannot be interacted with by anyone. By default, there is no persistent visual indication of an element or its subtree being inert. Appropriate visual styles for such content is often context-dependent. For instance, an inert off-screen navigation panel would not require a default style, as its off-screen position visually obscures the content. Similarly, a modal dialog element's backdrop will serve as the means to visually obscure the inert content of the web page, rather than styling the inert content specifically. However, for many other situations authors are strongly encouraged to clearly mark what parts of their document are active and which are inert, to avoid user confusion. In particular, it is worth remembering that not all users can see all parts of a page at once; for example, users of screen readers, users on small devices or with magnifiers, and even users using particularly small windows might not be able to see the active part of a page and might get frustrated if inert sections are not obviously inert. 6.4 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.4.1 Data model For the purpose of tracking user activation, each Window has two relevant values: last activation timestamp , which is either a DOMHighResTimeStamp , positive infinity (indicating that has never been activated), or negative infinity (indicating that the activation has been consumed ). Initially positive infinity. last history-action activation timestamp , which is either a DOMHighResTimeStamp or positive infinity, initially 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. We then have the following boolean user activation states for Sticky activation When the current high resolution time given 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 given 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 History-action activation When the last history-action activation timestamp of is not equal to the last activation timestamp of , then is said to have history-action activation This is a special variant of user activation, used to allow access to certain session history APIs which, if used too frequently, would make it harder for the user to traverse back using browser UI . It starts with a false value, and becomes true whenever the user interacts with , but is reset to false through history-action activation consumption . This ensures such APIs cannot be used multiple times in a row without an intervening user activation. But unlike transient activation , there is no time limit within which such APIs must be used. The last activation timestamp and last history-action activation timestamp are retained even after the Document changes its fully active status (e.g., after navigating away from a Document , or navigating to a cached Document ). This means sticky activation state spans multiple navigations as long as the same Document gets reused. For the transient activation state, the original expiry time remains unchanged (i.e., the state still expires within the transient activation duration limit from the original activation triggering input event ). It is important to consider this when deciding whether to base certain things off sticky activation or transient activation 6.4.2 Processing model When a user interaction causes firing of an activation triggering input event in a Document document , the user agent must perform the following activation notification steps before dispatching the event: Assert document is fully active Let windows be « document 's relevant global object ». Extend windows with the active window of each of document 's ancestor navigables Extend windows with the active window of each of document 's descendant navigables , filtered to include only those navigables whose active document 's origin is same origin with document 's origin For each window in windows Set window 's last activation timestamp to the current high resolution time Notify the close watcher manager about user activation given window An activation triggering input event is any event whose isTrusted attribute is true and whose type is one of: keydown ", provided the key is neither the Esc key nor a shortcut key reserved by the user agent; mousedown "; pointerdown ", provided the event's pointerType is " mouse "; pointerup ", provided the event's pointerType is not " mouse "; or touchend ". Activation consuming APIs defined in this and other specifications can consume user activation by performing the following steps, given a Window If 's navigable is null, then return. Let top be 's navigable 's top-level traversable Let navigables be the inclusive descendant navigables of top 's active document Let windows be the list of Window objects constructed by taking the active window of each item in navigables 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. History-action activation-consuming APIs can consume history-action user activation by performing the following steps, given a Window If 's navigable is null, then return. Let top be 's navigable 's top-level traversable Let navigables be the inclusive descendant navigables of top 's active document Let windows be the list of Window objects constructed by taking the active window of each item in navigables For each window in windows , set window 's last history-action activation timestamp to window 's last activation timestamp 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.4.3 APIs gated by user activation APIs that are dependent on user activation are classified into different levels: 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. History-action activation-consuming APIs These APIs require the history-action activation state to be true, and they consume history-action user activation in each call to prevent multiple calls per user activation. 6.4.4 The UserActivation interface UserActivation Firefox No Safari 16.4+ Chrome 72+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android Each Window has an associated UserActivation , which is a UserActivation object. Upon creation of the Window object, its associated UserActivation must be set to a new UserActivation object created in the Window object's relevant realm Exposed Window interface UserActivation readonly attribute boolean hasBeenActive readonly attribute boolean isActive }; partial interface Navigator SameObject readonly attribute UserActivation userActivation }; navigator userActivation hasBeenActive Returns whether the window has sticky activation navigator userActivation isActive Returns whether the window has transient activation Navigator/userActivation Firefox No Safari 16.4+ Chrome 72+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android The userActivation getter steps are to return this 's relevant global object 's associated UserActivation UserActivation/hasBeenActive Firefox No Safari 16.4+ Chrome 72+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android The hasBeenActive getter steps are to return true if this 's relevant global object has sticky activation , and false otherwise. UserActivation/hasBeenActive Firefox No Safari 16.4+ Chrome 72+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android The isActive getter steps are to return true if this 's relevant global object has transient activation and false otherwise. 6.4.5 User agent automation For the purposes of user-agent automation and application testing, this specification defines the following extension command for the Web Driver specification. It is optional for a user agent to support the following extension command [WEBDRIVER] HTTP Method URI Template POST /session/{ session id }/window/consume-user-activation The remote end steps are: Let window be the current browsing context 's active window Let consume be true if window has transient activation otherwise false. If consume is true, then consume user activation of window Return success with data consume 6.5 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 Chrome Android WebView Android 4.4+ 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.1 The ToggleEvent interface ToggleEvent/ToggleEvent Support in all current engines. Firefox 🔰 114+ Safari 17+ Chrome 114+ Opera Edge 114+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android ToggleEvent Support in all current engines. Firefox 🔰 114+ Safari 17+ Chrome 114+ Opera Edge 114+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android Exposed Window interface ToggleEvent Event constructor DOMString type optional ToggleEventInit eventInitDict = {}); readonly attribute DOMString oldState readonly attribute DOMString newState readonly attribute Element source }; dictionary ToggleEventInit EventInit DOMString oldState = ""; DOMString newState = ""; Element source null }; event oldState Set to " closed " when transitioning from closed to open, or set to open " when transitioning from open to closed. event newState Set to " open " when transitioning from closed to open, or set to " closed " when transitioning from open to closed. event source Set to the element which initiated the toggle, which can be set up with the popovertarget and commandfor attributes. If there is no source element, then it is set to null. ToggleEvent/oldState Support in all current engines. Firefox 🔰 114+ Safari 17+ Chrome 114+ Opera Edge 114+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android ToggleEvent/newState Support in all current engines. Firefox 🔰 114+ Safari 17+ Chrome 114+ Opera Edge 114+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android The oldState and newState attributes must return the values they are initialized to. The source getter steps are to return the result of retargeting source against this 's currentTarget DOM standard issue #1328 tracks how to better standardize associated event data in a way which makes sense on Events. Currently an event attribute initialized to a value cannot also have a getter, and so an internal slot (or map of additional fields) is required to properly specify this. toggle task tracker is a struct which has: task task which fires a ToggleEvent old state A string which represents the task 's event's value for the oldState attribute. 6.5.2 The CommandEvent interface Exposed Window interface CommandEvent Event constructor DOMString type optional CommandEventInit eventInitDict = {}); readonly attribute Element source readonly attribute DOMString command }; dictionary CommandEventInit EventInit Element source null DOMString command = ""; }; event command Returns what action the element can take. event source Returns the Element that was interacted with in order to cause this event. The command attribute must return the value it was initialized to. The source getter steps are to return the result of retargeting source against this 's currentTarget DOM standard issue #1328 tracks how to better standardize associated event data in a way which makes sense on Events. Currently an event attribute initialized to a value cannot also have a getter, and so an internal slot (or map of additional fields) is required to properly specify this. 6.6 Focus 6.6.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.6.2 Data model top-level traversable has system focus when it can receive keyboard input channeled from the operating system, possibly targeted at one of its active document 's descendant navigables top-level traversable has user attention when its system visibility state is " visible ", and it either has system focus or user agent widgets directly related to it can receive keyboard input channeled from the operating system. User attention is lost when a browser window loses focus, whereas system focus might also be lost to other system widgets in the browser window such as a location bar. Document is a fully active descendant of a top-level traversable with user attention when is fully active and 's node navigable 's top-level traversable has user attention 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 inert the element is either being rendered delegating its rendering to its children , or being used as relevant canvas fallback content The element itself. iframe dialog , sometimeshref=""> (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 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 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 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. navigable container (e.g. an iframe ) is a focusable area , but key events routed to a navigable container get immediately routed to its content navigable 's active document . Similarly, in sequential focus navigation a navigable container essentially acts merely as a placeholder for its content navigable '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. Even if a document is not fully active and not shown to the user, it can still have a focused area of the document . If a document's fully active state changes, its focused area of the document will stay the same. The currently focused area of a top-level traversable traversable is the focusable area -or-null returned by this algorithm: If traversable does not have system focus , then return null. Let candidate be traversable 's active document While candidate 's focused area is a navigable container with a non-null content navigable : set candidate to the active document of that navigable container 's content navigable 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 traversable traversable is the focus chain of the currently focused area of traversable , if traversable 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 traversable . When an element is the DOM anchor of a focusable area of the currently focused area of a top-level traversable , 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 node navigable 's parent is non-null, then set currentObject to currentObject 's node navigable 's parent Otherwise, break Return output The chain starts with subject and (if subject is or can be the currently focused area of a top-level traversable ) continues up the focus hierarchy up to the Document of the top-level traversable 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 , a slot , or an element which is the popover trigger of an element in the popover showing state 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 If element is in the popover showing state and has a popover trigger set, then return element 's popover trigger 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.6.3 The tabindex attribute Global_attributes/tabindex Support in all current engines. Firefox 1.5+ Safari 4+ Chrome 1+ Opera Edge 79+ Edge (Legacy) 12+ Internet Explorer Yes Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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 Navigable 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 less than or equal to 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 HTMLElement/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 Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 12.1+ The tabIndex getter steps are: Let attribute be this 's tabindex attribute. If attribute is not null: Let parsedValue be the result of integer parsing attribute 's value If parsedValue is not an error and is within the long range, then return parsedValue Return 0 if this 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 ; otherwise −1. The varying default value based on element type is a historical artifact. 6.6.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 navigable , given an optional string focus trigger (default " other "), 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 navigable Return the navigable 's active document If focus target is a navigable container with a non-null content navigable Return the navigable container 's content navigable 's active document If focus target is a shadow host whose shadow root 's delegates focus is true Let focusedElement be the currently focused area of a top-level traversable 's DOM anchor If focus target is a shadow-including inclusive ancestor of focusedElement , then return focusedElement Return the focus delegate for focus target given focus trigger 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 focus delegate for a focusTarget , given an optional string focusTrigger (default " other "), is given by the following steps: If focusTarget is a shadow host and its shadow root 's delegates focus is false, then return null. Let whereToLook be focusTarget If whereToLook is a shadow host , then set whereToLook to whereToLook 's shadow root Let autofocusDelegate be the autofocus delegate for whereToLook given focusTrigger If autofocusDelegate is not null, then return autofocusDelegate For each descendant of whereToLook 's descendants , in tree order Let focusableArea be null. If focusTarget is a dialog element and descendant is sequentially focusable , then set focusableArea to descendant Otherwise, if focusTarget is not a dialog and descendant is a focusable area , set focusableArea to descendant Otherwise, set focusableArea to the result of getting the focusable area for descendant given focusTrigger This step can end up recursing, i.e., the get the focusable area steps might return the focus delegate of descendant If focusableArea is not null, then return focusableArea It's important that we are not looking at the shadow-including descendants here, but instead only at the descendants Shadow hosts are instead handled by the recursive case mentioned above. Return null. The above algorithm essentially returns the first suitable focusable area where the path between its DOM anchor and focusTarget delegates focus at any shadow tree boundaries. The autofocus delegate for a focus target given a focus trigger is given by the following steps: For each descendant descendant of focus target , in tree order If descendant does not have an autofocus content attribute, then continue Let focusable area be descendant , if descendant is a focusable area ; otherwise let focusable area be the result of getting the focusable area for descendant given focus trigger If focusable area is null, then continue If focusable area is not click focusable and focus trigger is " click ", then continue Return focusable area 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 navigable , 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 navigable container with non-null content navigable , then set new focus target to the content navigable '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 traversable , then return. Let old chain be the current focus chain of the top-level traversable 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 navigable 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 a shadow host whose shadow root 's delegates focus is true, and old focus target 's shadow root is a shadow-including inclusive ancestor of the currently focused area of a top-level traversable 's DOM anchor , then set old focus target to that currently focused area of a top-level traversable 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 traversable , 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 traversable , then let old focus target be that currently focused area of a top-level traversable Let old chain be the current focus chain of the top-level traversable 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 node navigable 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 node navigable , and run the focus update steps given old chain , an empty list, and null. The unfocusing steps do not always result in the focus changing, even when applied to the currently focused area of a top-level traversable . For example, if the currently focused area of a top-level traversable is a viewport , then it will usually keep its focus regardless until another focusable area is explicitly focused with the focusing steps 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: Set entry 's user validity to true. 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 , and the focused area of the document is not entry Set document 's relevant global object 's navigation API 's focus changed during ongoing to true. 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 traversable , the user agent must run the following steps: Let target area be the currently focused area of the top-level traversable Assert target area is not null, since key events are only routed to top-level traversables that have system focus . Therefore, target area is a focusable area Let target node be target area 's DOM anchor 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: 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 node navigable 's top-level traversable does not have system focus , then return false. Let candidate be target 's node navigable 's top-level traversable 's active document While true: If candidate is target , then return true. If the focused area of candidate is a navigable container with a non-null content navigable , then set candidate to the active document of that navigable container 's content navigable Otherwise, return false. 6.6.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 sequential focus direction is one of two possible values: " forward ", or " backward ". They are used in the below algorithms to describe the direction in which sequential focus travels at the user's request. selection mechanism is one of two possible values: " DOM ", or sequential ". They are used to describe how the sequential navigation search algorithm finds the focusable area it returns. When the user requests that focus move from the currently focused area of a top-level traversable 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 traversable 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 traversable , if the user requested to move focus sequentially from there, or else the top-level traversable itself, if the user instead requested to move focus from outside the top-level traversable 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 starting point is a navigable 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 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 a top-level traversable , or a focusable area in the top-level traversable , 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 traversable itself. Otherwise, starting point is a focusable area in a child navigable . Set starting point to that child navigable 's parent and return to the step labeled loop The sequential navigation search algorithm , given a focusable area starting point sequential focus direction direction , and selection mechanism selection mechanism , consists of the following steps. They return a focusable area -or-null. 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 navigable 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 suitable sequentially focusable area , that appears nearest after starting point in starting point 's Document , in shadow-including tree order , if any; or else null In this case, starting point does not necessarily belong to its Document 's sequential focus navigation order , so we'll select the suitable item from that list that comes after starting point in shadow-including tree order Let candidate be the suitable sequentially focusable area , that appears nearest before starting point in starting point 's Document , in shadow-including tree order , if any; or else null selection mechanism is " sequential Let candidate be the first suitable sequentially focusable area after starting point , in starting point 's Document 's sequential focus navigation order , if any; or else null Let candidate be the last suitable sequentially focusable area before starting point , in starting point 's Document 's sequential focus navigation order , if any; or else null suitable sequentially focusable area is a focusable area whose DOM anchor is not inert and is sequentially focusable If candidate is a navigable container with a non-null content navigable , then: Let recursive candidate be the result of running the sequential navigation search algorithm with candidate 's content navigable direction , and " sequential ". If recursive candidate is null, then return the result of running the sequential navigation search algorithm with candidate direction , and selection mechanism Otherwise, set candidate to recursive candidate Return candidate 6.6.6 Focus management APIs dictionary FocusOptions boolean preventScroll false boolean focusVisible }; documentOrShadowRoot activeElement Document/activeElement Support in all current engines. Firefox 3+ Safari 4+ Chrome 2+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 6+ Firefox Android Safari iOS Chrome Android WebView Android 37+ Samsung Internet Opera Android 12.1+ ShadowRoot/activeElement Support in all current engines. Firefox 63+ Safari 10+ Chrome 53+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android Returns the deepest element in documentOrShadowRoot 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 navigable is focused, its container is focused within its parent 's active document . 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 2+ Opera Edge 79+ Edge (Legacy) 12+ Internet Explorer 5.5+ Firefox Android Safari iOS Chrome Android WebView Android 37+ Samsung Internet Opera Android Returns true if key events are being routed through or to document ; otherwise, returns false. Roughly speaking, this corresponds to document , or a document nested inside document , 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 Safari iOS Chrome Android 18+ WebView Android Samsung Internet Opera Android 12.1+ Moves the focus to window 's navigable , if any. element focus () HTMLElement/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 Safari iOS 1+ Chrome Android WebView Android Samsung Internet Opera Android 10.1+ element focus ({ preventScroll focusVisible }) Moves the focus to element If element is a navigable container , moves the focus to its content navigable instead. By default, this method also scrolls element into view. Providing the preventScroll option and setting it to true prevents this behavior. By default, user agents use implementation-defined heuristics to determine whether to indicate focus via a focus ring. Providing the focusVisible option and setting it to true will ensure the focus ring is always visible. element blur () HTMLElement/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 Safari iOS 1+ Chrome Android WebView Android Samsung Internet 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 DocumentOrShadowRoot activeElement getter steps are: Let candidate be this 's node document 's focused area 's DOM anchor Set candidate to the result of retargeting candidate against this If candidate 's root is not this , 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 Document hasFocus() method steps are to return the result of running the has focus steps given this The Window focus() method steps are: Let current be this 's navigable If current is null, then return. If the allow focus steps given current 's active document return false, then return. Run the focusing steps with current If current is a top-level traversable , 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 Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 12.1+ The Window blur() method steps are to do nothing. Historically, the focus() and blur() methods actually affected the system-level focus of the system widget (e.g., tab or window) that contained the navigable , but hostile sites widely abuse this behavior to the user's detriment. The HTMLOrSVGElement focus( options method steps are: If the allow focus steps given this 's node document return false, then return. Run the focusing steps for this If options [" focusVisible "] is true, or does not exist but in an implementation-defined way the user agent determines it would be best to do so, then indicate focus If options [" preventScroll "] is false, then scroll a target into view given this , " auto ", " center ", and " center ". The HTMLOrSVGElement blur() method steps are: The user agent should run the unfocusing steps given this User agents may instead selectively or uniformly do nothing, 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. The allow focus steps , given a Document object target , are: If target is allowed to use the " focus-without-user-activation " feature, then return true. If target 's relevant global object has transient activation , then return true. Return false. 6.6.7 The autofocus attribute The autofocus content attribute allows the author to indicate that an element is to be focused as soon as the page is loaded, allowing the user to just start typing without having to manually focus the main element. When the autofocus attribute is specified on an element inside dialog elements or HTML elements whose popover attribute is set, then it will be focused when the dialog or popover becomes shown. The autofocus attribute is a boolean attribute To find the nearest ancestor autofocus scoping root element given an Element element If element is a dialog element, then return element If element 's popover attribute is not in the No Popover state, then return element Let ancestor be element While ancestor has a parent element Set ancestor to ancestor 's parent element If ancestor is a dialog element, then return ancestor If ancestor 's popover attribute is not in the No Popover state, then return ancestor Return ancestor 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 is not fully active , then return. If target 's active sandboxing flag set has the sandboxed automatic features browsing context flag , then return. If the allow focus steps given target return false, then return. Let topDocument be target 's node navigable 's top-level traversable 's active document 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 node navigable 's top-level traversable is not the same as topDocument 's node navigable then remove element from candidates and continue If doc 's script-blocking style sheet set is not empty , 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 the active document of doc 's inclusive ancestor navigables 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. 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.7 Assigning keyboard shortcuts 6.7.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 possible key. input type button value Collect onclick "collect()" accesskey "C 1" id To tell the user what the shortcut key is, the author has 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.7.2 The accesskey attribute Global_attributes/accesskey Support in all current engines. Firefox 1+ Safari 4+ Chrome 1+ Opera Edge 79+ Edge (Legacy) 12+ Internet Explorer Yes Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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.7.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/accessKeyLabel Firefox 8+ Safari 14+ Chrome No Opera Edge No Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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.8 Editing 6.8.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 Safari iOS 1+ Chrome Android WebView Android Samsung Internet 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 4+ Chrome 1+ Opera 9+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 5.5+ Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android The contenteditable content attribute is an enumerated attribute with the following keywords and states: Keyword State Brief description true True The element is editable. false False The element is not editable. plaintext-only Plaintext-Only Only the element's raw text content is editable; rich formatting is disabled. The attribute's missing value default and invalid value default are both the Inherit state. The inherit state indicates that the element is editable (or not) based on the parent element's state. The attribute's empty value default is the True state. 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 ", " plaintext-only ", " 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 Safari iOS 1+ Chrome Android WebView Android Samsung Internet 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, " plaintext-only " if the content attribute is set to the Plaintext-Only 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 " plaintext-only ", then the content attribute must be set to the string " plaintext-only ", 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.8.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 Safari iOS Chrome Android WebView Android Samsung Internet 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.8.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.8.4 Editing APIs An editing host is either an HTML element with its contenteditable attribute in the true state or plaintext-only 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.8.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 Samsung Internet Opera Android 37+ The spellcheck attribute is an enumerated attribute with the following keywords and states: Keyword State Brief description true True Spelling and grammar will be checked. false False Spelling and grammar will not be checked. The attribute's missing value default and invalid value default are both the Default state. 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 attribute's empty value default is the True state. 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 true ", otherwise it must be set to " false ". User agents should 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.8.6 Writing suggestions User agents offer writing suggestions as users type into editable regions, either in form controls (e.g., the textarea element) or in elements in an editing host The writingsuggestions content attribute is an enumerated attribute with the following keywords and states: Keyword State Brief description true True Writing suggestions should be offered on this element. false False Writing suggestions should not be offered on this element. The attribute's missing value default is the Default state. The default state indicates that the element is to act according to a default behavior, possibly based on the parent element's own writingsuggestions state, as defined below. The attribute's invalid value default and empty value default are both the True state. element writingSuggestions [ = value Returns " true " if the user agent is to offer writing suggestions under the scope of the element; otherwise, returns " false ". Can be set, to override the default and set the writingsuggestions content attribute. The computed writing suggestions value of a given element is determined by running the following steps: If element 's writingsuggestions content attribute is in the False state, return " false ". If element 's writingsuggestions content attribute is in the Default state, element has a parent element, and the computed writing suggestions value of element 's parent element is " false ", then return false ". Return " true ". The writingSuggestions getter steps are: Return this 's computed writing suggestions value The writingSuggestions IDL attribute is not affected by user preferences that override the writingsuggestions content attribute, and therefore might not reflect the actual writing suggestions state. User agents should only offer suggestions within an element's scope if the result of running the following algorithm given element returns true: If the user has disabled writing suggestions, then return false. If none of the following conditions are true: element is an input element whose type attribute is in either the Text Telephone URL or Email state and is mutable element is a textarea element that is mutable ; or element is an editing host or is editable then return false. If element has an inclusive ancestor with a writingsuggestions content attribute that's not in the Default and the nearest such ancestor's writingsuggestions content attribute is in the False state, then return false. Otherwise, return true. This specification does not define the user interface for writing suggestions. A user agent could offer on-demand suggestions, continuous suggestions as the user types, inline suggestions, autofill-like suggestions in a popup, or could use other interfaces. 6.8.7 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-and-autocorrect 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 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 111+ Safari No Chrome 43+ Opera Edge 79+ Edge (Legacy) Internet Explorer Firefox Android Safari iOS 5+ Chrome Android WebView Android 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 attribute's missing value default is the Default state, and its invalid value default is the Sentences 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-and-autocorrect 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 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.8.8 Autocorrection Some methods of entering text assist users by automatically correcting misspelled words while typing, a process also known as autocorrection. User agents can support autocorrection 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 ). Autocorrection may be accompanied by user interfaces indicating that text is about to be autocorrected or has been autocorrected, and is commonly performed when inserting punctuation characters, spaces, or new paragraphs after misspelled words. The autocorrect attribute allows authors to control such behavior. The autocorrect attribute can be used on an editing host to control autocorrection behavior for the hosted editable region, on an input or textarea element to control the behavior when inserting text into that element, or on form element to control the default behavior for all autocapitalize-and-autocorrect inheriting elements associated with the form element. The autocorrect attribute never causes autocorrection 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 autocorrection state algorithm below.) The autocorrect attribute is an enumerated attribute with the following keywords and states: Keyword State Brief description on On The user agent is permitted to automatically correct spelling errors while the user types. Whether spelling is automatically corrected while typing left is for the user agent to decide, and may depend on the element as well as the user's preferences. off Off The user agent is not allowed to automatically correct spelling while the user types. The attribute's invalid value default missing value default , and empty value default are all the On state. The autocorrect getter steps are: return true if the element's used autocorrection state is On and false if the element's used autocorrection state is Off . The setter steps are: if the given value is true, then the element's autocorrect attribute must be set to " on "; otherwise it must be set to " off ". To compute the used autocorrection state of an element element , run these steps: If element is an input element whose type attribute is in one of the URL Email , or Password states, then return Off If the autocorrect content attribute is present on element , then return the state of the attribute. If element is an autocapitalize-and-autocorrect inheriting element and has a non-null form owner , then return the state of element 's form owner 's autocorrect attribute. Return On element autocorrect Returns the autocorrection behavior of the element. Note that for autocapitalize-and-autocorrect inheriting elements that inherit their state from a form element, this will return the autocorrection behavior of the form element, but for an element in an editable region, this will not return the autocorrection behavior of the editing host (unless this element is, in fact, the editing host ). element autocorrect value Updates the autocorrect content attribute (and thereby changes the autocorrection behavior of the element). The input element in the following example would not allow autocorrection, since it does not have an autocorrect content attribute and therefore inherits from the form element, which has an attribute of " off ". However, the textarea element would allow autocorrection, since it has an autocorrect content attribute with a value of " on ". form autocorrect "off" input type "search" textarea autocorrect "on" > textarea form 6.8.9 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 95+ Safari No Chrome 66+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android 79+ Safari iOS 12.2+ Chrome Android WebView Android Samsung Internet Opera Android 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. HTMLElement/inputMode Support in all current engines. Firefox 95+ Safari 12.1+ Chrome 66+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android 79+ Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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.8.10 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 94+ Safari 13.1+ Chrome 77+ Opera 66+ Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet 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 94+ Safari 13.1+ Chrome 77+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 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.9 Find-in-page 6.9.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 the 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.9.2 Interaction with details and hidden=until-found When find-in-page begins searching for matches, all details elements in the page which do not have their open attribute set should have the skipped contents of their second slot become accessible, without modifying the open attribute, in order to make find-in-page able to search through it. Similarly, all HTML elements with the hidden attribute in the Hidden Until Found state should have their skipped contents become accessible without modifying the hidden attribute in order to make find-in-page able to search through them. After find-in-page finishes searching for matches, the details elements and the elements with the hidden attribute in the Hidden Until Found state should have their contents become skipped again. This entire process must happen synchronously (and so is not observable to users or to author code). [CSSCONTAIN] When find-in-page chooses a new active match , perform the following steps: Let node be the first node in the active match Queue a global task on the user interaction task source given node 's relevant global object to run the ancestor revealing algorithm on node When find-in-page auto-expands a details element like this, it will fire a toggle event. As with the separate scroll event that find-in-page fires, this event could be used by the page to discover what the user is typing into the find-in-page dialog. If the page creates a tiny scrollable area with the current search term and every possible next character the user could type separated by a gap, and observes which one the browser scrolls to, it can add that character to the search term and update the scrollable area to incrementally build the search term. By wrapping each possible next match in a closed details element, the page could listen to toggle events instead of scroll events. This attack could be addressed for both events by not acting on every character the user types into the find-in-page dialog. 6.9.3 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.10 Close requests and close watchers 6.10.1 Close requests In an implementation-defined (and likely device-specific) manner, a user can send close request to the user agent. This indicates that the user wishes to close something that is currently being shown on the screen, such as a popover, menu, dialog, picker, or display mode. Some example close requests are: The Esc key on desktop platforms. The back button or gesture on certain mobile platforms such as Android. Any assistive technology's dismiss gesture, such as iOS VoiceOver's two-finger scrub "z" gesture. A game controller's canonical "back" button, such as the circle button on a DualShock gamepad. Whenever the user agent receives a potential close request targeted at a Document document , it must queue a global task on the user interaction task source given document 's relevant global object to perform the following close request steps If document 's fullscreen element is not null, then: Fully exit fullscreen given document 's node navigable 's top-level traversable 's active document Return. This does not fire any relevant event, such as keydown ; it only causes fullscreenchange to be eventually fired. Optionally, skip to the step labeled alternative processing For example, if the user agent detects user frustration at repeated close request interception by the current web page, it might take this path. Fire any relevant events, per UI Events or other relevant specifications. [UIEVENTS] An example of a relevant event in the UI Events model would be the keydown event that UI Events suggests firing when the user presses the Esc key on their keyboard. On most platforms with keyboards, this is treated as a close request , and so would trigger these close request steps An example of relevant events that are outside of the model given in UI Events would be assistive technology synthesizing an Esc keydown event when the user sends a close request by using a dismiss gesture. Let event be null if no such events are fired, or the Event object representing one of the fired events otherwise. If multiple events are fired, which one is chosen is implementation-defined If event is not null, and its canceled flag is set, then return. If document is not fully active , then return. This step is necessary because, if event is not null, then an event listener might have caused document to no longer be fully active Let closedSomething be the result of processing close watchers on document 's relevant global object If closedSomething is true, then return. Alternative processing : Otherwise, there was nothing watching for a close request . The user agent may instead interpret this interaction as some other action, instead of interpreting it as a close request. On platforms where pressing the Esc key is interpreted as a close request , the user agent must interpret the key being pressed down as the close request, instead of the key being released. Thus, in the above algorithm, the "relevant events" that are fired must be the single keydown event. On platforms where Esc is the close request , the user agent will first fire an appropriately-initialized keydown event. If the web developer cancels the event by calling preventDefault() , then nothing further happens. But if the event fires without being canceled, then the user agent proceeds to process close watchers On platforms where a back button is a potential close request , no event is involved, so when the back button is pressed, the user agent proceeds directly to process close watchers . If there is an active close watcher , then that will get triggered. If there is not, then the user agent can interpret the back button press in another way, for example as a request to traverse the history by a delta of −1. 6.10.2 Close watcher infrastructure Each Window has a close watcher manager , which is a struct with the following items Groups , a list of lists of close watchers , initially empty. Allowed number of groups , a number, initially 1. Next user interaction allows a new group a boolean, initially true. Most of the complexity of the close watcher manager comes from anti-abuse protections designed to prevent developers from disabling users' history traversal abilities, for platforms where a close request 's fallback action is the main mechanism of history traversal. In particular: The grouping of close watchers is designed so that if multiple close watchers are created without history-action activation , they are grouped together, so that a user-triggered close request will close all of the close watchers in a group. This ensures that web developers can't intercept an unlimited number of close requests by creating close watchers; instead they can create a number equal to at most 1 + the number of times the user activates the page The next user interaction allows a new group boolean encourages web developers to create close watchers in a way that is tied to individual user activations . Without it, each user activation would increase the allowed number of groups , even if the web developer isn't "using" those user activations to create close watchers. In short: Allowed: user interaction; create a close watcher in its own group; user interaction; create a close watcher in a second independent group. Disallowed: user interaction; user interaction; create a close watcher in its own group; create a close watcher in a second independent group. Allowed: user interaction; user interaction; create a close watcher in its own group; create a close watcher grouped with the previous one. This protection is not important for upholding our desired invariant of creating at most (1 + the number of times the user activates the page groups. A determined abuser will just create one close watcher per user interaction, "banking" them for future abuse. But this system causes more predictable behavior for the normal case, and encourages non-abusive developers to create close watchers directly in response to user interactions. To notify the close watcher manager about user activation given a Window window Let manager be window 's close watcher manager If manager 's next user interaction allows a new group is true, then increment manager 's allowed number of groups Set manager 's next user interaction allows a new group to false. close watcher is a struct with the following items window , a Window cancel action , an algorithm accepting a boolean argument and returning a boolean. The argument indicates whether or not the cancel action algorithm can prevent the close request from proceeding via the algorithm's return value. If the boolean argument is true, then the algorithm can return either true to indicate that the caller will proceed to the close action , or false to indicate that the caller will bail out. If the argument is false, then the return value is always false. This algorithm can never throw an exception. close action , an algorithm accepting no arguments and returning nothing. This algorithm can never throw an exception. An is running cancel action boolean. get enabled state , an algorithm accepting no arguments and returning a boolean. This algorithm can never throw an exception. close watcher closeWatcher is active if closeWatcher 's window 's close watcher manager contains any list which contains closeWatcher To establish a close watcher given a Window window , a list of steps cancelAction , a list of steps closeAction and an algorithm that returns a boolean getEnabledState Assert window 's associated Document is fully active Let closeWatcher be a new close watcher , with window window cancel action cancelAction close action closeAction is running cancel action false get enabled state getEnabledState Let manager be window 's close watcher manager If manager 's groups 's size is less than manager 's allowed number of groups , then append closeWatcher » to manager 's groups Otherwise: Assert manager 's groups 's size is at least 1 in this branch, since manager 's allowed number of groups is always at least 1. Append closeWatcher to manager 's groups 's last item Set manager 's next user interaction allows a new group to true. Return closeWatcher To request to close close watcher closeWatcher with boolean requireHistoryActionActivation If closeWatcher is not active , then return true. If the result of running closeWatcher 's get enabled state is false, then return true. If closeWatcher 's is running cancel action is true, then return true. Let window be closeWatcher 's window If window 's associated Document is not fully active , then return true. Let canPreventClose be true if requireHistoryActionActivation is false, or if window 's close watcher manager 's groups 's size is less than window 's close watcher manager 's allowed number of groups , and window has history-action activation ; otherwise false. Set closeWatcher 's is running cancel action to true. Let shouldContinue be the result of running closeWatcher 's cancel action given canPreventClose Set closeWatcher 's is running cancel action to false. If shouldContinue is false, then: Assert canPreventClose is true. Consume history-action user activation given window Return false. Note that since these substeps consume history-action user activation requesting to close close watcher twice without any intervening user activation will result in canPreventClose being false the second time. Close closeWatcher Return true. To close close watcher closeWatcher If closeWatcher is not active , then return. If the result of running closeWatcher 's get enabled state is false, then return. If closeWatcher 's window 's associated Document is not fully active , then return. Destroy closeWatcher Run closeWatcher 's close action To destroy close watcher closeWatcher Let manager be closeWatcher 's window 's close watcher manager For each group of manager 's groups remove closeWatcher from group Remove any item from manager 's groups that is empty To process close watchers given a Window window Let processedACloseWatcher be false. If window 's close watcher manager 's groups is not empty: Let group be the last item in window 's close watcher manager 's groups For each closeWatcher of group in reverse order: If the result of running closeWatcher 's get enabled state is true, set processedACloseWatcher to true. Let shouldProceed be the result of requesting to close closeWatcher with true. If shouldProceed is false, then break If window 's close watcher manager 's allowed number of groups is greater than 1, decrement it by 1. Return processedACloseWatcher 6.10.3 The CloseWatcher interface Exposed Window interface CloseWatcher EventTarget constructor optional CloseWatcherOptions options = {}); undefined requestClose (); undefined close (); undefined destroy (); attribute EventHandler oncancel attribute EventHandler onclose }; dictionary CloseWatcherOptions AbortSignal signal }; watcher = new CloseWatcher () watcher = new CloseWatcher ({ signal }) Creates a new CloseWatcher instance. If the signal option is provided, then watcher can be destroyed (as if by watcher.destroy() ) by aborting the given AbortSignal If any close watcher is already active, and the Window does not have history-action activation , then the resulting CloseWatcher will be closed together with that already-active close watcher in response to any close request . (This already-active close watcher does not necessarily have to be a CloseWatcher object; it could be a modal dialog element, or a popover generated by an element with the popover attribute.) watcher requestClose () Acts as if a close request was sent targeting watcher , by first firing a cancel event, and if that event is not canceled with preventDefault() , proceeding to fire a close event before deactivating the close watcher as if watcher.destroy() was called. This is a helper utility that can be used to consolidate cancelation and closing logic into the cancel and close event handlers, by having all non- close request closing affordances call this method. watcher close () Immediately fires the close event, and then deactivates the close watcher as if watcher.destroy() was called. This is a helper utility that can be used trigger the closing logic into the close event handler, skipping any logic in the cancel event handler. watcher destroy () Deactivates watcher , so that it will no longer receive close events and so that new independent CloseWatcher instances can be constructed. This is intended to be called if the relevant UI element is torn down in some other way than being closed. Each CloseWatcher instance has an internal close watcher , which is a close watcher The new CloseWatcher( options constructor steps are: If this 's relevant global object 's associated Document is not fully active , then throw an InvalidStateError DOMException Let closeWatcher be the result of establishing a close watcher given this 's relevant global object , with: cancelAction given canPreventClose being to return the result of firing an event named cancel at this , with the cancelable attribute initialized to canPreventClose closeAction being to fire an event named close at this getEnabledState being to return true. If options [" signal "] exists , then: If options [" signal "] is aborted , then destroy closeWatcher Add the following steps to options [" signal "]: Destroy closeWatcher Set this 's internal close watcher to closeWatcher The requestClose() method steps are to request to close this 's internal close watcher with false. The close() method steps are to close this 's internal close watcher The destroy() method steps are to destroy this 's internal close watcher 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 CloseWatcher interface: Event handler Event handler event type oncancel cancel onclose close If one wanted to implement a custom picker control, which closed itself on a user-provided close request as well as when a close button is pressed, the following code shows how one would use the CloseWatcher API to process close requests: const watcher new CloseWatcher (); const picker setUpAndShowPickerDOMElement (); let chosenValue null watcher onclose () => chosenValue picker querySelector 'input' ). value picker remove (); }; picker querySelector '.close-button' ). onclick () => watcher requestClose (); Note how the logic to gather the chosen value is centralized in the CloseWatcher object's close event handler, with the click event handler for the close button delegating to that logic by calling requestClose() The cancel event on CloseWatcher objects can be used to prevent the close event from firing, and the CloseWatcher from being destroying. A typical use case is as follows: watcher oncancel async => if hasUnsavedData && cancelable preventDefault (); const userReallyWantsToClose await askForConfirmation "Are you sure you want to close?" ); if userReallyWantsToClose hasUnsavedData false watcher close (); }; For abuse prevention purposes, this event is only cancelable if the page has history-action activation , which will be lost after any given close request . This ensures that if the user sends a close request twice in a row without any intervening user activation, the request definitely succeeds; the second request ignores any cancel event handler's attempt to call preventDefault() and proceeds to close the CloseWatcher Combined, the above two examples show how requestClose() and close() differ. Because we used requestClose() in the click event handler for the close button, clicking that button will trigger the CloseWatcher 's cancel event, and thus potentially ask the user for confirmation if there is unsaved data. If we had used close() , then this check would be skipped. Sometimes that is appropriate, but usually requestClose() is the better option for user-triggered close requests. In addition to the user activation restrictions for cancel events, there is a more subtle form of user activation gating for CloseWatcher construction. If one creates more than one CloseWatcher without user activation, then the newly-created one will get grouped together with the most-recently-created close watcher , so that a single close request will close them both: window onload () => // This will work as normal: it is the first close watcher created without user activation. new CloseWatcher ()). onclose () => /* ... */ }; }; button1 onclick () => // This will work as normal: the button click counts as user activation. new CloseWatcher ()). onclose () => /* ... */ }; }; button2 onclick () => // These will be grouped together, and both will close in response to a single close request. new CloseWatcher ()). onclose () => /* ... */ }; new CloseWatcher ()). onclose () => /* ... */ }; }; This means that calling destroy() close() , or requestClose() properly is important. Doing so is the only way to get back the "free" ungrouped close watcher slot. Such close watchers created without user activation are useful for cases like session inactivity timeout dialogs or urgent notifications of server-triggered events, which are not generated in response to user activation. 6.11 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.11.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.11.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.11.3 The DataTransfer interface DataTransfer Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 3+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 8+ Firefox Android Safari iOS Chrome Android WebView Android 37+ Samsung Internet Opera Android 12+ DataTransfer objects are used to expose the drag data store that underlies a drag-and-drop operation. 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 59+ Opera Edge 79+ Edge (Legacy) 17+ Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android 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 4+ Chrome 3+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 8+ Firefox Android Safari iOS Chrome Android WebView Android 37+ Samsung Internet Opera Android 12.1+ 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 4+ Chrome 3+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 8+ Firefox Android Safari iOS Chrome Android WebView Android 37+ Samsung Internet Opera Android 12.1+ 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 3+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android 52+ Safari iOS Chrome Android WebView Android 37+ Samsung Internet Opera Android 12+ Returns a DataTransferItemList object, with the drag data. dataTransfer setDragImage element DataTransfer/setDragImage Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 3+ Opera 12.1+ Edge 79+ Edge (Legacy) 18 Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android 37+ Samsung Internet Opera Android 12.1+ 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 4+ Chrome 3+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android Safari iOS Chrome Android WebView Android 37+ Samsung Internet Opera Android 12.1+ 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 4+ Chrome 3+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 8+ Firefox Android Safari iOS Chrome Android WebView Android 37+ Samsung Internet Opera Android 12.1+ 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 3.5+ Safari 5+ Chrome 3+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 8+ Firefox Android Safari iOS 5+ Chrome Android WebView Android 37+ Samsung Internet Opera Android 12+ Adds the specified data. dataTransfer clearData ([ format ]) DataTransfer/clearData Support in all current engines. Firefox 3.5+ Safari 4+ Chrome 3+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 8+ Firefox Android Safari iOS Chrome Android WebView Android 37+ Samsung Internet Opera Android 12.1+ 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 4+ Chrome 3+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android Safari iOS Chrome Android WebView Android 37+ Samsung Internet Opera Android 12.1+ 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 the 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( image 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 image is an img element, then set the drag data store bitmap to the element's image (at its natural 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( format 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. Set format to format 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.11.3.1 The DataTransferItemList interface DataTransferItemList Support in all current engines. Firefox 50+ Safari 6+ Chrome 13+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 14+ Each DataTransfer object is associated with a DataTransferItemList object. 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 Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 14+ 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 Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 14+ 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 Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 14+ 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 Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 14+ 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 indices of 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( index method must run these steps: If the DataTransferItemList object is not in the read/write mode , throw an InvalidStateError DOMException If the drag data store does not contain an index th item, then return. Remove the index 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.11.3.2 The DataTransferItem interface 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 Safari iOS Chrome Android WebView Android 4+ Samsung Internet Opera Android 14+ Each DataTransferItem object is associated with a DataTransfer object. 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 Safari iOS Chrome Android WebView Android 4+ Samsung Internet Opera Android 14+ 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 Safari iOS Chrome Android WebView Android 4+ Samsung Internet Opera Android 14+ 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 Safari iOS Chrome Android WebView Android 4+ Samsung Internet Opera Android 14+ 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 Safari iOS Chrome Android WebView Android 4+ Samsung Internet Opera Android 14+ 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.11.4 The DragEvent interface DragEvent/DragEvent Support in all current engines. Firefox 3.5+ Safari 14+ Chrome 46+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android Safari iOS No Chrome Android No WebView Android Samsung Internet Opera Android DragEvent Support in all current engines. Firefox 3.5+ Safari 14+ Chrome 46+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android Safari iOS No Chrome Android No WebView Android Samsung Internet Opera Android 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 14+ Chrome 46+ Opera Edge 79+ Edge (Legacy) 12+ Internet Explorer 🔰 10+ Firefox Android Safari iOS No Chrome Android No WebView Android Samsung Internet Opera Android 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 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.11.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 navigable 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 « ». 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 encoding-parsing-and-serializing a URL given the element's href content attribute's value, relative to the element's node document If the node is an img element with a src attribute Add to urls the result of encoding-parsing-and-serializing a URL given the element's src content attribute's value, 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. Fire a pointer event at the source node named pointercancel , and fire any other follow-up events as required by Pointer Events [POINTEREVENTS] 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.11.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 HTMLElement/dragstart_event Support in all current engines. Firefox 9+ Safari 3.1+ Chrome 1+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 12+ Source node ✓ Cancelable Read/write mode none Initiate the drag-and-drop operation drag HTMLElement/drag_event Support in all current engines. Firefox 9+ Safari 3.1+ Chrome 1+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 12+ Source node ✓ Cancelable Protected mode none Continue the drag-and-drop operation dragenter HTMLElement/dragenter_event Support in all current engines. Firefox 9+ Safari 3.1+ Chrome 1+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 12+ Immediate user selection or the body element ✓ Cancelable Protected mode Based on effectAllowed value Reject immediate user selection as potential target element dragleave HTMLElement/dragleave_event Support in all current engines. Firefox 9+ Safari 3.1+ Chrome 1+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 12+ Previous target element Protected mode none None dragover HTMLElement/dragover_event Support in all current engines. Firefox 9+ Safari 3.1+ Chrome 1+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 12+ Current target element ✓ Cancelable Protected mode Based on effectAllowed value Reset the current drag operation to "none" drop HTMLElement/drop_event Support in all current engines. Firefox 9+ Safari 3.1+ Chrome 1+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 12+ Current target element ✓ Cancelable Read-only mode Current drag operation Varies dragend HTMLElement/dragend_event Support in all current engines. Firefox 9+ Safari 3.1+ Chrome 1+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 9+ Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 12+ Source node Protected mode Current drag operation Varies All of 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.11.7 The draggable attribute Global_attributes/draggable Support in all current engines. Firefox 2+ Safari 5+ Chrome 4+ Opera 12+ Edge 79+ Edge (Legacy) 12+ Internet Explorer Yes Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android All HTML elements may have the draggable content attribute set. The draggable attribute is an enumerated attribute with the following keywords and states: Keyword State Brief description true True The element will be draggable. false False The element will not be draggable. The attribute's missing value default and invalid value default are both the Auto state. 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.11.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. 6.12 The popover attribute Global_attributes/popover Support in all current engines. Firefox 🔰 114+ Safari preview+ Chrome 114+ Opera Edge 114+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android All HTML elements may have the popover content attribute set. When specified, the element won't be rendered until it becomes shown, at which point it will be rendered on top of other page content. The popover attribute is a global attribute that allows authors flexibility to ensure popover functionality can be applied to elements with the most relevant semantics. The following demonstrates how one might create a popover sub-navigation list of links, within the global navigation for a website. ul li href ... All Products button popovertarget sub-nav img src down-arrow.png alt "Product pages" button ul popover id sub-nav li >< href ... Shirts li >< href ... Shoes li >< href ... Hats etc. ul li ul When using popover on elements without accessibility semantics, for instance the div element, authors should use the appropriate ARIA attributes to ensure the popover is accessible. The following shows the baseline markup to create a custom menu popover, where the first menuitem will receive keyboard focus when the popover is invoked due to the use of the autofocus attribute. Navigating the menuitems with arrow keys and activation behaviors would still need author scripting. Additional requirements for building custom menus widgets are defined in the WAI-ARIA specification button popovertarget Actions button div role id popover button role menuitem tabindex -1 autofocus Edit button button role menuitem tabindex -1 Hide button button role menuitem tabindex -1 Delete button div A popover can be useful for rendering a status message, confirming the action performed by the user. The following demonstrates how one could reveal a popover in an output element. button id submit Submit button >< output >< span popover manual > span > output > script const sBtn document getElementById "submit" ); const outSpan document querySelector "output [popover=manual]" ); let successMessage let errorMessage /* define logic for determining success of action and determining the appropriate success or error messages to use */ sBtn addEventListener "click" ()=> if success outSpan textContent successMessage else outSpan textContent errorMessage outSpan showPopover (); setTimeout function () outSpan hidePopover (); }, 10000 ); }); script Inserting a popover element into an output element will generally cause screen readers to announce the content when it becomes visible. Depending on the complexity or frequency of the content, this could be either useful or annoying to users of these assistive technologies. Keep this in mind when using the output element or other ARIA live regions to ensure the best user experience. The popover attribute is an enumerated attribute with the following keywords and states: Keyword State Brief description auto Auto Closes other popovers when opened; has light dismiss and responds to close requests manual Manual Does not close other popovers; does not light dismiss or respond to close requests hint Hint Closes other hint popovers when opened, but not other auto popovers; has light dismiss and responds to close requests The attribute's missing value default is the No Popover state, its invalid value default is the Manual state, and its empty value default is the Auto state. HTMLElement/popover Support in all current engines. Firefox 🔰 114+ Safari 17+ Chrome 114+ Opera Edge 114+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android The popover IDL attribute must reflect the popover attribute, limited to only known values Every HTML element has a popover visibility state , initially hidden , with these potential values: hidden showing Every Document has a popover pointerdown target , which is an HTML element or null, initially null. Every HTML element has a popover trigger , which is an HTML element or null, initially set to null. Every HTML element has a popover showing or hiding , which is a boolean, initially set to false. Every HTML element popover toggle task tracker which is a toggle task tracker or null, initially null. Every HTML element has a popover close watcher which is a close watcher or null, initially null. Every HTML element has an opened in popover mode , which is a string or null, initially null. The following attribute change steps , given element localName oldValue value , and namespace , are used for all HTML elements If namespace is not null, then return. If localName is not popover , then return. If element 's popover visibility state is in the showing state and oldValue and value are in different states , then run the hide popover algorithm given element , true, true, false, and null. element showPopover () Shows the popover element by adding it to the top layer. If element 's popover attribute is in the Auto state, then this will also close all other Auto popovers unless they are an ancestor of element according to the topmost popover ancestor algorithm. element hidePopover () Hides the popover element by removing it from the top layer and applying display: none to it. element togglePopover () If the popover element is not showing, then this method shows it. Otherwise, this method hides it. This method returns true if the popover is open after calling it, otherwise false. HTMLElement/showPopover Support in all current engines. Firefox 🔰 114+ Safari 17+ Chrome 114+ Opera Edge 114+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android The showPopover( options method steps are: Let source be options [" source "] if it exists ; otherwise, null. Run show popover given this , true, and source To show popover , given an HTML element element , a boolean throwExceptions , and an HTML element or null source If the result of running check popover validity given element false, throwExceptions , and null is false, then return. Let document be element 's node document Assert element 's popover trigger is null. Assert element is not in document 's top layer Let nestedShow be element 's popover showing or hiding Let fireEvents be the boolean negation of nestedShow Set element 's popover showing or hiding to true. Let cleanupShowingFlag be the following steps: If nestedShow is false, then set element 's popover showing or hiding to false. If the result of firing an event named beforetoggle , using ToggleEvent , with the cancelable attribute initialized to true, the oldState attribute initialized to " closed ", the newState attribute initialized to " open ", and the source attribute initialized to source at element is false, then run cleanupShowingFlag and return. If the result of running check popover validity given element , false, throwExceptions , and document is false, then run cleanupShowingFlag and return. Check popover validity is called again because firing the beforetoggle event could have disconnected this element or changed its popover attribute. Let shouldRestoreFocus be false. Let originalType be the current state of element 's popover attribute. Let stackToAppendTo be null. Let autoAncestor be the result of running the topmost popover ancestor algorithm given element document 's showing auto popover list source , and true. Let hintAncestor be the result of running the topmost popover ancestor algorithm given element document 's showing hint popover list source , and true. If originalType is the Auto state, then: Run close entire popover list given document 's showing hint popover list shouldRestoreFocus , and fireEvents Let ancestor be the result of running the topmost popover ancestor algorithm given element document 's showing auto popover list source , and true. If ancestor is null, then set ancestor to document Run hide all popovers until given ancestor shouldRestoreFocus , and fireEvents Set stackToAppendTo to " auto ". If originalType is the Hint state, then: If hintAncestor is not null, then: Run hide all popovers until given hintAncestor shouldRestoreFocus , and fireEvents Set stackToAppendTo to " hint ". Otherwise: Run close entire popover list given document 's showing hint popover list shouldRestoreFocus , and fireEvents If autoAncestor is not null, then: Run hide all popovers until given autoAncestor shouldRestoreFocus , and fireEvents Set stackToAppendTo to " auto ". Otherwise, set stackToAppendTo to " hint ". If originalType is Auto or Hint , then: Assert stackToAppendTo is not null. If originalType is not equal to the value of element 's popover attribute, then: If throwExceptions is true, then throw an InvalidStateError DOMException Return. If the result of running check popover validity given element false, throwExceptions , and document is false, then run cleanupShowingFlag and return. Check popover validity is called again because running hide all popovers until above could have fired the beforetoggle event, and an event handler could have disconnected this element or changed its popover attribute. If the result of running topmost auto or hint popover on document is null, then set shouldRestoreFocus to true. This ensures that focus is returned to the previously-focused element only for the first popover in a stack. If stackToAppendTo is " auto ": Assert document 's showing auto popover list does not contain element Set element 's opened in popover mode to " auto ". Otherwise: Assert stackToAppendTo is " hint ". Assert document 's showing hint popover list does not contain element Set element 's opened in popover mode to " hint ". Set element 's popover close watcher to the result of establishing a close watcher given element 's relevant global object , with: cancelAction being to return true. closeAction being to hide a popover given element , true, true, false, and null. getEnabledState being to return true. Set element 's previously focused element to null. Let originallyFocusedElement be document 's focused area of the document 's DOM anchor Add an element to the top layer given element Set element 's popover visibility state to showing Set element 's popover trigger to source Set element 's implicit anchor element to source Run the popover focusing steps given element If shouldRestoreFocus is true and element 's popover attribute is not in the No Popover state, then set element 's previously focused element to originallyFocusedElement Queue a popover toggle event task given element , " closed ", " open ", and source Run cleanupShowingFlag To queue a popover toggle event task given an element element , a string oldState , a string newState , and an Element or null source If element 's popover toggle task tracker is not null, then: Set oldState to element 's popover toggle task tracker 's old state Remove element 's popover toggle task tracker 's task from its task queue Set element 's popover toggle task tracker to null. Queue an element task given the DOM manipulation task source and element to run the following steps: Fire an event named toggle at element , using ToggleEvent , with the oldState attribute initialized to oldState , the newState attribute initialized to newState , and the source attribute initialized to source Set element 's popover toggle task tracker to null. Set element 's popover toggle task tracker to a struct with task set to the just-queued task and old state set to oldState HTMLElement/hidePopover Support in all current engines. Firefox 🔰 114+ Safari 17+ Chrome 114+ Opera Edge 114+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android The hidePopover() method steps are: Run the hide popover algorithm given this , true, true, true, and null. To hide a popover given an HTML element element , a boolean focusPreviousElement , a boolean fireEvents , a boolean throwExceptions , and an HTML element or null source If the result of running check popover validity given element true, throwExceptions , and null is false, then return. Let document be element 's node document Let nestedHide be element 's popover showing or hiding Set element 's popover showing or hiding to true. If nestedHide is true, then set fireEvents to false. Let cleanupSteps be the following steps: If nestedHide is false, then set element 's popover showing or hiding to false. If element 's popover close watcher is not null, then: Destroy element 's popover close watcher Set element 's popover close watcher to null. If element 's opened in popover mode is " auto or " hint ", then: Run hide all popovers until given element focusPreviousElement , and fireEvents If the result of running check popover validity given element true, throwExceptions , and null is false, then run cleanupSteps and return. Check popover validity is called again because running hide all popovers until could have disconnected element or changed its popover attribute. Let autoPopoverListContainsElement be true if document 's showing auto popover list 's last item is element , otherwise false. If fireEvents is true: Fire an event named beforetoggle , using ToggleEvent , with the oldState attribute initialized to " open ", the newState attribute initialized to " closed ", and the source attribute set to source at element If autoPopoverListContainsElement is true and document 's showing auto popover list 's last item is not element , then run hide all popovers until given element focusPreviousElement , and false. If the result of running check popover validity given element true, throwExceptions , and null is false, then run cleanupSteps and return. Check popover validity is called again because firing the beforetoggle event could have disconnected element or changed its popover attribute. Request an element to be removed from the top layer given element Set element 's implicit anchor element to null. Otherwise, remove an element from the top layer immediately given element Set element 's popover trigger to null. Set element 's opened in popover mode to null. Set element 's popover visibility state to hidden If fireEvents is true, then queue a popover toggle event task given element , " open ", " closed ", and source Let previouslyFocusedElement be element 's previously focused element If previouslyFocusedElement is not null, then: Set element 's previously focused element to null. If focusPreviousElement is true and document 's focused area of the document 's DOM anchor is a shadow-including inclusive descendant of element , then run the focusing steps for previouslyFocusedElement ; the viewport should not be scrolled by doing this step. Run cleanupSteps HTMLElement/togglePopover Support in all current engines. Firefox 🔰 114+ Safari 17+ Chrome 114+ Opera Edge 114+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android The togglePopover( options method steps are: Let force be null. If options is a boolean, set force to options Otherwise, if options [" force "] exists set force to options [" force "]. Let source be options [" source "] if it exists ; otherwise, null. If this 's popover visibility state is showing , and force is null or false, then run the hide popover algorithm given this , true, true, true, and null. Otherwise, if force is null or true, then run show popover given this , true, and source Otherwise: Let expectedToBeShowing be true if this 's popover visibility state is showing ; otherwise false. Run check popover validity given expectedToBeShowing , true, and null. Return true if this 's popover visibility state is showing ; otherwise false. To hide all popovers until , given an HTML element or Document endpoint , a boolean focusPreviousElement , and a boolean fireEvents If endpoint is an HTML element and endpoint is not in the popover showing state , then return. Let document be endpoint 's node document Assert endpoint is a Document or endpoint 's popover visibility state is showing Assert endpoint is a Document or endpoint 's popover attribute is in the Auto state or endpoint 's popover attribute is in the Hint state. If endpoint is a Document Run close entire popover list given document 's showing hint popover list focusPreviousElement , and fireEvents Run close entire popover list given document 's showing auto popover list focusPreviousElement , and fireEvents Return. If document 's showing hint popover list contains endpoint Assert endpoint 's popover attribute is in the Hint state. Run hide popover stack until given endpoint document 's showing hint popover list focusPreviousElement and fireEvents Return. Run close entire popover list given document 's showing hint popover list focusPreviousElement , and fireEvents If document 's showing auto popover list does not contain endpoint , then return. Run hide popover stack until given endpoint document 's showing auto popover list focusPreviousElement , and fireEvents To hide popover stack until , given an HTML element endpoint , a list popoverList , a boolean focusPreviousElement , and a boolean fireEvents Let repeatingHide be false. Perform the following steps at least once: Let lastToHide be null. For each popover in popoverList If popover is endpoint , then break Set lastToHide to popover If lastToHide is null, then return. While lastToHide 's popover visibility state is showing Assert popoverList is not empty. Run the hide popover algorithm given the last item in popoverList focusPreviousElement fireEvents , false, and null. Assert repeatingHide is false or popoverList 's last item is endpoint Set repeatingHide to true if popoverList contains endpoint and popoverList 's last item is not endpoint otherwise false. If repeatingHide is true, then set fireEvents to false. and keep performing them while repeatingHide is true. The hide all popovers until algorithm is used in several cases to hide all popovers that don't stay open when something happens. For example, during light-dismiss of a popover, this algorithm ensures that we close only the popovers that aren't related to the node clicked by the user. To find the topmost popover ancestor , given a Node newPopoverOrTopLayerElement , a list popoverList , an HTML element or null source , and a boolean isPopover , perform the following steps. They return an HTML element or null. The topmost popover ancestor algorithm will return the topmost (latest in the showing auto popover list ) ancestor popover for the provided popover or top layer element. Popovers can be related to each other in several ways, creating a tree of popovers. There are two paths through which one popover (call it the "child" popover) can have a topmost ancestor popover (call it the "parent" popover): The popovers are nested within each other in the node tree. In this case, the descendant popover is the "child" and its topmost ancestor popover is the "parent". A popover trigger element (e.g., a button ) has a popovertarget attribute pointing to a popover. In this case, the popover is the "child", and the popover subtree the trigger element is in is the "parent". The trigger element has to be in a popover and reference an open popover. In each of the relationships formed above, the parent popover has to be strictly earlier in the showing auto popover list than the child popover, or it does not form a valid ancestral relationship. This eliminates non-showing popovers and self-pointers (e.g., a popover containing an invoking element that points back to the containing popover), and it allows for the construction of a well-formed tree from the (possibly cyclic) graph of connections. Only Auto popovers are considered. If the provided element is a top layer element such as a dialog which is not showing as a popover, then topmost popover ancestor will only look in the node tree to find the first popover. If isPopover is true: Assert newPopoverOrTopLayerElement is an HTML element Assert newPopoverOrTopLayerElement 's popover attribute is not in the No Popover State or the Manual state. Assert newPopoverOrTopLayerElement 's popover visibility state is not in the popover showing state Otherwise: Assert source is null. Let popoverPositions be an empty ordered map Let index be 0. For each popover of popoverList Set popoverPositions popover ] to index Increment index by 1. If isPopover is true, then set popoverPositions newPopoverOrTopLayerElement ] to index Increment index by 1. Let topmostPopoverAncestor be null. Let checkAncestor be an algorithm which performs the following steps given candidate If candidate is null, then return. Let okNesting be false. Let candidateAncestor be null. While okNesting is false: Set candidateAncestor to the result of running nearest inclusive open popover given candidate If candidateAncestor is null or popoverPositions does not contain candidateAncestor , then return. Assert candidateAncestor 's popover attribute is not in the Manual or None state. Set okNesting to true if isPopover is false, newPopoverOrTopLayerElement 's popover attribute is in the Hint state, or candidateAncestor 's popover attribute is in the Auto state. If okNesting is false, then set candidate to candidateAncestor 's parent in the flat tree Let candidatePosition be popoverPositions candidateAncestor ]. If topmostPopoverAncestor is null or popoverPositions topmostPopoverAncestor ] is less than candidatePosition , then set topmostPopoverAncestor to candidateAncestor Run checkAncestor given newPopoverOrTopLayerElement 's parent node within the flat tree Run checkAncestor given source Return topmostPopoverAncestor To find the nearest inclusive open popover given a Node node , perform the following steps. They return an HTML element or null. Let currentNode be node While currentNode is not null: If currentNode 's popover attribute is in the Auto state or the Hint state, and currentNode 's popover visibility state is showing then return currentNode Set currentNode to currentNode 's parent in the flat tree Return null. To find the topmost auto or hint popover given a Document document , perform the following steps. They return an HTML element or null. If document 's showing hint popover list is not empty, then return document 's showing hint popover list 's last element. If document 's showing auto popover list is not empty, then return document 's showing auto popover list 's last element. Return null. To perform the popover focusing steps for an HTML element subject If the allow focus steps given subject 's node document return false, then return. If subject is a dialog element, then run the dialog focusing steps given subject and return. If subject has the autofocus attribute, then let control be subject Otherwise, let control be the autofocus delegate for subject given " other ". If control is null, then return. Run the focusing steps given control Let topDocument be control 's node navigable 's top-level traversable 's active document If control 's node document 's origin is not the same as the origin of topDocument , then return. Empty topDocument 's autofocus candidates Set topDocument 's autofocus processed flag to true. To check popover validity for an HTML element element given a boolean expectedToBeShowing , a boolean throwExceptions , and a Document or null expectedDocument perform the following steps. They throw an exception or return a boolean. If element 's popover attribute is in the No Popover state, then: If throwExceptions is true, then throw a NotSupportedError DOMException Return false. If any of the following are true: expectedToBeShowing is true and element 's popover visibility state is not showing ; or expectedToBeShowing is false and element 's popover visibility state is not hidden then return false. If any of the following are true: element is not connected element 's node document is not fully active expectedDocument is not null and element 's node document is not expectedDocument element is a dialog element and its is modal is set to true; or element 's fullscreen flag is set, then: If throwExceptions is true, then throw an InvalidStateError DOMException Return false. Return true. To get the showing auto popover list for a Document document Let popovers be « ». For each Element element in document 's top layer If all of the following are true: element is an HTML element element 's opened in popover mode is " auto "; and element 's popover visibility state is showing then append element to popovers Return popovers To get the showing hint popover list for a Document document Let popovers be « ». For each Element element in document 's top layer If all of the following are true: element is an HTML element element 's opened in popover mode is " hint "; and element 's popover visibility state is showing then append element to popovers Return popovers To close entire popover list given a list popoverList , a boolean focusPreviousElement , and a boolean fireEvents While popoverList is not empty: Run the hide popover algorithm given popoverList 's last item, focusPreviousElement fireEvents , false, and null. 6.12.1 The popover target attributes Buttons may have the following content attributes: popovertarget popovertargetaction If specified, the popovertarget attribute value must be the ID of an element with a popover attribute in the same tree as the button with the popovertarget attribute. The popovertargetaction attribute is an enumerated attribute with the following keywords and states: Keyword State Brief description toggle Toggle Shows or hides the targeted popover element. show Show Shows the targeted popover element. hide Hide Hides the targeted popover element. The attribute's missing value default and invalid value default are both the Toggle state. Whenever possible ensure the popover element is placed immediately after its triggering element in the DOM. Doing so will help ensure that the popover is exposed in a logical programmatic reading order for users of assistive technology, such as screen readers. The following shows how the popovertarget attribute in combination with the popovertargetaction attribute can be used to show and close a popover: button popovertarget "foo" popovertargetaction "show" Show a popover button article popover "auto" id "foo" This is a popover article! button popovertarget "foo" popovertargetaction "hide" Close button article If a popovertargetaction attribute is not specified, the default action will be to toggle the associated popover. The following shows how only specifying the popovertarget attribute on its invoking button can toggle a manual popover between its opened and closed states. A manual popover will not respond to light dismiss or close requests input type "button" popovertarget "foo" value "Toggle the popover" div popover manual id "foo" This is a popover! div DOM interface HTMLButtonElement/popoverTargetElement Support in all current engines. Firefox 🔰 114+ Safari 17+ Chrome 114+ Opera Edge 114+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android HTMLInputElement/popoverTargetElement Support in all current engines. Firefox 🔰 114+ Safari 17+ Chrome 114+ Opera Edge 114+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android interface mixin PopoverTargetAttributes CEReactions Reflect attribute Element popoverTargetElement CEReactions attribute DOMString popoverTargetAction }; HTMLButtonElement/popoverTargetAction Support in all current engines. Firefox 🔰 114+ Safari 17+ Chrome 114+ Opera Edge 114+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android HTMLInputElement/popoverTargetAction Support in all current engines. Firefox 🔰 114+ Safari 17+ Chrome 114+ Opera Edge 114+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android The popoverTargetAction IDL attribute must reflect the popovertargetaction attribute, limited to only known values To run the popover target attribute activation behavior given a Node node and a Node eventTarget Let popover be node 's popover target element If popover is null, then return. If eventTarget is a shadow-including inclusive descendant of popover and popover is a shadow-including descendant of node then return. If node 's popovertargetaction attribute is in the show state and popover 's popover visibility state is showing , then return. If node 's popovertargetaction attribute is in the hide state and popover 's popover visibility state is hidden , then return. If popover 's popover visibility state is showing , then run the hide popover algorithm given popover , true, true, false, and node Otherwise, if popover 's popover visibility state is hidden and the result of running check popover validity given popover , false, false, and null is true, then run show popover given popover , false, and node To get the popover target element given a Node node , perform the following steps. They return an HTML element or null. If node is not a button , then return null. If node is disabled , then return null. If node has a form owner and node is a submit button , then return null. Let popoverElement be the result of running node 's get the popovertarget -associated element If popoverElement is null, then return null. If popoverElement 's popover attribute is in the No Popover state, then return null. Return popoverElement 6.12.2 Popover light dismiss "Light dismiss" means that clicking outside of a popover whose popover attribute is in the Auto state will close the popover. This is in addition to how such popovers respond to close requests To light dismiss open popovers , given a PointerEvent event Assert event 's isTrusted attribute is true. Let target be event 's target Let document be target 's node document Let topmostPopover be the result of running topmost auto popover given document If topmostPopover is null, then return. If event 's type is " pointerdown ", then: set document 's popover pointerdown target to the result of running topmost clicked popover given target If event 's type is " pointerup ", then: Let ancestor be the result of running topmost clicked popover given target Let sameTarget be true if ancestor is document 's popover pointerdown target Set document 's popover pointerdown target to null. If ancestor is null, then set ancestor to document If sameTarget is true, then run hide all popovers until given ancestor , false, and true. To find the topmost clicked popover , given a Node node Let clickedPopover be the result of running nearest inclusive open popover given node Let targetPopover be the result of running nearest inclusive target popover given node If the result of getting the popover stack position given clickedPopover is greater than the result of getting the popover stack position given targetPopover , then return clickedPopover Return targetPopover To get the popover stack position , given an HTML element popover Let hintList be popover 's node document 's showing hint popover list Let autoList be popover 's node document 's showing auto popover list If popover is in hintList , then return the index of popover in hintList + the size of autoList + 1. If popover is in autoList , then return the index of popover in autoList + 1. Return 0. To find the nearest inclusive target popover given a Node node Let currentNode be node While currentNode is not null: Let targetPopover be currentNode 's popover target element If targetPopover is not null and targetPopover 's popover attribute is in the Auto state or the Hint state, and targetPopover 's popover visibility state is showing then return targetPopover Set currentNode to currentNode 's ancestor in the flat tree 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 Supporting concepts 7.1.1 Origins 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 consisting of: scheme (an ASCII string ). host (a host ). port (null or a 16-bit unsigned integer). 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 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 both null, 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.1.1.1 Sites scheme-and-host is a tuple of a scheme (an ASCII string ) and a host (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 sites and , are said to be same site if the following algorithm returns true: If and are the same opaque origin , then return true. If or is an opaque origin , then return false. If 's and 's scheme values are different, then return false. If 's and 's host values are not equal , then return false. Return true. The serialization of a site is the string obtained by applying the following algorithm to the given site site If site is an opaque origin , then return " null ". Let result be site [0]. Append " :// " to result Append site [1], serialized , to result Return result It needs to be clear from context that the serialized value is a site, not an origin, as there is not necessarily a syntactic difference between the two. For example, the origin (" https ", " shop.example ", null, null) and the site (" https ", " shop.example ") have the same serialization: " ". 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 the following algorithm returns true: Let siteA be the result of obtaining a site given Let siteB be the result of obtaining a site given If siteA is same site with siteB , then return true. Return false. 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 ") (" https ", " example.com ") (" https ", " example.com. ") (Here we have omitted the port and domain components since they are not considered.) 7.1.1.2 Relaxing the same-origin restriction 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 , and Document s without a browsing context , 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 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 scalar value string hostSuffixString is a registrable domain suffix of or is equal to host originalHost If hostSuffixString is the empty string, then return false. Let hostSuffix be the result of parsing hostSuffixString If hostSuffix is failure, then return false. If hostSuffix does not equal originalHost , then: If hostSuffix or originalHost is not a domain , then return false. This excludes hosts that are IP addresses If hostSuffix , prefixed by U+002E (.), does not match the end of originalHost , then return false. If any of the following are true: hostSuffix equals hostSuffix 's public suffix ; or hostSuffix , prefixed by U+002E (.), matches the end of originalHost 's public suffix then return false. [URL] Assert originalHost 's public suffix , prefixed by U+002E (.), matches the end of hostSuffix Return true. hostSuffixString originalHost Outcome of is a registrable domain suffix of or is equal to Notes 0.0.0.0 0.0.0.0 0x10203 0.1.2.3 [0::1] ::1 example.com example.com example.com example.com. Trailing dot is significant. example.com. example.com example.com www.example.com com example.com At the time of writing, com is a public suffix. example example compute.amazonaws.com example.compute.amazonaws.com At the time of writing, .compute.amazonaws.com is a public suffix. example.compute.amazonaws.com www.example.compute.amazonaws.com amazonaws.com www.example.compute.amazonaws.com amazonaws.com test.amazonaws.com At the time of writing, amazonaws.com is a registrable domain. 7.1.1.3 The Origin interface The Origin interface represents an origin , allowing robust same origin and same site comparisons. [Exposed=*] interface Origin constructor (); static Origin from any value ); readonly attribute boolean opaque boolean isSameOrigin Origin other ); boolean isSameSite Origin other ); }; Origin objects have an associated origin , which holds an origin Platform objects have an extract an origin operation, which returns null unless otherwise specified. Objects implementing the Origin interface's extract an origin steps are to return this 's origin The new Origin() constructor steps are to set this 's origin to a unique opaque origin The static from( value method steps are: If value is a platform object Let origin be the result of executing value 's extract an origin operation. If origin is not null, then return a new Origin object whose origin is origin If value is a string Let parsedURL be the result of basic URL parsing value If parsedURL is not failure, then return a new Origin object whose origin is set to parsedURL 's origin Throw a TypeError The opaque getter steps are to return true if this 's origin is an opaque origin ; otherwise false. The isSameOrigin( other method steps are to return true if this 's origin is same origin with other 's origin ; otherwise false. The isSameSite( other method steps are to return true if this 's origin is same site with other 's origin otherwise false. 7.1.2 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 , values 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 s (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.1.3 Cross-origin opener policies An 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 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 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 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 a Cross-Origin-Embedder-Policy ` header whose value is compatible with cross-origin isolation together. noopener-allow-popups This forces the creation of a new top-level browsing context for the document, regardless of its predecessor. While including a noopener-allow-popups value severs the opener relationship between the document on which it is applied and its opener, it does not create a robust security boundary between those same-origin documents. Other risks from same-origin applications include: Same-origin requests fetching the document's content — could be mitigated through Fetch Metadata filtering. [FETCHMETADATA] Same-origin framing - could be mitigated through X-Frame-Options or CSP frame-ancestors JavaScript accessible cookies - can be mitigated by ensuring all cookies are httponly localStorage access to sensitive data. Service worker installation. Cache API manipulation or access to sensitive data. [SW] postMessage or BroadcastChannel messaging that exposes sensitive information. Autofill which may not require user interaction for same-origin documents. Developers using noopener-allow-popups need to make sure that their sensitive applications don't rely on client-side features accessible to other same-origin documents, e.g., localStorage and other client-side storage APIs, BroadcastChannel and related same-origin communication mechanisms. They also need to make sure that their server-side endpoints don't return sensitive data to non-navigation requests, whose response content is accessible to same-origin documents. An opener policy consists of: value , which is an opener policy value , initially " unsafe-none ". reporting endpoint , which is string or null, initially null. report-only value , which is an opener policy value , initially " unsafe-none ". report-only reporting endpoint which is a string or null, initially null. To match opener policy values , given an opener policy value documentCOOP , an origin documentOrigin , an opener policy value responseCOOP , and an origin responseOrigin If documentCOOP is " unsafe-none " and responseCOOP is " unsafe-none ", then return true. If documentCOOP is " unsafe-none " or responseCOOP is " unsafe-none ", then return false. If documentCOOP is responseCOOP and documentOrigin is same origin with responseOrigin , then return true. Return false. 7.1.3.1 The headers Headers/Cross-Origin-Opener-Policy Support in all current engines. Firefox 79+ Safari 15.2+ Chrome 83+ Opera No Edge 83+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android No Samsung Internet Opera Android No Document 's cross-origin opener policy is derived from the ` Cross-Origin-Opener-Policy ` and ` 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 an opener policy given a response response and an environment reservedEnvironment Let policy be a new opener policy If reservedEnvironment is a non-secure context , then return policy Let parsedItem 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 compatible with cross-origin isolation , 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 [0] is " noopener-allow-popups ", then set policy 's value to " noopener-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 compatible with cross-origin isolation or coep 's report-only value is compatible with cross-origin isolation , 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.1.3.2 Browsing context group switches due to opener policy To check if popup COOP values require a browsing context group switch , given two origins responseOrigin and activeDocumentNavigationOrigin , and two opener policy values responseCOOPValue and activeDocumentCOOPValue If responseCOOPValue is " noopener-allow-popups ", then return true. If all of the following are true: activeDocumentCOOPValue 's value is same-origin-allow-popups " or noopener-allow-popups "; and responseCOOPValue is " unsafe-none ", then return false. If the result of matching activeDocumentCOOPValue activeDocumentNavigationOrigin responseCOOPValue , and responseOrigin is true, then return false. Return true. To check if COOP values require a browsing context group switch , given a boolean isInitialAboutBlank , two origins responseOrigin and activeDocumentNavigationOrigin , and two opener policy values responseCOOPValue and activeDocumentCOOPValue If isInitialAboutBlank is true, then return the result of checking if popup COOP values requires a browsing context group switch with responseOrigin activeDocumentNavigationOrigin responseCOOPValue , and activeDocumentCOOPValue Here we are dealing with a non-popup navigation. If the result of matching activeDocumentCOOPValue activeDocumentNavigationOrigin responseCOOPValue , and responseOrigin is true, 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 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 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. An opener policy enforcement result is a 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 origin An opener policy opener policy A boolean current context is navigation source , initially false. To enforce a response's opener policy , given a browsing context browsingContext , a URL responseURL , an origin responseOrigin , an opener policy responseCOOP , an opener policy enforcement result currentCOOPEnforcementResult , and a referrer referrer Let newCOOPEnforcementResult be a new opener policy enforcement result with needs a browsing context group switch currentCOOPEnforcementResult 's needs a browsing context group switch would need a browsing context group switch due to report-only currentCOOPEnforcementResult 's would need a browsing context group switch due to report-only url responseURL origin responseOrigin opener policy responseCOOP current context is navigation source true Let isInitialAboutBlank be browsingContext 's active document 's is initial about:blank 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 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 currentCOOPEnforcementResult 's opener policy , " 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 opener policy , is true, then: Set newCOOPEnforcementResult '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 currentCOOPEnforcementResult 's opener policy , " 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 navigation params navigationParams Let browsingContext be navigationParams 's navigable 's active browsing context If browsingContext is not a top-level browsing context , then return browsingContext Let coopEnforcementResult be navigationParams 's COOP enforcement result Let swapGroup be coopEnforcementResult 's needs a browsing context group switch Let sourceOrigin be browsingContext 's active document 's origin Let destinationOrigin be navigationParams 's origin If sourceOrigin is not same site with destinationOrigin If either of sourceOrigin or destinationOrigin have a scheme that is not an HTTP(S) scheme and the user agent considers it necessary for sourceOrigin and destinationOrigin to be isolated from each other (for implementation-defined reasons), optionally set swapGroup to true. For example, if a user navigates from about:settings to , the user agent could force a swap. Issue #10842 tracks settling on an interoperable behavior here, instead of letting this be optional. If navigationParams 's user involvement is " browser UI ", optionally set swapGroup to true. Issue #6356 tracks settling on an interoperable behavior here, instead of letting this be optional. If browsingContext 's group 's browsing context set 's size is 1, optionally set swapGroup to true. Some implementations swap browsing context groups here for performance reasons. The check for other contexts that could script this one is not sufficient to prevent differences in behavior that could affect a web page. Even if there are currently no other contexts, the destination page could open a window, then if the user navigates back, the previous page could expect to be able to script the opened window. Doing a swap here would break that use case. If swapGroup is false, then: If coopEnforcementResult 's would need a browsing context group switch due to report-only is true, set browsingContext 's virtual browsing context group ID to a new unique identifier. Return browsingContext Let newBrowsingContext be the first return value of creating a new top-level browsing context and document In this case we are going to perform a browsing context group swap. browsingContext will not be used by the new Document that we are about to create . If it is not used by other Document s either (such as ones in the back/forward cache), then the user agent might destroy it at this point. Let navigationCOOP be navigationParams 's cross-origin opener policy 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. Let sandboxFlags be a clone of navigationParams 's final sandboxing flag set 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 sandboxFlags Return newBrowsingContext 7.1.3.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. Assert accessor 's active document and accessed 's active document are both fully active Let accessorTopDocument be accessor 's top-level browsing context 's active document Let accessorInclusiveAncestorOrigins be the list obtained by taking the origin of the active document of each of accessor 's active document 's inclusive ancestor navigables Let accessedTopDocument be accessed 's top-level browsing context 's active document Let accessedInclusiveAncestorOrigins be the list obtained by taking the origin of the active document of each of accessed 's active document 's inclusive ancestor navigables If any of accessorInclusiveAncestorOrigins are not same origin with accessorTopDocument 's origin , or if any of accessedInclusiveAncestorOrigins are not same origin with accessedTopDocument 's origin , then return. This avoids leaking information about cross-origin iframes to a top level frame with 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 is 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 is an ancestor of accessed , then set accessorAccessedRelationship to accessor is openee Queue violation reports for accesses , given accessorAccessedRelationship accessorTopDocument 's opener policy accessedTopDocument 's 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 accessorTopDocument 's referrer accessedTopDocument '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 an 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 an 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 nextResponseURL , null otherwise. type navigation-from-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 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 an 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 an 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 an 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 an 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 an 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 an 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.1.4 Cross-origin embedder policies Headers/Cross-Origin-Embedder-Policy Support in all current engines. Firefox 79+ Safari 15.2+ Chrome 83+ Opera Edge 83+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android 86+ Samsung Internet Opera Android An embedder policy value is one of three strings that controls the fetching of cross-origin resources without explicit permission from resource owners. 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. credentialless When this value is used, fetching cross-origin no-CORS resources omits credentials. In exchange, an explicit ` Cross-Origin-Resource-Policy ` header is not required. Other requests sent with credentials require the server's explicit permission through the CORS protocol or the ` Cross-Origin-Resource-Policy ` header. Before supporting " credentialless ", implementers are strongly encouraged to support both: Private Network Access Opaque Response Blocking Otherwise, it would allow attackers to leverage the client's network position to read non public resources, using the cross-origin isolated capability An embedder policy value is compatible with cross-origin isolation if it is " credentialless " or " require-corp ". 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.1.4.1 The headers The ` Cross-Origin-Embedder-Policy ` and Cross-Origin-Embedder-Policy-Report-Only ` HTTP response headers 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 compatible with cross-origin isolation Set policy 's value to parsedItem [0]. 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 compatible with cross-origin isolation Set policy 's report only value to parsedItem [0]. If parsedItem [1][" report-to "] exists , then set policy 's endpoint to parsedItem [1][" report-to "]. Return policy 7.1.4.2 Embedder policy checks To check a navigation response's adherence to its embedder policy given a response response , a navigable navigable , and an embedder policy responsePolicy If navigable is not a child navigable , then return true. Let parentPolicy be navigable 's container document 's policy container 's embedder policy If parentPolicy 's report-only value is compatible with cross-origin isolation and responsePolicy 's value is not, then queue a cross-origin embedder policy inheritance violation with response ", parentPolicy 's report only reporting endpoint reporting ", and navigable 's container document 's relevant settings object If parentPolicy 's value is not compatible with cross-origin isolation or responsePolicy 's value is compatible with cross-origin isolation , then return true. Queue a cross-origin embedder policy inheritance violation with response , " ", parentPolicy 's reporting endpoint enforce ", and navigable '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 policy container 's embedder policy If ownerPolicy 's report-only value is compatible with cross-origin isolation and policy 's value is not, then queue a cross-origin embedder policy inheritance violation with response , " worker initialization ", ownerPolicy 's report only reporting endpoint reporting ", and owner If ownerPolicy 's value is not compatible with cross-origin isolation or policy 's value is compatible with cross-origin isolation , then return true. Queue a cross-origin embedder policy inheritance violation with response , " worker initialization ", ownerPolicy '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.1.5 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 origin browsing context flag This flag forces content into an opaque 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 download The sandboxed custom protocols navigation browsing context flag This flag prevents navigations toward non fetch schemes from being handed off to external software When the user agent is to parse a sandboxing directive , given a string input and 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 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. The sandboxed custom protocols navigation browsing context flag , unless tokens contains either the allow-top-navigation-to-custom-protocols keyword, the allow-popups keyword, or the allow-top-navigation 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 navigable 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 CSP list cspList has CSP-derived sandboxing flags , which is a sandboxing flag set . It is the return value of the following algorithm: Let directives be an empty ordered set For each policy in cspList If policy 's disposition is not " enforce ", then continue If policy 's directive set contains directive whose name is " sandbox ", then append that directive to directives If directives is empty, then return an empty sandboxing flag set Let directive be directives directives 's size − 1]. Return the result of parsing the sandboxing directive directive 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 7.1.6 iframe element referrer policy To determine the iframe element referrer policy given an element-or-null embedder If embedder is an iframe element, then return embedder 's referrerpolicy attribute's state's corresponding keyword. Return the empty string. This is used for allowing masking of some origins in the internal ancestor origin objects list creation steps 7.1.7 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. An embedder policy , which is an embedder policy . It is initially a new embedder policy referrer policy , which is a referrer policy . It is initially the default referrer policy An integrity policy , which is an integrity policy , initially a new integrity policy report only integrity policy , which is an integrity policy , initially a new integrity policy 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 Set clone 's embedder policy to a copy of policyContainer 's embedder policy Set clone 's referrer policy to policyContainer 's referrer policy Set clone 's integrity policy to a copy of policyContainer 's integrity policy 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 local , then return true. Return false. To create a policy container from a fetch response given a response response and an environment -or-null environment 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 If environment is non-null, then set result 's embedder policy to the result of obtaining an embedder policy given response and environment . Otherwise, set it to " unsafe-none ". Set result 's referrer policy to the result of parsing the Referrer-Policy ` header given response [REFERRERPOLICY] Parse Integrity-Policy headers with response and result 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 , a response response , and an environment environment 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 and environment 7.2 APIs related to navigation and session history 7.2.1 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. This section uses the terminology and typographic conventions from the JavaScript specification. [JAVASCRIPT] 7.2.1.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.1.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.1.3 Shared abstract operations 7.2.1.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 " } ». This abstract operation does not return a Completion Record 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.1.3.2 CrossOriginPropertyFallback If is " then ", %Symbol.toStringTag% %Symbol.hasInstance% , or %Symbol.isConcatSpreadable% , then return PropertyDescriptor [[Value]]: undefined, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }. Throw a SecurityError DOMException 7.2.1.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. This abstract operation does not return a Completion Record 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.1.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 , 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 , 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 , 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. This abstract operation does not return a Completion Record 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.1.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.1.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 desc .[[Set]], Receiver »). Return true. Throw a SecurityError DOMException 7.2.1.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 ", %Symbol.toStringTag% %Symbol.hasInstance% %Symbol.isConcatSpreadable% ». This abstract operation does not return a Completion Record 7.2.2 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 Safari iOS Chrome Android WebView Android 37+ Samsung Internet 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 Replaceable readonly attribute 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 = "");
// 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. getter object DOMString name );
// the user agent readonly attribute Navigator navigator Replaceable readonly attribute Navigator clientInformation ; // legacy alias of .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 StructuredSerializeOptions 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 Safari iOS 1+ Chrome Android WebView Android Samsung Internet 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 Safari iOS Chrome Android WebView Android Samsung Internet 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 Safari iOS 1+ Chrome Android WebView Android Samsung Internet 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 Safari iOS Chrome Android WebView Android Samsung Internet 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 Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 12.1+ Returns the Window associated with document , if there is one, or null otherwise. 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 Window 's browsing context is its associated Document 's browsing context It is either null or a browsing context Window 's navigable is the navigable whose active document is the Window 's associated Document 's, or null if there is no such navigable The window frames , and self getter steps are to return this 's relevant realm .[[GlobalEnv]].[[GlobalThisValue]]. The document getter steps are to return this '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 getter steps are: If this 's browsing context is null, then return null. Return this '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 Safari iOS Chrome Android WebView Android Samsung Internet 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.2.2.1 Opening and closing windows 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 Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 10.1+ Opens a window to show url (defaults to " about:blank "), and returns it. target (defaults to " _blank ") gives the name of the new window. If a window already exists with that name, it is reused. The features argument can contain a set of comma-separated tokens noopener noreferrer These behave equivalently to the noopener and noreferrer link types on hyperlinks popup Encourages user agents to provide a minimal web browser user interface for the new window. (Impacts the visible getter on all BarProp objects as well.) globalThis open "https://email.example/message/CAOOOkFcWW97r8yg=SsWg7GgCmp4suVX9o85y8BvNRqMjuc5PXg" undefined "noopener,popup" ); 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 Safari iOS Chrome Android WebView Android Samsung Internet 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 Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 10.1+ Closes the window. window closed Window/closed Support in all current engines. Firefox 1+ Safari 1+ Chrome 1+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 4+ Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 12.1+ 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 Safari iOS 1+ Chrome Android WebView Android Samsung Internet Opera Android 12.1+ Cancels the document load. To get noopener for window open , given a Document sourceDocument , an ordered map tokenizedFeatures , and a URL record -or-null url , perform the following steps. They return a boolean. If url is not null and url 's blob URL entry is not null: Let blobOrigin be url 's blob URL entry 's environment 's origin Let topLevelOrigin be sourceDocument 's relevant settings object 's top-level origin If blobOrigin is not same site with topLevelOrigin then return true. Let noopener be false. If tokenizedFeatures [" noopener "] exists , then set noopener to the result of parsing tokenizedFeatures [" noopener "] as a boolean feature Return noopener 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, then return null. Let sourceDocument be the entry global object 's associated Document Let urlRecord be null. If url is not the empty string, then: Set urlRecord to the result of encoding-parsing a URL given url , relative to sourceDocument If urlRecord is failure, then throw a SyntaxError DOMException If target is the empty string, then set target to " _blank ". Let tokenizedFeatures be the result of tokenizing features Let noreferrer be false. If tokenizedFeatures [" noreferrer "] exists , then set noreferrer to the result of parsing tokenizedFeatures [" noreferrer "] as a boolean feature Let noopener be the result of getting noopener for window open with sourceDocument tokenizedFeatures , and urlRecord Remove tokenizedFeatures [" noopener "] and tokenizedFeatures [" noreferrer "]. Let referrerPolicy be the empty string. If noreferrer is true, then set noopener to true and set referrerPolicy to " no-referrer ". Let targetNavigable and windowType be the result of applying the rules for choosing a navigable given target sourceDocument 's node navigable , 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. If targetNavigable is null, then return null. If windowType is either " new and unrestricted " or " new with no opener ", then: Set targetNavigable 's active browsing context 's is popup to the result of checking if a popup window is requested , given tokenizedFeatures Set up browsing context features for targetNavigable 's active browsing context given tokenizedFeatures [CSSOMVIEW] If urlRecord is null, then set urlRecord to a URL record representing about:blank If urlRecord matches about:blank , then perform the URL and history update steps given targetNavigable 's active document and urlRecord This is necessary in case url is something like about:blank?foo . If url is just plain about:blank , this will do nothing. Otherwise, navigate targetNavigable to urlRecord using sourceDocument , with referrerPolicy set to referrerPolicy and exceptionsEnabled set to true. Otherwise: If urlRecord is not null, then navigate targetNavigable to urlRecord using sourceDocument , with referrerPolicy set to referrerPolicy and exceptionsEnabled set to true. If noopener is false, then set targetNavigable 's active browsing context 's opener browsing context to sourceDocument 's browsing context If noopener is true or windowType is " new with no opener ", then return null. Return targetNavigable 's active WindowProxy The open( url target features method steps are to run the window open steps with url target , and features The method provides a mechanism for navigating an existing browsing context or opening and navigating an auxiliary browsing context 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 To check if a window feature is set , given tokenizedFeatures featureName , and defaultValue If tokenizedFeatures featureName exists , then return the result of parsing tokenizedFeatures featureName ] as a boolean feature Return defaultValue To check if a popup window is requested , given tokenizedFeatures If tokenizedFeatures is empty , then return false. If tokenizedFeatures [" popup "] exists , then return the result of parsing tokenizedFeatures [" popup "] as a boolean feature Let location be the result of checking if a window feature is set , given tokenizedFeatures , " location ", and false. Let toolbar be the result of checking if a window feature is set , given tokenizedFeatures , " toolbar ", and false. If location and toolbar are both false, then return true. Let menubar be the result of checking if a window feature is set , given tokenizedFeatures , " menubar ", and false. If menubar is false, then return true. Let resizable be the result of checking if a window feature is set , given tokenizedFeatures , " resizable ", and true. If resizable is false, then return true. Let scrollbars be the result of checking if a window feature is set , given tokenizedFeatures , " scrollbars ", and false. If scrollbars is false, then return true. Let status be the result of checking if a window feature is set , given tokenizedFeatures , " status ", and false. If status is false, then return true. Return false. 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. If value is true ", 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 getter steps are: If this 's navigable is null, then return the empty string. Return this 's navigable 's target name The name setter steps are: If this 's navigable is null, then return. Set this 's navigable 's active session history entry 's document state 's navigable target name to the given value. The name gets reset when the navigable is navigated to another origin The close() method steps are: Let thisTraversable be this 's navigable If thisTraversable is not a top-level traversable , then return. If thisTraversable 's is closing is true, then return. Let browsingContext be thisTraversable 's active browsing context Let sourceSnapshotParams be the result of snapshotting source snapshot params given thisTraversable 's active document If all the following are true: thisTraversable is script-closable the incumbent global object 's browsing context is familiar with browsingContext ; and the incumbent global object 's navigable is allowed by sandboxing to navigate thisTraversable , given sourceSnapshotParams then: Set thisTraversable 's is closing to true. Queue a task on the DOM manipulation task source to definitely close thisTraversable navigable is script-closable if it is a top-level traversable , and any of the following are true: its is created by web content is true; or its session history entries 's size is 1. The closed getter steps are to return true if this 's browsing context is null or its is closing is true; otherwise false. The stop() method steps are: If this 's navigable is null, then return. Stop loading this 's navigable 7.2.2.2 Indexed access on the Window object 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 Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 12.1+ Returns the number of document-tree child navigables window index Returns the WindowProxy corresponding to the indicated document-tree child navigables The length getter steps are to return this 's associated Document 's document-tree child navigables 's size Indexed access to document-tree child navigables is defined through the [[GetOwnProperty]] internal method of the WindowProxy object. 7.2.2.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 navigable target name property set of a Window object window is the return value of running these steps: Let children be the document-tree child navigables of window 's associated Document Let firstNamedChildren be an empty ordered set For each navigable of children Let name be navigable 's target name If name is the empty string, then continue If firstNamedChildren contains navigable whose target name is name then continue Append navigable to firstNamedChildren Let names be an empty ordered set For each navigable of firstNamedChildren Let name be navigable 's target name If navigable 's active document 's origin is same origin with window 's relevant settings object 's origin , then append name to names Return names The two seperate iterations mean 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 navigable target 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, since the algorithm would otherwise not have been invoked by Web IDL If objects contains a navigable , then: Let container be the first navigable container in window 's associated Document 's descendants whose content navigable is in objects Return container 's content navigable 's active WindowProxy 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 navigables of window 's associated Document whose target 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 Since the Window interface has the [Global] extended attribute, its named properties follow the rules for named properties objects rather than legacy platform objects 7.2.2.4 Accessing related windows 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 WebView Android Samsung Internet Opera Android 12.1+ Returns the WindowProxy for the top-level traversable 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 Safari iOS Chrome Android WebView Android Samsung Internet 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 Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 10.1+ Returns the WindowProxy for the parent navigable 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 Safari iOS 1+ Chrome Android WebView Android Samsung Internet Opera Android 12.1+ Returns the navigable container element. Returns null if there isn't one, and in cross-origin situations. The top getter steps are: If this 's navigable is null, then return null. Return this 's navigable 's top-level traversable 's active WindowProxy The opener getter steps are: Let current be this 's browsing context If current is null, 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 setter steps are: If the given value is null and this 's browsing context is non-null, then set this 's browsing context 's opener browsing context to null. If the given value is non-null, then perform ? DefinePropertyOrThrow this , " opener ", { [[Value]]: the given value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }). Setting window.opener to null clears the opener browsing context reference. In practice, this prevents future scripts from accessing their opener browsing context 's Window object. By default, scripts can access their opener browsing context 's Window object through the window.opener getter. E.g., a script can set window.opener.location , causing the opener browsing context to navigate. The parent getter steps are: Let navigable be this 's navigable If navigable is null, then return null. If navigable 's parent is not null, then set navigable to navigable 's parent Return navigable 's active WindowProxy The frameElement getter steps are: Let current be this 's node navigable 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 properties 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 nulled out when element was removed from the document. 7.2.2.5 Historical browser interface element APIs For historical reasons, the Window interface had some properties that represented the visibility of certain web browser interface elements. For privacy and interoperability reasons, those properties now return values that represent whether the Window 's browsing context 's is popup property is true or false. Each interface element is represented by a BarProp object: BarProp Support in all current engines. Firefox 1+ Safari 3+ Chrome 1+ Opera Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android Safari iOS 1+ Chrome Android WebView Android 37+ Samsung Internet Opera Android 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 Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android Safari iOS 1+ Chrome Android WebView Android Samsung Internet Opera Android window menubar visible Window/menubar Support in all current engines. Firefox 1+ Safari 3+ Chrome 1+ Opera Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android Safari iOS 1+ Chrome Android WebView Android Samsung Internet Opera Android 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 Safari iOS 1+ Chrome Android WebView Android Samsung Internet Opera Android 12.1+ 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 Safari iOS 1+ Chrome Android WebView Android Samsung Internet Opera Android 12.1+ window statusbar visible Window/statusbar Support in all current engines. Firefox 1+ Safari 3+ Chrome 1+ Opera Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android Safari iOS 1+ Chrome Android WebView Android Samsung Internet Opera Android window toolbar visible Window/toolbar Support in all current engines. Firefox 1+ Safari 3+ Chrome 1+ Opera Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android Safari iOS 1+ Chrome Android WebView Android Samsung Internet Opera Android Returns true if the Window is not a popup; otherwise, returns false. BarProp/visible Support in all current engines. Firefox 1+ Safari 3+ Chrome 1+ Opera Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android Safari iOS 1+ Chrome Android WebView Android 37+ Samsung Internet Opera Android The visible getter steps are: Let browsingContext be this 's relevant global object 's browsing context If browsingContext is null, then return true. Return the negation of browsingContext 's top-level browsing context 's is popup The following BarProp objects must exist for each Window object: The location bar BarProp object Historically represented the user interface element that contains a control that displays the browser's location bar. The menu bar BarProp object Historically represented the user interface element that contains a list of commands in menu form, or some similar interface concept. The personal bar BarProp object Historically represented the user interface element that contains links to the user's favorite pages, or some similar interface concept. The scrollbar BarProp object Historically represented the user interface element that contains a scrolling mechanism, or some similar interface concept. The status bar BarProp object Historically represented 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 currently indicating. The toolbar BarProp object Historically represented 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.). 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.2.2.6 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 API base URL Return the current base URL of window 's associated Document The origin Return the origin of window 's associated Document The has cross-site ancestor If window 's navigable 's parent is null, then return false. Let parentDocument be window 's navigable 's parent 's active document If parentDocument 's relevant settings object 's has cross-site ancestor is true, then return true. If parentDocument 's origin is not same site with window 's associated Document 's origin , then return true. Return false. The policy container Return the policy container of window 's associated Document 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. The time origin Return window 's associated Document 's load timing info 's navigation start time 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.2.3 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.2.3.1 [[GetPrototypeOf]] ( ) Let be the value of the [[Window]] internal slot of this If IsPlatformObjectSameOrigin ) is true, then return ! OrdinaryGetPrototypeOf ). Return null. 7.2.3.2 [[SetPrototypeOf]] ( Return ! SetImmutablePrototype this ). 7.2.3.3 [[IsExtensible]] ( ) Return true. 7.2.3.4 [[PreventExtensions]] ( ) Return false. 7.2.3.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 children be the document-tree child navigables of 's associated Document Let value be undefined. If index is less than children 's size , then: Sort children in ascending order, with navigableA being less than navigableB if navigableA 's container was inserted into 's associated Document earlier than navigableB 's container was. Set value to children index ]'s active WindowProxy 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 navigable target name property set , then: Let value be the active WindowProxy 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.2.3.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.2.3.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.2.3.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: If is an array index property name then return false. Return ? OrdinarySet Receiver ). Return ? CrossOriginSet this Receiver ). this is passed rather than as CrossOriginSet will invoke the [[GetOwnProperty]] internal method. 7.2.3.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.2.3.10 [[OwnPropertyKeys]] ( ) Let be the value of the [[Window]] internal slot of this Let maxProperties be 's associated Document 's document-tree child navigables 's size Let keys be the range 0 to maxProperties , exclusive. If IsPlatformObjectSameOrigin ) is true, then return the concatenation of keys and OrdinaryOwnPropertyKeys ). Return the concatenation of keys and ! CrossOriginOwnPropertyKeys ). 7.2.4 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 Safari iOS Chrome Android WebView Android Samsung Internet 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 Safari iOS Chrome Android WebView Android 37+ Samsung Internet 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 Safari iOS Chrome Android WebView Android Samsung Internet 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]]( %Symbol.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 %Symbol.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 %Symbol.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 getter steps are to return this 's relevant global object 's Location object, if this is fully active , and null otherwise. The Window object's location getter steps are to return this 's Location object. Location objects provide a representation of the URL of their associated Document , as well as methods for navigating and reloading the associated navigable 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 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 Safari iOS Chrome Android WebView Android Samsung Internet 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 Safari iOS Chrome Android WebView Android Samsung Internet 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 Edge 79+ Edge (Legacy) 12+ Internet Explorer 11 Firefox Android Safari iOS Chrome Android WebView Android 3+ Samsung Internet Opera Android 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 Safari iOS Chrome Android WebView Android Samsung Internet 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 Safari iOS Chrome Android WebView Android Samsung Internet 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 Safari iOS Chrome Android WebView Android Samsung Internet 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 Safari iOS Chrome Android WebView Android Samsung Internet 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 Safari iOS Chrome Android WebView Android Samsung Internet 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 Safari iOS Chrome Android WebView Android Samsung Internet 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 Safari iOS Chrome Android WebView Android Samsung Internet 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 Safari iOS 1+ Chrome Android WebView Android Samsung Internet 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 Safari iOS Chrome Android WebView Android Samsung Internet 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 Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 10.1+ Reloads the current page. location ancestorOrigins Location/ancestorOrigins Firefox No Safari 6+ Chrome 20+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android Returns a DOMStringList object listing the origins of the ancestor navigables active documents Location object has an associated relevant Document which is its 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. To Location -object navigate Location object location to a URL url , optionally given a NavigationHistoryBehavior historyHandling (default " auto "): Let navigable be location 's relevant global object 's navigable Let sourceDocument be the incumbent global object 's associated Document If location 's relevant Document is not yet completely loaded , and the incumbent global object does not have transient activation , then set historyHandling to " replace ". Navigate navigable to url using sourceDocument , with exceptionsEnabled set to true and historyHandling set to historyHandling The href getter steps are: If this '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 's url serialized The href setter steps are: If this 's relevant Document is null, then return. Let url be the result of encoding-parsing a URL given the given value, relative to the entry settings object If url is failure, then throw a SyntaxError DOMException Location -object navigate this to url The href setter intentionally has no security check. The origin getter steps are: If this '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 's url 's origin The protocol getter steps are: If this '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 's url 's scheme , followed by " ". The protocol setter steps are: If this 's relevant Document is null, then return. If this '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 '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 navigate this to copyURL The host getter steps are: If this '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 '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 setter steps are: If this 's relevant Document is null, then return. If this '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 's url If copyURL has an opaque path , then return. Basic URL parse the given value, with copyURL as url and host state as state override Location -object navigate this to copyURL The hostname getter steps are: If this '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 's url 's host is null, return the empty string. Return this 's url 's host serialized The hostname setter steps are: If this 's relevant Document is null, then return. If this '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 's url If copyURL has an opaque path , then return. Basic URL parse the given value, with copyURL as url and hostname state as state override Location -object navigate this to copyURL The port getter steps are: If this '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 's url 's port is null, return the empty string. Return this 's url 's port serialized The port setter steps are: If this 's relevant Document is null, then return. If this '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 '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 navigate this to copyURL The pathname getter steps are: If this '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 result of URL path serializing this Location object's url The pathname setter steps are: If this 's relevant Document is null, then return. If this '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 's url If copyURL has an opaque path , 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 navigate this to copyURL The getter steps are: If this '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 's url 's query is either null or the empty string, return the empty string. Return " ", followed by this 's url 's query The setter steps are: If this 's relevant Document is null, then return. If this '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 '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 navigate this to copyURL The hash getter steps are: If this '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 's url 's fragment is either null or the empty string, return the empty string. Return " ", followed by this 's url 's fragment The hash setter steps are: If this 's relevant Document is null, then return. If this '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 's url Let thisURLFragment be copyURL 's fragment if it is non-null; otherwise the empty string. 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 If copyURL 's fragment is thisURLFragment , then return. This bailout is necessary for compatibility with deployed content, which redundantly sets location.hash on scroll . It does not apply to other mechanisms of fragment navigation, such as the location.href setter or location.assign() Location -object navigate this to copyURL Unlike the equivalent API for the and area elements, the hash setter does not special case the empty string, to remain compatible with deployed scripts. The assign( url method steps are: If this 's relevant Document is null, then return. If this 's relevant Document 's origin is not same origin-domain with the entry settings object 's origin , then throw a SecurityError DOMException Let urlRecord be the result of encoding-parsing a URL given url , relative to the entry settings object If urlRecord is failure, then throw a SyntaxError DOMException Location -object navigate this to urlRecord The replace( url method steps are: If this 's relevant Document is null, then return. Let urlRecord be the result of encoding-parsing a URL given url , relative to the entry settings object If urlRecord is failure, then throw a SyntaxError DOMException Location -object navigate this to urlRecord given " replace ". The replace() method intentionally has no security check. The reload() method steps are: Let document be this 's relevant Document If document is null, then return. If document 's origin is not same origin-domain with the entry settings object 's origin , then throw a SecurityError DOMException Reload document 's node navigable Location object has an associated empty DOMStringList which is a DOMStringList object whose associated list is an empty list This object cannot carry state across navigations because it is only returned when there is no relevant Document , in which case it's not possible to navigate, and it's not possible to return to a non-null relevant Document The ancestorOrigins getter steps are: If this 's relevant Document is null, then return this 's empty DOMStringList If this 's relevant Document 's origin is not same origin-domain with the entry settings object 's origin , then throw a SecurityError DOMException Assert this 's relevant Document 's ancestor origins list is not null. Otherwise, return this 's relevant Document 's ancestor origins list 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.2.4.1 [[GetPrototypeOf]] ( ) If IsPlatformObjectSameOrigin this ) is true, then return ! OrdinaryGetPrototypeOf this ). Return null. 7.2.4.2 [[SetPrototypeOf]] ( Return ! SetImmutablePrototype this ). 7.2.4.3 [[IsExtensible]] ( ) Return true. 7.2.4.4 [[PreventExtensions]] ( ) Return false. 7.2.4.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.2.4.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.2.4.7 [[Get]] ( Receiver If IsPlatformObjectSameOrigin this ) is true, then return ? OrdinaryGet this Receiver ). Return ? CrossOriginGet this Receiver ). 7.2.4.8 [[Set]] ( Receiver If IsPlatformObjectSameOrigin this ) is true, then return ? OrdinarySet this Receiver ). Return ? CrossOriginSet this Receiver ). 7.2.4.9 [[Delete]] ( If IsPlatformObjectSameOrigin this ) is true, then return ? OrdinaryDelete this ). Throw a SecurityError DOMException 7.2.4.10 [[OwnPropertyKeys]] ( ) If IsPlatformObjectSameOrigin this ) is true, then return OrdinaryOwnPropertyKeys this ). Return CrossOriginOwnPropertyKeys this ). 7.2.5 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 Safari iOS Chrome Android WebView Android Samsung Internet 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 Safari iOS Chrome Android WebView Android Samsung Internet 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 ); }; 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 Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 12.1+ Returns the number of overall session history entries for the current traversable navigable history scrollRestoration History/scrollRestoration Support in all current engines. Firefox 46+ Safari 11+ Chrome 46+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android Returns the scroll restoration mode of the active session history entry history scrollRestoration value Set the scroll restoration mode of the active session history entry to value 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 Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 12.1+ Returns the classic history API state of the active session history entry , deserialized into a JavaScript value. history go () Reloads the current page. 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 Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 12.1+ Goes back or forward the specified number of steps in the overall session history entries list for the current traversable navigable A zero delta will reload the current page. If the delta is out of range, does nothing. 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 Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 12.1+ Goes back one step in the overall session history entries list for the current traversable navigable If there is no previous page, does nothing. 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 Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 12.1+ Goes forward one step in the overall session history entries list for the current traversable navigable If there is no next page, does nothing. history pushState data , "") 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 Safari iOS 4+ Chrome Android WebView Android 37+ Samsung Internet Opera Android 11.5+ Adds a new entry into session history with its classic history API state set to a serialization of data . The active history entry 's URL will be copied over and used for the new entry's URL. (The second parameter exists for historical reasons, and cannot be omitted; passing the empty string is traditional.) history pushState data , "", url Adds a new entry into session history with its classic history API state set to a serialization of data , and with its URL set to url If the current Document cannot have its URL rewritten to url , a SecurityError DOMException will be thrown. (The second parameter exists for historical reasons, and cannot be omitted; passing the empty string is traditional.) history replaceState data , "") 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 Safari iOS 4+ Chrome Android WebView Android 37+ Samsung Internet Opera Android 11.5+ Updates the classic history API state of the active session history entry to a structured clone of data (The second parameter exists for historical reasons, and cannot be omitted; passing the empty string is traditional.) history replaceState data , "", url Updates the classic history API state of the active session history entry to a structured clone of data , and its URL to url If the current Document cannot have its URL rewritten to url , a SecurityError DOMException will be thrown. (The second parameter exists for historical reasons, and cannot be omitted; passing the empty string is traditional.) Document has a history object , a History object. The history getter steps are to return this 's associated Document 's history object Each History object has state initially null. Each History object has a length , a non-negative integer, initially 0. Each History object has an index , a non-negative integer, initially 0. Although the index is not directly exposed, it can be inferred from changes to the length during synchronous navigations. In fact, that is what it's used for. The length getter steps are: If this 's relevant global object 's associated Document is not fully active , then throw a SecurityError DOMException Return this 's length The scrollRestoration getter steps are: If this 's relevant global object 's associated Document is not fully active , then throw a SecurityError DOMException Return this 's relevant global object 's navigable 's active session history entry 's scroll restoration mode The scrollRestoration setter steps are: If this 's relevant global object 's associated Document is not fully active , then throw a SecurityError DOMException Set this 's relevant global object 's navigable 's active session history entry 's scroll restoration mode to the given value. The state getter steps are: If this 's relevant global object 's associated Document is not fully active , then throw a SecurityError DOMException Return this 's state The go( delta method steps are to delta traverse this given delta The back() method steps are to delta traverse this given −1. The forward() method steps are to delta traverse this given +1. To delta traverse History object history given an integer delta Let document be history 's relevant global object 's associated Document If document is not fully active , then throw a SecurityError DOMException If delta is 0, then reload document 's node navigable , and return. Traverse the history by a delta given document 's node navigable 's traversable navigable delta and with sourceDocument set to document The pushState( data unused url method steps are to run the shared history push/replace state steps given this data url , and push ". The replaceState( data unused url method steps are to run the shared history push/replace state steps given this data url , and " replace ". The shared history push/replace state steps , given a History history , a value data , a scalar value string -or-null url , and a history handling behavior historyHandling , are: Let document be history 's relevant global object 's associated Document If document is not fully active , then throw a SecurityError DOMException Optionally, throw a SecurityError DOMException (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 document 's URL If url is not null or the empty string, then: Set newURL to the result of encoding-parsing a URL given url , relative to the relevant settings object of history If newURL is failure, then throw a SecurityError DOMException If document cannot have its URL rewritten to newURL , then throw a SecurityError DOMException The special case for the empty string here is historical, and leads to different resulting URLs when comparing code such as location.href = "" (which performs URL parsing on the empty string) versus history.pushState(null, "", "") (which bypasses it). Let be history 's relevant global object 's navigation API Let continue be the result of firing a push/replace/reload navigate event at with navigationType set to historyHandling isSameDocument set to true, destinationURL set to newURL , and classicHistoryAPIState set to serializedData If continue is false, then return. Run the URL and history update steps given document and newURL , with serializedData set to serializedData and historyHandling set to historyHandling 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.) Document document can have its URL rewritten to a URL targetURL if the following algorithm returns true: Let documentURL be document 's URL If targetURL and documentURL differ in their scheme username password host , or port components, then return false. If targetURL 's scheme is an HTTP(S) scheme , then return true. Differences in path query , and fragment are allowed for http: and https: URLs. If targetURL 's scheme is " file ", then: If targetURL and documentURL differ in their path component, then return false. Return true. Differences in query and fragment are allowed for file: URLs. If targetURL and documentURL differ in their path component or query components, then return false. Only differences in fragment are allowed for other types of URLs. Return true. document 's URL targetURL can have its URL rewritten file:///path/to/x file:///path/to/x#hash file:///path/to/x file:///path/to/x?search file:///path/to/x file:///path/to/y about:blank about:blank#hash about:blank about:blank?search about:blank about:srcdoc data:text/html,foo data:text/html,foo#hash data:text/html,foo data:text/html,foo?search data:text/html,foo data:text/html,bar data:text/html,foo data:bar blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43 blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43#hash blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43 blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43?search blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43 blob:https://example.com/anything blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43 blob:path Note how only the URL of the Document matters, and not its origin . They can mismatch in cases like about:blank Document s with inherited origins, in sandboxed iframe s, or when the document.domain setter has been used. 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. 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.2.6 The navigation API 7.2.6.1 Introduction This section is non-normative. The navigation API, provided by the global property, provides a modern and web application-focused way of managing navigations and history entries. It is a successor to the classic location and history APIs. One ability the API provides is inspecting session history entries . For example, the following will display the entries' URLs in an ordered list: const ol document createElement "ol" ); ol start // so that the list items' ordinal values match up with the entry indices for const entry of entries ()) const li document createElement "li" ); if entry index currentEntry index li className "backward" else if entry index currentEntry index li className "forward" else li className "current" li textContent entry url ol append li ); The navigation.entries() array contains NavigationHistoryEntry instances, which have other useful properties in addition to the url and index properties shown here. Note that the array only contains NavigationHistoryEntry objects that represent the current navigable , and thus its contents are not impacted by navigations inside navigable containers such as iframe s, or by navigations of the parent navigable in cases where the navigation API is itself being used inside an iframe . Additionally, it only contains NavigationHistoryEntry objects representing same- origin session history entries , meaning that if the user has visited other origins before or after the current one, there will not be corresponding NavigationHistoryEntry s. The navigation API can also be used to navigate, reload, or traverse through the history: button onclick "navigation.reload()" Reload button input type "url" id "navigationURL" button onclick "navigation.navigate(navigationURL.value)" Navigate button button id "backButton" onclick "navigation.back()" Back button button id "forwardButton" onclick "navigation.forward()" Forward button select id "traversalDestinations" > select button id "goButton" onclick "navigation.traverseTo(traversalDestinations.value)" Traverse To button script backButton disabled canGoBack forwardButton disabled canGoForward for const entry of entries ()) traversalDestinations append new Option entry url entry key )); script Note that traversals are again limited to same- origin destinations, meaning that, for example, navigation.canGoBack will be false if the previous session history entry is for a page from another origin. The most powerful part of the navigation API is the navigate event, which fires whenever almost any navigation or traversal occurs in the current navigable onnavigate event => console log event navigationType ); // "push", "replace", "reload", or "traverse" console log event destination url ); console log event userInitiated ); // ... and other useful properties }; (The event will not fire for location bar-initiated navigations , or navigations initiated from other windows, when the destination of the navigation is a new document.) Much of the time, the event's cancelable property will be true, meaning this event can be canceled using preventDefault() onnavigate event => if event cancelable && isDisallowedURL event destination url )) alert `Please don't go to ${ event destination url !` ); event preventDefault (); }; The cancelable property will be false for some " traverse " navigations, such as those taking place inside child navigables , those crossing to new origins, or when the user attempts to traverse again shortly after a previous call to preventDefault() prevented them from doing so. The NavigateEvent 's intercept() method allows intercepting a navigation and converting it into a same-document navigation: addEventListener "navigate" => // Some navigations, e.g. cross-origin navigations, we cannot intercept. // Let the browser handle those normally. if canIntercept return // Similarly, don't intercept fragment navigations or downloads. if hashChange || downloadRequest !== null return const url new URL event destination url ); if url pathname startsWith "/articles/" )) intercept ({ async handler () // The URL has already changed, so show a placeholder while // fetching the new content, such as a spinner or loading page. renderArticlePagePlaceholder (); // Fetch the new content and display when ready. const articleContent await getArticleContent url pathname signal signal }); renderArticlePage articleContent ); }); }); Note that the handler function can return a promise to represent the asynchronous progress, and success or failure, of the navigation. While the promise is still pending, browser UI can treat the navigation as ongoing (e.g., by presenting a loading spinner). Other parts of the navigation API are also sensitive to these promises, such as the return value of navigation.navigate() const committed finished await navigate "/articles/the-navigation-api-is-cool" ); // The committed promise will fulfill once the URL has changed, which happens // immediately (as long as the NavigateEvent wasn't canceled). await committed // The finished promise will fulfill once the Promise returned by handler() has // fulfilled, which happens once the article is downloaded and rendered. (Or, // it will reject, if handler() fails along the way). await finished 7.2.6.2 The interface Exposed Window interface EventTarget sequence NavigationHistoryEntry entries (); readonly attribute NavigationHistoryEntry currentEntry undefined updateCurrentEntry NavigationUpdateCurrentEntryOptions options ); readonly attribute NavigationTransition transition readonly attribute NavigationActivation activation readonly attribute boolean canGoBack readonly attribute boolean canGoForward NavigationResult navigate USVString url optional NavigationNavigateOptions options = {}); NavigationResult reload optional NavigationReloadOptions options = {}); NavigationResult traverseTo DOMString key optional NavigationOptions options = {}); NavigationResult back optional NavigationOptions options = {}); NavigationResult forward optional NavigationOptions options = {}); attribute EventHandler onnavigate attribute EventHandler onnavigatesuccess attribute EventHandler onnavigateerror attribute EventHandler oncurrententrychange }; dictionary NavigationUpdateCurrentEntryOptions required any state }; dictionary NavigationOptions any info }; dictionary NavigationNavigateOptions NavigationOptions any state NavigationHistoryBehavior history = " auto "; }; dictionary NavigationReloadOptions NavigationOptions any state }; dictionary NavigationResult Promise NavigationHistoryEntry committed Promise NavigationHistoryEntry finished }; enum NavigationHistoryBehavior auto push replace }; Each Window has an associated API , which is a object. Upon creation of the Window object, its navigation API must be set to a new object created in the Window object's relevant realm The getter steps are to return this 's API 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 interface: Event handler Event handler event type onnavigate navigate onnavigatesuccess navigatesuccess onnavigateerror navigateerror oncurrententrychange currententrychange 7.2.6.3 Core infrastructure Each has an associated entry list , a list of NavigationHistoryEntry objects, initially empty. Each has an associated current entry index , an integer, initially −1. The current entry of a is the result of running the following steps: If has entries and events disabled , then return null. Assert 's current entry index is not −1. Return 's entry list 's current entry index ]. has entries and events disabled if the following steps return true: Let document be 's relevant global object 's associated Document If document is not fully active , then return true. If document 's is initial about:blank is true, then return true. If document 's origin is opaque , then return true. Return false. To get the navigation API entry index of a session history entry she within a Let index be 0. For each nhe of 's entry list If nhe 's session history entry is equal to she , then return index Increment index by 1. Return −1. A key type used throughout the navigation API is the NavigationType enumeration: enum NavigationType push replace reload traverse }; This captures the main web developer-visible types of "navigations", which (as noted elsewhere ) do not exactly correspond to this standard's singular navigate algorithm. The meaning of each value is the following: push Corresponds to calls to navigate where the history handling behavior ends up as " push ", or to history.pushState() replace Corresponds to calls to navigate where the history handling behavior ends up as " replace ", or to history.replaceState() reload Corresponds to calls to reload traverse Corresponds to calls to traverse the history by a delta The value space of the NavigationType enumeration is a superset of the value space of the specification-internal history handling behavior type. Several parts of this standard make use of this overlap, by passing in a history handling behavior to an algorithm that expects a NavigationType 7.2.6.4 Initializing and updating the entry list To initialize the navigation API entries for a new document given a , a list of session history entries newSHEs , and a session history entry initialSHE Assert 's entry list is empty Assert 's current entry index is −1. If has entries and events disabled , then return. For each newSHE of newSHEs Let newNHE be a new NavigationHistoryEntry created in the relevant realm of Set newNHE 's session history entry to newSHE Append newNHE to 's entry list newSHEs will have originally come from getting session history entries for the navigation API , and thus each newSHE will be contiguous same origin with initialSHE Set 's current entry index to the result of getting the navigation API entry index of initialSHE within To update the navigation API entries for reactivation given a , a list of session history entries newSHEs , and a session history entry reactivatedSHE If has entries and events disabled , then return. Let newNHEs be a new empty list Let oldNHEs be a clone of 's entry list For each newSHE of newSHEs Let newNHE be null. If oldNHEs contains NavigationHistoryEntry matchingOldNHE whose session history entry is newSHE , then: Set newNHE to matchingOldNHE Remove matchingOldNHE from oldNHEs Otherwise: Set newNHE to a new NavigationHistoryEntry created in the relevant realm of Set newNHE 's session history entry to newSHE Append newNHE to newNHEs newSHEs will have originally come from getting session history entries for the navigation API , and thus each newSHE will be contiguous same origin with reactivatedSHE By the end of this loop, all NavigationHistoryEntry s that remain in oldNHEs represent session history entries which have been disposed while the Document was in bfcache Set 's entry list to newNHEs Set 's current entry index to the result of getting the navigation API entry index of reactivatedSHE within Queue a global task on the navigation and traversal task source given 's relevant global object to run the following steps: For each disposedNHE of oldNHEs Fire an event named dispose at disposedNHE We delay these steps by a task to ensure that dispose events will fire after the pageshow event. This ensures that pageshow is the first event a page receives upon reactivation (However, the rest of this algorithm runs before the pageshow event fires. This ensures that navigation.entries() and navigation.currentEntry will have correctly-updated values during any pageshow event handlers.) To update the navigation API entries for a same-document navigation given a , a session history entry destinationSHE , and a NavigationType navigationType If has entries and events disabled , then return. Let oldCurrentNHE be the current entry of Let disposedNHEs be a new empty list If navigationType is " traverse ", then: Set 's current entry index to the result of getting the navigation API entry index of destinationSHE within Assert 's current entry index is not −1. This algorithm is only called for same-document traversals. Cross-document traversals will instead call either initialize the navigation API entries for a new document or update the navigation API entries for reactivation Otherwise, if navigationType is " push ", then: Set 's current entry index to 's current entry index + 1. Let be 's current entry index While 's entry list 's size Append 's entry list ] to disposedNHEs Set to + 1. Remove all items in disposedNHEs from 's entry list Otherwise, if navigationType is " replace ", then: Append oldCurrentNHE to disposedNHEs If navigationType is " push " or replace ", then: Let newNHE be a new NavigationHistoryEntry created in the relevant realm of Set newNHE 's session history entry to destinationSHE Set 's entry list 's current entry index ] to newNHE If 's ongoing API method tracker is non-null, then notify about the committed-to entry given 's ongoing API method tracker and the current entry of It is important to do this before firing the dispose or currententrychange events, since event handlers could start another navigation, or otherwise change the value of 's ongoing API method tracker Let navigateEvent be 's ongoing navigate event Let apiMethodTracker be 's ongoing API method tracker Prepare to run script given 's relevant settings object See the discussion for other navigation API events to understand why we do this. Fire an event named currententrychange at using NavigationCurrentEntryChangeEvent , with its navigationType attribute initialized to navigationType and its from initialized to oldCurrentNHE For each disposedNHE of disposedNHEs Fire an event named dispose at disposedNHE Run the navigate event intercept commit handler steps given navigateEvent , and apiMethodTracker Clean up after running script given 's relevant settings object In implementations, same-document navigations can cause session history entries to be disposed by falling off the back of the session history entry list. This is not yet handled by the above algorithm (or by any other part of this standard). See issue #8620 to track progress on defining the correct behavior in such cases. 7.2.6.5 The NavigationHistoryEntry interface Exposed Window interface NavigationHistoryEntry EventTarget readonly attribute USVString url readonly attribute DOMString key readonly attribute DOMString id readonly attribute long long index readonly attribute boolean sameDocument any getState (); attribute EventHandler ondispose }; entry url The URL of this navigation history entry. This can return null if the entry corresponds to a different Document than the current one (i.e., if sameDocument is false), and that Document was fetched with a referrer policy of no-referrer " or " origin ", since that indicates the Document in question is hiding its URL even from other same-origin pages. entry key A user agent-generated random UUID string representing this navigation history entry's place in the navigation history list. This value will be reused by other NavigationHistoryEntry instances that replace this one due to " replace " navigations, and will survive reloads and session restores. This is useful for navigating back to this entry in the navigation history list, using navigation.traverseTo(key) entry id A user agent-generated random UUID string representing this specific navigation history entry. This value will not be reused by other NavigationHistoryEntry instances. This value will survive reloads and session restores. This is useful for associating data with this navigation history entry using other storage APIs. entry index The index of this NavigationHistoryEntry within navigation.entries() , or −1 if the entry is not in the navigation history entry list. entry sameDocument Indicates whether or not this navigation history entry is for the same Document as the current one, or not. This will be true, for example, when the entry represents a fragment navigation or single-page app navigation. entry getState () Returns the deserialization of the state stored in this entry, which was added to the entry using navigation.navigate() or navigation.updateCurrentEntry() . This state survives reloads and session restores. Note that in general, unless the state value is a primitive, entry.getState() !== entry.getState() , since a fresh deserialization is returned each time. This state is unrelated to the classic history API's history.state Each NavigationHistoryEntry has an associated session history entry , which is a session history entry The key of a NavigationHistoryEntry nhe is given by the return value of the following algorithm: If nhe 's relevant global object 's associated Document is not fully active , then return the empty string. Return nhe 's session history entry 's navigation API key The ID of a NavigationHistoryEntry nhe is given by the return value of the following algorithm: If nhe 's relevant global object 's associated Document is not fully active , then return the empty string. Return nhe 's session history entry 's navigation API ID The index of a NavigationHistoryEntry nhe is given by the return value of the following algorithm: If nhe 's relevant global object 's associated Document is not fully active , then return −1. Return the result of getting the navigation API entry index of this 's session history entry within this 's relevant global object 's navigation API The url getter steps are: Let document be this 's relevant global object 's associated Document If document is not fully active , then return the empty string. Let she be this 's session history entry If she 's document does not equal document , and she 's document state 's request referrer policy is " no-referrer " or " origin ", then return null. Return she 's URL serialized The key getter steps are to return this 's key The id getter steps are to return this 's ID The index getter steps are to return this 's index The sameDocument getter steps are: Let document be this 's relevant global object 's associated Document If document is not fully active , then return false. Return true if this 's session history entry 's document equals document , and false otherwise. The getState() method steps are: If this 's relevant global object 's associated Document is not fully active , then return undefined. Return StructuredDeserialize this 's session history entry 's navigation API state ). Rethrow any exceptions. This can in theory throw an exception, if attempting to deserialize a large ArrayBuffer when not enough memory is available. 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 NavigationHistoryEntry interface: Event handler Event handler event type ondispose dispose 7.2.6.6 The history entry list entries entries() Returns an array of NavigationHistoryEntry instances represent the current navigation history entry list, i.e., all session history entries for this navigable that are same origin and contiguous to the current session history entry currentEntry Returns the NavigationHistoryEntry corresponding to the current session history entry updateCurrentEntry ({ state }) Updates the navigation API state of the current session history entry , without performing a navigation like navigation.reload() would do. This method is best used to capture updates to the page that have already happened, and need to be reflected into the navigation API state. For cases where the state update is meant to drive a page update, instead use navigation.navigate() or navigation.reload() , which will trigger a navigate event. canGoBack Returns true if the current current session history entry (i.e., currentEntry ) is not the first one in the navigation history entry list (i.e., in entries() ). This means that there is a previous session history entry for this navigable , and its document state 's origin is same origin with the current Document 's origin canGoForward Returns true if the current current session history entry (i.e., currentEntry ) is not the last one in the navigation history entry list (i.e., in entries() ). This means that there is a next session history entry for this navigable , and its document state 's origin is same origin with the current Document 's origin The entries() method steps are: If this has entries and events disabled , then return the empty list. Return this 's entry list Recall that because of Web IDL's sequence type conversion rules, this will create a new JavaScript array object on each call. That is, navigation.entries() !== navigation.entries() The currentEntry getter steps are to return the current entry of this The updateCurrentEntry( options method steps are: Let current be the current entry of this If current is null, then throw an InvalidStateError DOMException Let serializedState be StructuredSerializeForStorage options [" state "]), rethrowing any exceptions. Set current 's session history entry 's navigation API state to serializedState Fire an event named currententrychange at this using NavigationCurrentEntryChangeEvent , with its navigationType attribute initialized to null and its from initialized to current The canGoBack getter steps are: If this has entries and events disabled , then return false. Assert this 's current entry index is not −1. If this 's current entry index is 0, then return false. Return true. The canGoForward getter steps are: If this has entries and events disabled , then return false. Assert this 's current entry index is not −1. If this 's current entry index is equal to this 's entry list 's size − 1, then return false. Return true. 7.2.6.7 Initiating navigations committed finished } = navigate url committed finished } = navigate url options Navigates the current page to the given url options can contain the following values: history can be set to replace " to replace the current session history entry, instead of pushing a new one. info can be set to any value; it will populate the info property of the corresponding NavigateEvent state can be set to any serializable value; it will populate the state retrieved by navigation.currentEntry.getState() once the navigation completes, for same-document navigations. (It will be ignored for navigations that end up cross-document.) By default this will perform a full navigation (i.e., a cross-document navigation, unless the given URL differs only in a fragment from the current one). The navigateEvent.intercept() method can be used to convert it into a same-document navigation. The returned promises will behave as follows: For navigations that get aborted, both promises will reject with an AbortError DOMException For same-document navigations created by using the navigateEvent.intercept() method, committed will fulfill after the navigation commits, and finished will fulfill or reject according to any promsies returned by handlers passed to intercept() For other same-document navigations (e.g., non-intercepted fragment navigations ), both promises will fulfill immediately. For cross-document navigations, or navigations that result in 204 or 205 statuses or ` Content-Disposition: attachment ` header fields from the server (and thus do not actually navigate), both promises will never settle. In all cases, when the returned promises fulfill, it will be with the NavigationHistoryEntry that was navigated to. committed finished } = reload options Reloads the current page. options can contain info and state , which behave as described above. The default behavior of performing a from-network-or-cache reload of the current page can be overriden by the using the navigateEvent.intercept() method. Doing so will mean this call only updates state or passes along the appropriate info , plus performing whater actions the navigate event handlers see fit to carry out. The returned promises will behave as follows: If the reload is intercepted by using the navigateEvent.intercept() method, committed will fulfill after the navigation commits, and finished will fulfill or reject according to any promsies returned by handlers passed to intercept() Otherwise, both promises will never settle. committed finished } = traverseTo key committed finished } = traverseTo key , { info }) Traverses to the closest session history entry that matches the NavigationHistoryEntry with the given key info can be set to any value; it will populate the info property of the corresponding NavigateEvent If a traversal to that session history entry is already in progress, then this will return the promises for that original traversal, and info will be ignored. The returned promises will behave as follows: If there is no NavigationHistoryEntry in navigation.entries() whose key matches key , both promises will reject with an InvalidStateError DOMException For same-document traversals intercepted by the navigateEvent.intercept() method, committed will fulfill as soon as the traversal is processed and navigation.currentEntry is updated, and finished will fulfill or reject according to any promsies returned by the handlers passed to intercept() For non-intercepted same-document travesals, both promises will fulfill as soon as the traversal is processed and navigation.currentEntry is updated. For cross-document traversals, including attempted cross-document traversals that end up resulting in a 204 or 205 statuses or ` Content-Disposition: attachment ` header fields from the server (and thus do not actually traverse), both promises will never settle. committed finished } = back key committed finished } = back key , { info }) Traverses to the closest previous session history entry which results in this navigable traversing, i.e., which corresponds to a different NavigationHistoryEntry and thus will cause navigation.currentEntry to change. info can be set to any value; it will populate the info property of the corresponding NavigateEvent If a traversal to that session history entry is already in progress, then this will return the promises for that original traversal, and info will be ignored. The returned promises behave equivalently to those returned by traverseTo() committed finished } = forward key committed finished } = forward key , { info }) Traverses to the closest forward session history entry which results in this navigable traversing, i.e., which corresponds to a different NavigationHistoryEntry and thus will cause navigation.currentEntry to change. info can be set to any value; it will populate the info property of the corresponding NavigateEvent If a traversal to that session history entry is already in progress, then this will return the promises for that original traversal, and info will be ignored. The returned promises behave equivalently to those returned by traverseTo() The navigate( url options method steps are: Let urlRecord be the result of parsing a URL given url , relative to this 's relevant settings object If urlRecord is failure, then return an early error result for a SyntaxError DOMException If urlRecord 's scheme is " javascript ", then return an early error result for a NotSupportedError DOMException Let document be this 's relevant global object 's associated Document If options [" history "] is " push ", and the navigation must be a replace given urlRecord and document , then return an early error result for a NotSupportedError DOMException Let state be options [" state "], if it exists ; otherwise, undefined. Let serializedState be StructuredSerializeForStorage state ). If this throws an exception, then return an early error result for that exception. It is important to perform this step early, since serialization can invoke web developer code, which in turn might change various things we check in later steps. If document is not fully active , then return an early error result for an InvalidStateError DOMException If document 's unload counter is greater than 0, then return an early error result for an InvalidStateError DOMException Let info be options [" info "], if it exists otherwise, undefined. Let apiMethodTracker be the result of setting up a navigate/reload API method tracker for this given info and serializedState Navigate document 's node navigable to urlRecord using document , with historyHandling set to options [" history "], navigationAPIState set to serializedState , and apiMethodTracker set to apiMethodTracker Unlike location.assign() and friends, which are exposed across origin-domain boundaries, navigation.navigate() can only be accessed by code with direct synchronous access to the window.navigation property. Thus, we avoid the complications about attributing the source document of the navigation, and we don't need to deal with the allowed by sandboxing to navigate check and its acccompanying exceptionsEnabled flag. We just treat all navigations as if they come from the Document corresponding to this object itself (i.e., document ). Return a navigation API method tracker-derived result for apiMethodTracker The reload( options method steps are: Let document be this 's relevant global object 's associated Document Let serializedState be StructuredSerializeForStorage (undefined). If options [" state "] exists , then set serializedState to StructuredSerializeForStorage options [" state "]). If this throws an exception, then return an early error result for that exception. It is important to perform this step early, since serialization can invoke web developer code, which in turn might change various things we check in later steps. Otherwise: Let current be the current entry of this If current is not null, then set serializedState to current 's session history entry 's navigation API state If document is not fully active , then return an early error result for an InvalidStateError DOMException If document 's unload counter is greater than 0, then return an early error result for an InvalidStateError DOMException Let info be options [" info "], if it exists otherwise, undefined. Let apiMethodTracker be the result of setting up a navigate/reload API method tracker for this given info and serializedState Reload document 's node navigable with navigationAPIState set to serializedState and apiMethodTracker set to apiMethodTracker Return a navigation API method tracker-derived result for apiMethodTracker The traverseTo( key options method steps are: If this 's current entry index is −1, then return an early error result for an InvalidStateError DOMException If this 's entry list does not contain NavigationHistoryEntry whose session history entry 's API key equals key , then return an early error result for an InvalidStateError DOMException Return the result of performing a navigation API traversal given this key , and options The back( options method steps are: If this 's current entry index is −1 or 0, then return an early error result for an InvalidStateError DOMException Let key be this 's entry list this 's current entry index − 1]'s session history entry 's navigation API key Return the result of performing a navigation API traversal given this key , and options The forward( options method steps are: If this 's current entry index is −1 or is equal to this 's entry list 's size 1, then return an early error result for an InvalidStateError DOMException Let key be this 's entry list this 's current entry index + 1]'s session history entry 's navigation API key Return the result of performing a navigation API traversal given this key , and options To perform a navigation API traversal given a , a string key , and a NavigationOptions options Let document be 's relevant global object 's associated Document If document is not fully active , then return an early error result for an InvalidStateError DOMException If document 's unload counter is greater than 0, then return an early error result for an InvalidStateError DOMException Let current be the current entry of If key equals current 's session history entry 's navigation API key , then return «[ committed " → a promise resolved with current , " finished a promise resolved with current ]». If 's upcoming traverse API method trackers key exists , then return a navigation API method tracker-derived result for 's upcoming traverse API method trackers key ]. Let info be options [" info "], if it exists otherwise, undefined. Let apiMethodTracker be the result of adding an upcoming traverse API method tracker for given key and info Let navigable be document 's node navigable Let traversable be navigable 's traversable navigable Let sourceSnapshotParams be the result of snapshotting source snapshot params given document Append the following session history traversal steps to traversable Let navigableSHEs be the result of getting session history entries given navigable Let targetSHE be the session history entry in navigableSHEs whose navigation API key is key . If no such entry exists, then: Queue a global task on the navigation and traversal task source given 's relevant global object to reject the finished promise for apiMethodTracker with an InvalidStateError DOMException Abort these steps. This path is taken if 's entry list was outdated compared to navigableSHEs , which can occur for brief periods while all the relevant threads and processes are being synchronized in reaction to a history change. If targetSHE is navigable 's active session history entry , then: Queue a global task on the navigation and traversal task source given 's relevant global object to reject the finished promise for apiMethodTracker with an InvalidStateError DOMException Abort these steps. This can occur if a previously queued traversal already took us to this session history entry Let result be the result of applying the traverse history step given by targetSHE 's step to traversable , given sourceSnapshotParams navigable , and " none ". If result is " canceled-by-beforeunload ", then queue a global task on the navigation and traversal task source given 's relevant global object to reject the finished promise for apiMethodTracker with a new AbortError DOMException created in 's relevant realm If result is " initiator-disallowed ", then queue a global task on the navigation and traversal task source given 's relevant global object to reject the finished promise for apiMethodTracker with a new SecurityError DOMException created in 's relevant realm When result is " canceled-by-beforeunload " or " initiator-disallowed ", the navigate event was never fired, aborting the ongoing would not be correct; it would result in a navigateerror event without a preceding navigate event. In the " canceled-by-navigate " case, navigate is fired, but the inner navigate event firing algorithm will take care of aborting the ongoing navigation Return a navigation API method tracker-derived result for apiMethodTracker An early error result for an exception is a NavigationResult dictionary instance given by «[ " committed " → a promise rejected with , " finished " → a promise rejected with ]». To compute the navigation API method tracker-derived result for a API method tracker -or-null apiMethodTracker If apiMethodTracker is pending , then return an early error result for an AbortError DOMException Return a NavigationResult dictionary instance given by «[ " committed " → apiMethodTracker 's committed promise , " finished " → apiMethodTracker 's finished promise ]». 7.2.6.8 Ongoing navigation tracking During any given navigation (in the broad sense of the word ), the object needs to keep track of the following: For all navigations State Duration Explanation The NavigateEvent For the duration of event firing So that if the navigation is canceled while the event is firing, we can cancel the event The event's abort controller Until all promises returned from handlers passed to intercept() have settled So that if the navigation is canceled, we can signal abort Whether a new element was focused Until all promises returned from handlers passed to intercept() have settled So that if one was, focus is not reset The NavigationHistoryEntry being navigated to From when it is determined, until all promises returned from handlers passed to intercept() have settled So that we know what to resolve any committed and finished promises with Any finished promise that was returned Until all promises returned from handlers passed to intercept() have settled So that we can resolve or reject it appropriately For non-" traverse " navigations State Duration Explanation Any state For the duration of event firing So that we can update the current entry's navigation API state if the event finishes firing without being canceled For " traverse " navigations State Duration Explanation Any info Until the task is queued to fire the navigate event So that we can use it to fire the navigate after the trip through the session history traversal queue Any committed promise that was returned Until the session history is updated (inside that same task) So that we can resolve or reject it appropriately Whether intercept() was called Until the session history is updated (inside that same task) So that we can suppress the normal scroll restoration logic in favor of the behavior given by the scroll option We also cannot assume there is only a single navigation requested at any given time, due to web developer code such as: const p1 navigate url1 ). finished const p2 navigate url2 ). finished That is, in this scenario, we need to ensure that while navigating to url2 , we still have the promise p1 around so that we can reject it. We can't just get rid of any ongoing navigation promises the moment the second call to navigate() happens. We end up accomplishing all this by associating the following with each Ongoing navigate event , a NavigateEvent or null, initially null. Focus changed during ongoing navigation , a boolean, initially false. Suppress normal scroll restoration during ongoing navigation , a boolean, initially false. Ongoing API method tracker , a navigation API method tracker or null, initially null. Upcoming traverse API method trackers , an ordered map from strings to navigation API method trackers , initially empty. The state here that is not stored in navigation API method trackers is state which needs to be tracked even for navigations that are not initiated via navigation API methods. navigation API method tracker is a struct with the following items navigation object , a key , a string or null An info , a JavaScript value serialized state , a serialized state or null committed-to entry NavigationHistoryEntry or null committed promise , a promise finished promise , a promise pending , a boolean. All this state is then managed via the following algorithms. To set up a navigate/reload API method tracker given a , a JavaScript value info , and a serialized state -or-null serializedState Let committedPromise and finishedPromise be new promises created in 's relevant realm Mark as handled finishedPromise The web developer doesn’t necessarily care about finishedPromise being rejected: They might only care about committedPromise They could be doing multiple synchronous navigations within the same task, in which case all but the last will be aborted (causing their finishedPromise to reject). This could be an application bug, but also could just be an emergent feature of disparate parts of the application overriding each others' actions. They might prefer to listen to other transition-failure signals instead of finishedPromise , e.g., the navigateerror event, or the navigation.transition.finished promise. As such, we mark it as handled to ensure that it never triggers unhandledrejection events. Return a new navigation API method tracker with: navigation object key null info info serialized state serializedState committed-to entry null committed promise committedPromise finished promise finishedPromise pending false if has entries and events disabled ; otherwise true To add an upcoming traverse API method tracker given a , a string destinationKey , and a JavaScript value info Let committedPromise and finishedPromise be new promises created in 's relevant realm Mark as handled finishedPromise See the previous discussion about why this is done. Let apiMethodTracker be a new navigation API method tracker with: navigation object key destinationKey info info serialized state null committed-to entry null committed promise committedPromise finished promise finishedPromise pending false Set 's upcoming traverse API method trackers destinationKey ] to apiMethodTracker Return apiMethodTracker To clean up navigation API method tracker apiMethodTracker Let be apiMethodTracker 's navigation object If 's ongoing API method tracker is apiMethodTracker , then set 's ongoing API method tracker to null. Otherwise: Let key be apiMethodTracker 's key Assert key is not null. Assert 's upcoming traverse API method trackers key exists Remove 's upcoming traverse API method trackers key ]. To notify about the committed-to entry given a navigation API method tracker apiMethodTracker and a NavigationHistoryEntry nhe Set apiMethodTracker 's committed-to entry to nhe If apiMethodTracker 's serialized state is not null, then set nhe 's session history entry 's navigation API state to apiMethodTracker 's serialized state If it's null, then we're traversing to nhe via navigation.traverseTo() , which does not allow changing the state. At this point, apiMethodTracker 's serialized state is no longer needed. Implementations might want to clear it out to avoid keeping it alive for the lifetime of the navigation API method tracker Resolve apiMethodTracker 's committed promise with nhe At this point, apiMethodTracker 's committed promise is only needed in cases where it has not yet been returned to author code. Implementations might want to clear it out to avoid keeping it alive for the lifetime of the navigation API method tracker To resolve the finished promise for a navigation API method tracker apiMethodTracker Assert apiMethodTracker 's committed-to entry is not null. Resolve apiMethodTracker 's finished promise with its committed-to entry Clean up apiMethodTracker To reject the finished promise for a navigation API method tracker apiMethodTracker with a JavaScript value exception Reject apiMethodTracker 's committed promise with exception This will do nothing if apiMethodTracker 's committed promise was previously resolved via notify about the committed-to entry Reject apiMethodTracker 's finished promise with exception Clean up apiMethodTracker To abort the ongoing navigation given a and an optional DOMException error Let event be 's ongoing navigate event Assert event is not null. Set 's focus changed during ongoing navigation to false. Set 's suppress normal scroll restoration during ongoing to false. If error was not given, then let error be a new AbortError DOMException created in 's relevant realm If event 's dispatch flag is set, then set event 's canceled flag to true. Abort event given error To abort a NavigateEvent event given reason Let be event 's relevant global object 's navigation API Signal abort on event 's abort controller given reason Let errorInfo be the result of extracting error information from reason For example, if this algorithm is reached because of a call to window.stop() , these properties would probably end up initialized based on the line of script that called window.stop() . But if it's because the user clicked the stop button, these properties would probably end up with default values like the empty string or 0. Set 's ongoing navigate event to null. If 's ongoing API method tracker is non-null, then reject the finished promise for apiMethodTracker with reason Fire an event named navigateerror at using ErrorEvent , with additional attributes initialized according to errorInfo If 's transition is null, then return. Reject 's transition 's committed promise with reason Reject 's transition 's finished promise with reason Set 's transition to null. To inform the navigation API about aborting navigation in a navigable navigable If this algorithm is running on navigable 's active window 's relevant agent 's event loop , then continue on to the following steps. Otherwise, queue a global task on the navigation and traversal task source given navigable 's active window to run the following steps. Let be navigable 's active window 's navigation API While 's ongoing navigate event is not null: Abort the ongoing navigation given If there is an ongoing cross-document navigation, this means it will be signaled to the navigation API as aborted, e.g., by firing navigateerror events. This is somewhat accurate, since the next navigation the Document experiences will be this same-document navigation, so a developer which was expecting the next navigation completion to be that of the cross-document navigation gets a useful signal that this did not happen. However, it is also somewhat inaccurate, as the browser will continue to process the ongoing cross-document navigation (applying it after this same-document one synchronously finishes). Ultimately, the navigation API gets a bit messy with overlapping cross- and same-document navigations, as the ongoing navigation tracking machinery and APIs are built to expose only a single ongoing navigation. Web developers will be best-served if they do not create such overlapping situations, e.g., by await ing promises returned from navigation.navigate() before starting new navigations. This is a loop, since abort the ongoing navigation can run JavaScript (e.g., via the navigateerror event), which might start a new navigation. Since such a newly-started navigation will be superseded by the completion of this navigation, it gets signaled to the navigation API as aborted. To inform the navigation API about child navigable destruction given a navigable navigable Inform the navigation API about aborting navigation in navigable Let be navigable 's active window 's navigation API Let traversalAPIMethodTrackers be a clone of 's upcoming traverse API method trackers For each apiMethodTracker of traversalAPIMethodTrackers reject the finished promise for apiMethodTracker with a new AbortError DOMException created in 's relevant realm The ongoing navigation concept is most-directly exposed to web developers through the navigation.transition property, which is an instance of the NavigationTransition interface: Exposed Window interface NavigationTransition readonly attribute NavigationType navigationType readonly attribute NavigationHistoryEntry from readonly attribute NavigationDestination to readonly attribute Promise undefined committed readonly attribute Promise undefined finished }; transition NavigationTransition representing any ongoing navigation that hasn't yet reached the navigatesuccess or navigateerror stage, if one exists; or null, if there is no such transition ongoing. Since navigation.currentEntry (and other properties like location.href ) are updated immediately upon navigation, this navigation.transition property is useful for determining when such navigations are not yet fully settled, according to any handlers passed to navigateEvent.intercept() transition navigationType One of " push ", " replace ", " reload ", or " traverse ", indicating what type of navigation this transition is for. transition from The NavigationHistoryEntry from which the transition is coming. This can be useful to compare against navigation.currentEntry transition to The NavigationDestination of the transition. This can be useful as a way to reflect a current navigation's destination's url without having to listen to the navigate event. transition committed A promise which fulfills once the navigation.currentEntry and URL change. This occurs after all of its precommit handlers are fulfilled. The promise rejects if one or more of the precommit handlers rejects. transition finished A promise which fulfills at the same time as the navigatesuccess fires, or rejects at the same time the navigateerror event fires. Each has a transition , which is a NavigationTransition or null, initially null. The transition getter steps are to return this 's transition Each NavigationTransition has an associated navigation type , which is a NavigationType Each NavigationTransition has an associated from entry , which is a NavigationHistoryEntry Each NavigationTransition has an associated destination , which is a NavigationDestination Each NavigationTransition has an associated committed promise , which is a promise. Each NavigationTransition has an associated finished promise , which is a promise. The navigationType getter steps are to return this 's type The from getter steps are to return this 's from entry The to getter steps are to return this 's destination The committed getter steps are to return this 's committed promise The finished getter steps are to return this 's finished promise 7.2.6.9 The NavigationActivation interface Exposed Window interface NavigationActivation readonly attribute NavigationHistoryEntry from readonly attribute NavigationHistoryEntry entry readonly attribute NavigationType navigationType }; activation NavigationActivation containing information about the most recent cross-document navigation, the navigation that "activated" this Document While navigation.currentEntry and the Document 's URL can be updated regularly due to same-document navigations, navigation.activation stays constant, and its properties are only updated if the Document is reactivated from history. activation entry NavigationHistoryEntry , equivalent to the value of the navigation.currentEntry property at the moment the Document was activated. activation from NavigationHistoryEntry , representing the Document that was active right before the current Document . This will have a value null in case the previous Document was not same origin with this one or if it was the initial about:blank Document There are some cases in which either the from or entry NavigationHistoryEntry objects would not be viable targets for the traverseTo() method, as they might not be retained in history. For example, the Document can be activated using location.replace() or its initial entry could be replaced by history.replaceState() . However, those entries' url property and getState() method are still accessible. activation navigationType One of " push ", " replace ", " reload ", or " traverse ", indicating what type of navigation activated this Document Each has an associated activation , which is null or a NavigationActivation object, initially null. Each NavigationActivation has: old entry , null or a NavigationHistoryEntry new entry , null or a NavigationHistoryEntry navigation type , a NavigationType The activation getter steps are to return this 's activation The from getter steps are to return this 's old entry The entry getter steps are to return this 's new entry The navigationType getter steps are to return this 's navigation type 7.2.6.10 The navigate event A major feature of the navigation API is the navigate event. This event is fired on any navigation (in the broad sense of the word ), allowing web developers to monitor such outgoing navigations. In many cases, the event is cancelable , which allows preventing the navigation from happening. And in others, the navigation can be intercepted and replaced with a same-document navigation by using the intercept() method of the NavigateEvent class. 7.2.6.10.1 The NavigateEvent interface Exposed Window interface NavigateEvent Event constructor DOMString type NavigateEventInit eventInitDict ); readonly attribute NavigationType navigationType readonly attribute NavigationDestination destination readonly attribute boolean canIntercept readonly attribute boolean userInitiated readonly attribute boolean hashChange readonly attribute AbortSignal signal readonly attribute FormData formData readonly attribute DOMString downloadRequest readonly attribute any info readonly attribute boolean hasUAVisualTransition readonly attribute Element sourceElement undefined intercept optional NavigationInterceptOptions options = {}); undefined scroll (); }; dictionary NavigateEventInit EventInit NavigationType navigationType = " push "; required NavigationDestination destination boolean canIntercept false boolean userInitiated false boolean hashChange false required AbortSignal signal FormData formData null DOMString downloadRequest null any info boolean hasUAVisualTransition false Element sourceElement null }; dictionary NavigationInterceptOptions NavigationPrecommitHandler precommitHandler NavigationInterceptHandler handler NavigationFocusReset focusReset NavigationScrollBehavior scroll }; enum NavigationFocusReset after-transition manual }; enum NavigationScrollBehavior after-transition manual }; callback NavigationInterceptHandler Promise undefined > (); event navigationType One of " push ", " replace ", " reload ", or " traverse ", indicating what type of navigation this is. event destination NavigationDestination representing the destination of the navigation. event canIntercept True if intercept() can be called to intercept this navigation and convert it into a same-document navigation, replacing its usual behavior; false otherwise. Generally speaking, this will be true whenever the current Document can have its URL rewritten to the destination URL, except for in the case of cross-document traverse " navigations, where it will always be false. event userInitiated True if this navigation was due to a user clicking on an element, submitting a form element, or using the browser UI to navigate; false otherwise. event hashChange True for a fragment navigation ; false otherwise. event signal An AbortSignal which will become aborted if the navigation gets canceled, e.g., by the user pressing their browser's "Stop" button, or by another navigation interrupting this one. The expected pattern is for developers to pass this along to any async operations, such as fetch() , which they perform as part of handling this navigation. event formData The FormData representing the submitted form entries for this navigation, if this navigation is a " push " or " replace " navigation representing a POST form submission ; null otherwise. (Notably, this will be null even for " reload or " traverse " navigations that are revisiting session history entry that was originally created from a form submission.) event downloadRequest Represents whether or not this navigation was requested to be a download, by using an or area element's attribute: If a download was not requested, then this property is null. If a download was requested, returns the filename that was supplied as the attribute's value. (This could be the empty string.) Note that a download being requested does not always mean that a download will happen: for example, a download might be blocked by browser security policies, or end up being treated as a push " navigation for unspecified reasons Similarly, a navigation might end up being a download even if it was not requested to be one, due to the destination server responding with a ` Content-Disposition: attachment ` header. Finally, note that the navigate event will not fire at all for downloads initiated using browser UI affordances, e.g., those created by right-clicking and choosing to save the target of a link. event info An arbitrary JavaScript value passed via one of the navigation API methods which initiated this navigation, or undefined if the navigation was initiated by the user or by a different API. event hasUAVisualTransition Returns true if the user agent performed a visual transition for this navigation before dispatching this event. If true, the best user experience will be given if the author synchronously updates the DOM to the post-navigation state. event sourceElement Returns the Element responsible for this navigation. This can be an or area element, a submit button , or a submitted form element. event intercept ({ precommitHandler handler focusReset scroll }) Intercepts this navigation, preventing its normal handling and instead converting it into a same-document navigation of the same type to the destination URL. The precommitHandler option can be a function that accepts a NavigationPrecommitController and returns a promise. The precommit handler function will run after the navigate event has finished firing, but before the navigation.currentEntry property has been updated. Returning a rejected promise will abort the navigation and its effect, such as updating the URL and session history. After all the precommit handlers are fulfilled, the navigation can proceed to commit and call the rest of the handlers. The precommitHandler option can only be passed when the event is cancelable : trying to pass a precommitHandler to a non-cancelable NavigateEvent will throw a SecurityError DOMException The handler option can be a function that returns a promise. The handler function will run after the navigate event has finished firing and the navigation.currentEntry property has been updated. This returned promise is used to signal the duration, and success or failure, of the navigation. After it settles, the browser signals to the user (e.g., via a loading spinner UI, or assistive technology) that the navigation is finished. Additionally, it fires navigatesuccess or navigateerror events as appropriate, which other parts of the web application can respond to. By default, using this method will cause focus to reset when any handlers' returned promises settle. Focus will be reset to the first element with the autofocus attribute set, or the body element if the attribute isn't present. The focusReset option can be set to " manual " to avoid this behavior. By default, using this method will delay the browser's scroll restoration logic for " traverse " or " reload " navigations, or its scroll-reset/scroll-to-a-fragment logic for " push or " replace " navigations, until any handlers' returned promises settle. The scroll option can be set to " manual " to turn off any browser-driven scroll behavior entirely for this navigation, or scroll() can be called before the promise settles to trigger this behavior early. This method will throw a SecurityError DOMException if canIntercept is false, or if isTrusted is false. It will throw an InvalidStateError DOMException if not called synchronously, during event dispatch. event scroll () For " traverse " or " reload " navigations, restores the scroll position using the browser's usual scroll restoration logic. For " push " or " replace " navigations, either resets the scroll position to the top of the document or scrolls to the fragment specified by destination.url if there is one. If called more than once, or called after automatic post-transition scroll processing has happened due to the scroll option being left as " after-transition ", or called before the navigation has committed, this method will throw an InvalidStateError DOMException Each NavigateEvent has an interception state , which is either " none ", " intercepted ", " committed ", scrolled ", or " finished ", initially " none ". Each NavigateEvent has a navigation precommit handler list , a list of NavigationPrecommitHandler callbacks, initially empty. Each NavigateEvent has a navigation handler list , a list of NavigationInterceptHandler callbacks, initially empty. Each NavigateEvent has a focus reset behavior , a NavigationFocusReset -or-null, initially null. Each NavigateEvent has a scroll behavior , a NavigationScrollBehavior -or-null, initially null. Each NavigateEvent has an abort controller , an AbortController -or-null, initially null. Each NavigateEvent has a classic history API state , a serialized state or null. It is only used in some cases where the event's navigationType is " push " or " replace ", and is set appropriately when the event is fired The navigationType destination canIntercept userInitiated hashChange signal formData downloadRequest info hasUAVisualTransition , and sourceElement attributes must return the values they are initialized to. The intercept( options method steps are: Perform shared checks given this If this 's canIntercept attribute was initialized to false, then throw a SecurityError DOMException If this 's dispatch flag is unset, then throw an InvalidStateError DOMException If options [" precommitHandler "] exists , then: If this 's cancelable attribute is initialized to false, then throw an InvalidStateError DOMException Append options [" precommitHandler "] to this 's navigation precommit handler list Assert this 's interception state is either " none " or " intercepted ". Set this 's interception state to " intercepted ". If options [" handler "] exists , then append it to this 's navigation handler list If options [" focusReset "] exists , then: If this 's focus reset behavior is not null, and it is not equal to options [" focusReset "], then the user agent may report a warning to the console indicating that the focusReset option for a previous call to intercept() was overridden by this new value, and the previous value will be ignored. Set this 's focus reset behavior to options [" focusReset "]. If options [" scroll "] exists , then: If this 's scroll behavior is not null, and it is not equal to options [" scroll "], then the user agent may report a warning to the console indicating that the scroll option for a previous call to intercept() was overridden by this new value, and the previous value will be ignored. Set this 's scroll behavior to options [" scroll "]. The scroll() method steps are: Perform shared checks given this If this 's interception state is not " committed ", then throw an InvalidStateError DOMException Process scroll behavior given this To perform shared checks for a NavigateEvent event If event 's relevant global object 's associated Document is not fully active , then throw an InvalidStateError DOMException If event 's isTrusted attribute was initialized to false, then throw a SecurityError DOMException If event 's canceled flag is set, then throw an InvalidStateError DOMException 7.2.6.10.2 The NavigationPrecommitController interface Exposed Window interface NavigationPrecommitController undefined redirect USVString url optional NavigationNavigateOptions options = {}); undefined addHandler NavigationInterceptHandler handler ); }; callback NavigationPrecommitHandler Promise undefined > ( NavigationPrecommitController controller ); precommitController redirect (USVString url NavigationNavigateOptions options For " push " or " replace " navigations, sets the destination.url to url If options is given, also sets the info and the resulting NavigationHistoryEntry 's state to options 's info and state , if they are present. The history option can also switch between push " or " replace " navigations types. For " reload " or " traverse " navigations, an InvalidStateError will be thrown. If the current Document cannot have its URL rewritten to url , a SecurityError DOMException will be thrown. precommitController addHandler NavigationInterceptHandler handler Adds a NavigationInterceptHandler callback that would be called once the navigation is committed, as if this method was passed to the navigateEvent.intercept() method as a handler Each NavigationPrecommitController has a NavigateEvent event The redirect( url options method steps are: Assert this 's event 's interception state is not " none ". Perform shared checks given this 's event If this 's event 's interception state is not " intercepted ", then throw an InvalidStateError DOMException If this 's event 's navigationType is neither " push " nor " replace ", then throw an InvalidStateError DOMException Let document be this 's relevant global object 's associated Document Let destinationURL be the result of parsing url given document If destinationURL is failure, then throw a SyntaxError DOMException If document cannot have its URL rewritten to destinationURL , then throw a SecurityError DOMException If options [" history "] is " push " or " replace ", then set this 's event 's navigationType to options [" history "]. If options [" state "] exists , then: Let serializedState be the result of calling StructuredSerializeForStorage options [" state "]). This may throw an exception. Set this 's event 's destination 's state to serializedState Set this 's event 's target 's ongoing API method tracker 's serialized state to serializedState Set this 's event 's destination 's URL to destinationURL If options [" info "] exists , then set this 's event 's info to options [" info "]. The addHandler( handler ,) method steps are: Assert this 's event 's interception state is not " none ". Perform shared checks given this 's event If this 's event 's interception state is not " intercepted ", then throw an InvalidStateError DOMException Append handler to this 's event 's navigation handler list 7.2.6.10.3 The NavigationDestination interface Exposed Window interface NavigationDestination readonly attribute USVString url readonly attribute DOMString key readonly attribute DOMString id readonly attribute long long index readonly attribute boolean sameDocument any getState (); }; event destination url The URL being navigated to. event destination key The value of the key property of the destination NavigationHistoryEntry , if this is a " traverse " navigation, or the empty string otherwise. event destination id The value of the id property of the destination NavigationHistoryEntry , if this is a " traverse " navigation, or the empty string otherwise. event destination index The value of the index property of the destination NavigationHistoryEntry , if this is a " traverse " navigation, or −1 otherwise. event destination sameDocument Indicates whether or not this navigation is to the same Document as the current one, or not. This will be true, for example, in the case of fragment navigations or history.pushState() navigations. Note that this property indicates the original nature of the navigation. If a cross-document navigation is converted into a same-document navigation using navigateEvent.intercept() , that will not change the value of this property. event destination getState () For " traverse " navigations, returns the deserialization of the state stored in the destination session history entry For " push " or " replace " navigations, returns the deserialization of the state passed to navigation.navigate() , if the navigation was initiated by that method, or undefined it if it wasn't. For " reload " navigations, returns the deserialization of the state passed to navigation.reload() , if the reload was initiated by that method, or undefined it if it wasn't. Each NavigationDestination has a URL , which is a URL Each NavigationDestination has an entry , which is a NavigationHistoryEntry or null. It will be non-null if and only if the NavigationDestination corresponds to a " traverse " navigation. Each NavigationDestination has a state , which is a serialized state Each NavigationDestination has an is same document , which is a boolean. The url getter steps are to return this 's URL serialized The key getter steps are: If this 's entry is null, then return the empty string. Return this 's entry 's key The id getter steps are: If this 's entry is null, then return the empty string. Return this 's entry 's ID The index getter steps are: If this 's entry is null, then return −1. Return this 's entry 's index The sameDocument getter steps are to return this 's is same document The getState() method steps are to return StructuredDeserialize this 's state ). 7.2.6.10.4 Firing the event Other parts of the standard fire the navigate event, through a series of wrapper algorithms given in this section. To fire a traverse navigate event at a given a session history entry destinationSHE and an optional user navigation involvement userInvolvement (default " none "): Let event be the result of creating an event given NavigateEvent , in 's relevant realm Set event 's classic history API state to null. Let destination be a new NavigationDestination created in 's relevant realm Set destination 's URL to destinationSHE 's URL Let destinationNHE be the NavigationHistoryEntry in 's entry list whose session history entry is destinationSHE , or null if no such NavigationHistoryEntry exists. If destinationNHE is non-null, then: Set destination 's entry to destinationNHE Set destination 's state to destinationSHE 's navigation API state Otherwise, Set destination 's entry to null. Set destination 's state to StructuredSerializeForStorage (null). Set destination 's is same document to true if destinationSHE 's document is equal to 's relevant global object 's associated Document otherwise false. Return the result of performing the inner navigate event firing algorithm given , " traverse ", event destination userInvolvement , null, null, and null. To fire a push/replace/reload navigate event at given a NavigationType navigationType , a URL destinationURL , a boolean isSameDocument , an optional user navigation involvement userInvolvement (default " none "), an optional Element -or-null sourceElement (default null), an optional entry list -or-null formDataEntryList (default null), an optional serialized state navigationAPIState (default StructuredSerializeForStorage (null)), an optional serialized state -or-null classicHistoryAPIState (default null), and an optional navigation API method tracker -or-null apiMethodTracker Let document be 's relevant global object 's associated Document Inform the navigation API about aborting navigation in document 's node navigable If has entries and events disabled , and apiMethodTracker is not null: Set apiMethodTracker 's pending to false. Set apiMethodTracker to null. If has entries and events disabled , then navigate() and reload() calls return promises that will never fulfill. We never create a NavigationHistoryEntry object for such Document s, there is no NavigationHistoryEntry to apply serializedState to, and there is no navigate event to include info with. So, we don't need to track this API method call after all. We need to check this after aborting previous navigations, in case the Document has became non- fully active as a result of a navigateerror event. If document is not fully active , then return false. Let event be the result of creating an event given NavigateEvent , in 's relevant realm Set event 's classic history API state to classicHistoryAPIState Let destination be a new NavigationDestination created in 's relevant realm Set destination 's URL to destinationURL Set destination 's entry to null. Set destination 's state to navigationAPIState Set destination 's is same document to isSameDocument Return the result of performing the inner navigate event firing algorithm given navigationType event destination userInvolvement sourceElement formDataEntryList , null, and apiMethodTracker To fire a download request navigate event at a given a URL destinationURL , a user navigation involvement userInvolvement , an Element -or-null sourceElement , and a string filename Let event be the result of creating an event given NavigateEvent , in 's relevant realm Set event 's classic history API state to null. Let destination be a new NavigationDestination created in 's relevant realm Set destination 's URL to destinationURL Set destination 's entry to null. Set destination 's state to StructuredSerializeForStorage (null). Set destination 's is same document to false. Return the result of performing the inner navigate event firing algorithm given , " push ", event destination userInvolvement sourceElement , null, and filename The inner navigate event firing algorithm consists of the following steps, given a , a NavigationType navigationType , a NavigateEvent event , a NavigationDestination destination , a user navigation involvement userInvolvement , an Element -or-null sourceElement , an entry list -or-null formDataEntryList , a string-or-null downloadRequestFilename , and an optional navigation API method tracker -or-null apiMethodTracker (default null): If has entries and events disabled , then: Assert 's ongoing API method tracker is null. Assert 's upcoming traverse API method trackers is empty Assert apiMethodTracker is null. Return true. These assertions holds because traverseTo() back() , and forward() will immediately fail when entries and events are disabled (since there are no entries to traverse to). Assert 's ongoing API method tracker is null. If destination 's entry is non-null: Assert apiMethodTracker is null. apiMethodTracker is passed as an argument only for navigate() and reload() calls. Let destinationKey be destination 's entry 's key Assert destinationKey is not the empty string. If 's upcoming traverse API method trackers destinationKey exists Set apiMethodTracker to 's upcoming traverse API method trackers destinationKey ]. Remove 's upcoming traverse API method trackers destinationKey ]. If apiMethodTracker is not null: Set 's ongoing API method tracker to apiMethodTracker Set apiMethodTracker 's pending to false. Let navigable be 's relevant global object 's navigable Let document be 's relevant global object 's associated Document If document can have its URL rewritten to destination 's URL , and either destination 's is same document is true or navigationType is not " traverse ", then initialize event 's canIntercept to true. Otherwise, initialize it to false. Let traverseCanBeCanceled be true if all of the following are true: navigable is a top-level traversable destination 's is same document is true; and either userInvolvement is not " browser UI ", or 's relevant global object has history-action activation Otherwise, let it be false. If either: navigationType is not " traverse "; or traverseCanBeCanceled is true, then initialize event 's cancelable to true. Otherwise, initialize it to false. Initialize event 's type to " navigate ". Initialize event 's navigationType to navigationType Initialize event 's destination to destination Initialize event 's downloadRequest to downloadRequestFilename If apiMethodTracker is not null, then initialize event 's info to apiMethodTracker 's info . Otherwise, initialize it to undefined. At this point apiMethodTracker 's info is no longer needed and can be nulled out instead of keeping it alive for the lifetime of the navigation API method tracker Initialize event 's hasUAVisualTransition to true if a visual transition, to display a cached rendered state of the document 's latest entry , was done by the user agent. Otherwise, initialize it to false. Initialize event 's sourceElement to sourceElement Set event 's abort controller to a new AbortController created in 's relevant realm Initialize event 's signal to event 's abort controller 's signal Let currentURL be document 's URL If all of the following are true: event 's classic history API state is null; destination 's is same document is true; destination 's URL equals currentURL with exclude fragments set to true; and destination 's URL 's fragment is not identical to currentURL 's fragment then initialize event 's hashChange to true. Otherwise, initialize it to false. The first condition here means that hashChange will be true for fragment navigations , but false for cases like history.pushState(undefined, "", "#fragment") If userInvolvement is not " none ", then initialize event 's userInitiated to true. Otherwise, initialize it to false. If formDataEntryList is not null, then initialize event 's formData to a new FormData created in 's relevant realm associated to formDataEntryList . Otherwise, initialize it to null. Assert 's ongoing navigate event is null. Set 's ongoing navigate event to event Set 's focus changed during ongoing navigation to false. Set 's suppress normal scroll restoration during ongoing to false. Let dispatchResult be the result of dispatching event at If dispatchResult is false: If navigationType is " traverse ", then consume history-action user activation given 's relevant global object If event 's abort controller 's signal is not aborted , then abort the ongoing navigation given Return false. If event 's interception state is not " none ": Let fromNHE be the current entry of Assert fromNHE is not null. Set 's transition to a new NavigationTransition created in 's relevant realm , with navigation type navigationType from entry fromNHE destination event 's destination committed promise a new promise created in 's relevant realm finished promise a new promise created in 's relevant realm Mark as handled 's transition 's finished promise See the discussion about other finished promises to understand why this is done. Mark as handled 's transition 's committed promise If event 's navigation precommit handler list is empty then commit event given apiMethodTracker Otherwise: Let precommitController be a new NavigationPrecommitController created in 's relevant realm whose event is event Let precommitPromisesList be an empty list For each handler of event 's navigation precommit handler list Append the result of invoking handler with precommitController » to precommitPromisesList Wait for all precommitPromisesList with the following success steps: commit event given apiMethodTracker , and the following failure step given reason process navigate event handler failure given event and reason If event 's interception state is " none ", then return true. Return false. The navigate event intercept commit handler steps , given a , a NavigateEvent object event , and a API method tracker apiMethodTracker are as follows: Let promisesList be an empty list For each handler of event 's navigation handler list Append the result of invoking handler with an empty arguments list to promisesList If promisesList 's size is 0, then set promisesList to « a promise resolved with undefined ». There is a subtle timing difference between how waiting for all schedules its success and failure steps when given zero promises versus ≥1 promises. For most uses of waiting for all , this does not matter. However, with this API, there are so many events and promise handlers which could fire around the same time that the difference is pretty easily observable: it can cause the event/promise handler sequence to vary. (Some of the events and promises involved include: navigatesuccess navigateerror currententrychange dispose apiMethodTracker 's promises, and the navigation.transition.finished promise.) Wait for all of promisesList , with the following success steps: If event 's relevant global object is not fully active , then abort these steps. If event 's abort controller 's signal is aborted , then abort these steps. Assert event equals 's ongoing navigate event Set 's ongoing navigate event to null. Finish event given true. If apiMethodTracker is non-null, then resolve the finished promise for apiMethodTracker Fire an event named navigatesuccess at If 's transition is not null, then resolve 's transition 's finished promise with undefined. Set 's transition to null. and the following failure step given reason process navigate event handler failure given event and reason To commit a navigate event given a NavigateEvent object event and a navigation API method tracker apiMethodTracker Let be event 's target Let navigable be event 's relevant global object 's navigable If event 's relevant global object 's associated Document is not fully active , then return. If event 's abort controller 's signal is aborted , then return. Let endResultIsSameDocument be true if event 's interception state is not " none " or event 's destination 's is same document is true. Prepare to run script given 's relevant settings object This is done to avoid the JavaScript execution context stack becoming empty right after any currententrychange event handlers run as a result of the URL and history update steps that could soon happen. If the stack were to become empty at that time, then it would immediately perform a microtask checkpoint , causing various promise fulfillment handlers to run interleaved with the event handlers and before any handlers passed to navigateEvent.intercept() . This is undesirable since it means promise handler ordering vs. currententrychange event handler ordering vs. intercept() handler ordering would be dependent on whether the navigation is happening with an empty JavaScript execution context stack (e.g., because the navigation was user-initiated) or with a nonempty one (e.g., because the navigation was caused by a JavaScript API call). By inserting an otherwise-unnecessary JavaScript execution context onto the stack in this step, we essentially suppress the perform a microtask checkpoint algorithm until later, thus ensuring that the sequence is always: currententrychange event handlers, then intercept() handlers, then promise handlers. If event 's interception state is not " none ": Set event 's interception state to " committed ". Switch on event 's navigationType push replace Run the URL and history update steps given event 's relevant global object 's associated Document and event 's destination 's URL , with serializedData set to event 's classic history API state and historyHandling set to event 's navigationType reload Update the navigation API entries for a same-document navigation given navigable 's active session history entry , and " reload ". traverse Set 's suppress normal scroll restoration during ongoing to true. If event 's scroll behavior was set to " after-transition ", then scroll restoration will happen as part of finishing the relevant NavigateEvent Otherwise, there will be no scroll restoration. That is, no navigation which is intercepted by intercept() goes through the normal scroll restoration process; scroll restoration for such navigations is either done manually, by the web developer, or is done after the transition. Let userInvolvement be " none ". If event 's userInitiated is true, then set userInvolvement to " activation ". At this point after interception, it is not consequential whether the activation was a result of browser UI. Append the following session history traversal steps to navigable 's traversable navigable Resume applying the traverse history step given event 's destination 's entry 's session history entry 's step navigable 's traversable navigable , and userInvolvement If 's transition is not null, then resolve 's transition 's committed promise with undefined. If endResultIsSameDocument is false and apiMethodTracker is non-null, then clean up apiMethodTracker Clean up after running script given 's relevant settings object Per the previous note , this stops suppressing any potential promise handler microtasks, causing them to run at this point or later. To process navigate event handler failure given a NavigateEvent object event and a reason If event 's relevant global object 's associated Document is not fully active , then return. If event 's abort controller 's signal is aborted , then return. Assert event is event 's relevant global object 's navigation API 's ongoing navigate event If event 's interception state is not " intercepted ", then finish event given false. Abort event given reason 7.2.6.10.5 Scroll and focus behavior By calling navigateEvent.intercept() , web developers can suppress the normal scroll and focus behavior for same-document navigations, instead invoking cross-document navigation-like behavior at a later time. The algorithms in this section are called at those appropriate later points. To finish NavigateEvent event , given a boolean didFulfill Assert event 's interception state is not " finished ". If event 's interception state is " intercepted ", then: Assert didFulfill is false. Assert event 's navigation precommit handler list is not empty Only precommit handlers can cancel a navigation before it is committed. Set event 's interception state to " finished ". Return. If event 's interception state is " none ", then return. Potentially reset the focus given event If didFulfill is true, then potentially process scroll behavior given event Set event 's interception state to " finished ". To potentially reset the focus given a NavigateEvent event Assert event 's interception state is " committed " or " scrolled ". Let be event 's relevant global object 's navigation API Let focusChanged be 's focus changed during ongoing Set 's focus changed during ongoing navigation to false. If focusChanged is true, then return. If event 's focus reset behavior is " manual ", then return. If it was left as null, then we treat that as " after-transition ", and continue onward. Let document be event 's relevant global object 's associated Document Let focusTarget be the autofocus delegate for document If focusTarget is null, then set focusTarget to document 's body element If focusTarget is null, then set focusTarget to document 's document element Run the focusing steps for focusTarget , with document 's viewport as the fallback target Move the sequential focus navigation starting point to focusTarget To potentially process scroll behavior given a NavigateEvent event Assert event 's interception state is " committed " or " scrolled ". If event 's interception state is " scrolled ", then return. If event 's scroll behavior is manual ", then return. If it was left as null, then we treat that as " after-transition ", and continue onward. Process scroll behavior given event To process scroll behavior given a NavigateEvent event Assert event 's interception state is " committed ". Set event 's interception state to " scrolled ". If event 's navigationType was initialized to " traverse " or " reload ", then restore scroll position data given event 's relevant global object 's navigable 's active session history entry Otherwise: Let document be event 's relevant global object 's associated Document If document 's indicated part is null, then scroll to the beginning of the document given document [CSSOMVIEW] Otherwise, scroll to the fragment given document 7.2.7 Event interfaces The NavigateEvent interface has its own dedicated section , due to its complexity. 7.2.7.1 The NavigationCurrentEntryChangeEvent interface Exposed Window interface NavigationCurrentEntryChangeEvent Event constructor DOMString type NavigationCurrentEntryChangeEventInit eventInitDict ); readonly attribute NavigationType navigationType readonly attribute NavigationHistoryEntry from }; dictionary NavigationCurrentEntryChangeEventInit EventInit NavigationType navigationType null required NavigationHistoryEntry from }; event navigationType Returns the type of navigation which caused the current entry to change, or null if the change is due to navigation.updateCurrentEntry() event from Returns the previous value of navigation.currentEntry , before the current entry changed. If navigationType is null or " reload ", then this value will be the same as navigation.currentEntry . In that case, the event signifies that the contents of the entry changed, even if we did not move to a new entry or replace the current one. The navigationType and from attributes must return the values they were initialized to. 7.2.7.2 The PopStateEvent interface PopStateEvent/PopStateEvent Support in all current engines. Firefox 11+ Safari 6+ Chrome 16+ Opera Edge 79+ Edge (Legacy) 14+ Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android PopStateEvent Support in all current engines. Firefox 4+ Safari 6+ Chrome 4+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 12.1+ Exposed Window interface PopStateEvent Event constructor DOMString type optional PopStateEventInit eventInitDict = {}); readonly attribute any state readonly attribute boolean hasUAVisualTransition }; dictionary PopStateEventInit EventInit any state null boolean hasUAVisualTransition false }; event state PopStateEvent/state Support in all current engines. Firefox 4+ Safari 6+ Chrome 4+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 10+ Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 12.1+ Returns a copy of the information that was provided to pushState() or replaceState() event hasUAVisualTransition Returns true if the user agent performed a visual transition for this navigation before dispatching this event. If true, the best user experience will be given if the author synchronously updates the DOM to the post-navigation state. 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 The hasUAVisualTransition attribute must return the value it was initialized to. 7.2.7.3 The HashChangeEvent interface HashChangeEvent/HashChangeEvent Support in all current engines. Firefox 11+ Safari 6+ Chrome 16+ Opera Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android HashChangeEvent Support in all current engines. Firefox 3.6+ Safari 5+ Chrome 8+ Opera 10.6+ Edge 79+ Edge (Legacy) 12+ Internet Explorer 8+ Firefox Android Safari iOS 5+ Chrome Android WebView Android Samsung Internet 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 5.1+ Chrome 8+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 12.1+ Returns the URL of the session history entry that was previously current. event newURL HashChangeEvent/newURL Support in all current engines. Firefox 6+ Safari 5.1+ Chrome 8+ Opera 12.1+ Edge 79+ Edge (Legacy) 12+ Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android 12.1+ 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.2.7.4 The PageSwapEvent interface Exposed Window interface PageSwapEvent Event constructor DOMString type optional PageSwapEventInit eventInitDict = {}); readonly attribute NavigationActivation activation readonly attribute ViewTransition viewTransition }; dictionary PageSwapEventInit EventInit NavigationActivation activation null ViewTransition viewTransition null }; event activation NavigationActivation object representing the destination and type of the cross-document navigation. This would be null for cross-origin navigations. event activation entry NavigationHistoryEntry , representing the Document that is about to become active. event activation from NavigationHistoryEntry , equivalent to the value of the navigation.currentEntry property at the moment the event is fired. event activation navigationType One of " push ", " replace ", " reload ", or " traverse ", indicating what type of navigation that is about to result in a page swap. event viewTransition Returns the ViewTransition object that represents an outbound cross-document view transition, if such transition is active when the event is fired. Otherwise, returns null. The activation and viewTransition attributes must return the values they were initialized to. 7.2.7.5 The PageRevealEvent interface Exposed Window interface PageRevealEvent Event constructor DOMString type optional PageRevealEventInit eventInitDict = {}); readonly attribute ViewTransition viewTransition }; dictionary PageRevealEventInit EventInit ViewTransition viewTransition null }; event viewTransition Returns the ViewTransition object that represents an inbound cross-document view transition, if such transition is active when the event is fired. Otherwise, returns null. The viewTransition attribute must return the value it was initialized to. 7.2.7.6 The PageTransitionEvent interface PageTransitionEvent/PageTransitionEvent Support in all current engines. Firefox 11+ Safari 6+ Chrome 16+ Opera Edge 79+ Edge (Legacy) Internet Explorer No Firefox Android Safari iOS Chrome Android WebView Android Samsung Internet Opera Android PageTransitionEvent Support in all current engines. Firefox 1.5+ Safari 5+ Chrome 4+ Opera Edge 79+ Edge (Legacy) 12+ Internet Explorer 11 Firefox Android Safari iOS 4+ Chrome Android WebView Android 37+ Samsung Internet Opera Android 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 11+ Safari 5+ Chrome 4+ Opera Edge 79+ Edge (Legacy) 12+ Internet Explorer 11 Firefox Android Safari iOS 4+ Chrome Android WebView Android 37+ Samsung Internet Opera Android 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. To fire a page transition event named eventName at a Window window with a boolean persisted fire an event named eventName at window , using PageTransitionEvent , with the persisted attribute initialized to persisted , the cancelable attribute initialized to true, the bubbles attribute initialized to true, and legacy target override flag set. The values for cancelable and bubbles don't make any sense, since canceling the event does nothing and it's not possible to bubble past the Window object. They are set to true for historical reasons. 7.2.7.7 The BeforeUnloadEvent interface BeforeUnloadEvent Support in all current engines. Firefox 1.5+ Safari 7+ Chrome 30+ Opera Edge 79+ Edge (Legacy) Internet Explorer 4+ Firefox Android Safari iOS Chrome Android WebView Android 37+ Samsung Internet 3.0+ Opera Android Exposed Window interface BeforeUnloadEvent Event attribute DOMString returnValue }; There are no BeforeUnloadEvent -specific initialization methods. The BeforeUnloadEvent interface is a legacy interface which allows checking if unloading is canceled 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 checking if unloading is canceled . 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.2.8 The NotRestoredReasons interface Exposed Window interface NotRestoredReasonDetails readonly attribute DOMString reason Default object toJSON (); };
Exposed Window interface NotRestoredReasons readonly attribute USVString src readonly attribute DOMString id readonly attribute DOMString name readonly attribute USVString url readonly attribute FrozenArray NotRestoredReasonDetails >? reasons readonly attribute FrozenArray NotRestoredReasons >? children Default object toJSON (); }; notRestoredReasonDetails reason Returns a string that explains the reason that prevented the document from being served from back/forward cache . See the definition of bfcache blocking details for the possible string values. notRestoredReasons src Returns the src attribute of the document's node navigable 's container if it is an iframe element. This can be null if not set or if it is not an iframe element. notRestoredReasons id Returns the id attribute of the document's node navigable 's container if it is an iframe element. This can be null if not set or if it is not an iframe element. notRestoredReasons name Returns the name attribute of the document's node navigable 's container if it is an iframe element. This can be null if not set or if it is not an iframe element. notRestoredReasons url Returns the document's URL , or null if the document is in a cross-origin iframe . This is reported in addition to src because it is possible iframe navigated since the original src was set. notRestoredReasons reasons Returns an array of NotRestoredReasonDetails for the document. This is null if the document is in a cross-origin iframe notRestoredReasons children Returns an array of NotRestoredReasons that are for the document’s children. This is null if the document is in a cross-origin iframe NotRestoredReasonDetails object has a backing struct , a not restored reason details or null, initially null. The reason getter steps are to return this 's backing struct 's reason To create a NotRestoredReasonDetails object given a not restored reason details backingStruct and a realm realm Let notRestoredReasonDetails be a new NotRestoredReasonDetails object created in realm Set notRestoredReasonDetails 's backing struct to backingStruct Return notRestoredReasonDetails not restored reason details is a struct with the following items reason , a string, initially empty. The reason is a string that represents the reason that prevented the page from being restored from back/forward cache The string is one of the following: fetch While unloading , a fetch initiated by this Document was still ongoing and was canceled, so the page was not in a state that could be stored in the back/forward cache navigation-failure The original navigation that created this Document errored, so storing the resulting error document in the back/forward cache was prevented. parser-aborted The Document never finished its initial HTML parsing, so storing the unfinished document in the back/forward cache was prevented. websocket While unloading , an open WebSocket connection was shut down, so the page was not in a state that could be stored in the back/forward cache [WEBSOCKETS] lock While unloading , held locks and lock requests were terminated, so the page was not in a state that could be stored in the back/forward cache [WEBLOCKS] masked This Document has children that are in a cross-origin iframe , and they prevented back/forward cache ; or this Document could not be back/forward cached for user agent-specific reasons, and the user agent has chosen not to use one of the more specific reasons from the list of user-agent specific blocking reasons In addition to the list above, a user agent might choose to expose a reason that prevented the page from being restored from back/forward cache for user-agent specific blocking reasons . These are one of the following strings: audio-capture The Document requested audio capture permission by using Media Capture and Streams 's getUserMedia() with audio. [MEDIASTREAM] background-work The Document requested background work by calling SyncManager 's register() method, PeriodicSyncManager 's register() method, or BackgroundFetchManager 's fetch() method. broadcastchannel-message While the page was stored in back/forward cache , a BroadcastChannel connection on the page received a message and message event was fired. idbversionchangeevent The Document had a pending IDBVersionChangeEvent while unloading [INDEXEDDB] idledetector The Document had an active IdleDetector while unloading keyboardlock While unloading , keyboard lock was still active because Keyboard 's lock() method was called. mediastream MediaStreamTrack was in the live state upon unloading [MEDIASTREAM] midi The Document requested a MIDI permission by calling navigator.requestMIDIAccess() modals User prompts were shown while unloading navigating While unloading , loading was still ongoing, and so the Document was not in a state that could be stored in back/forward cache navigation-canceled The navigation request was canceled by calling window.stop() and the page was not in a state to be stored in back/forward cache non-trivial-browsing-context-group The browsing context group of this Document had more than one top-level browsing context otpcredential The Document created an OTPCredential outstanding-network-request While unloading , the Document had outstanding network requests and was not in a state that could be stored in back/forward cache paymentrequest The Document had an active PaymentRequest while unloading [PAYMENTREQUEST] pictureinpicturewindow The Document had an active PictureInPictureWindow while unloading [PICTUREINPICTURE] plugins The Document contained plugins request-method-not-get The Document was created from an HTTP request whose method was not ` GET `. [FETCH] response-auth-required The Document was created from an HTTP response that required HTTP authentication. response-cache-control-no-store The Document was created from an HTTP response whose ` Cache-Control ` header included the " no-store " token. [HTTP] response-cache-control-no-cache The Document was created from an HTTP response whose ` Cache-Control ` header included the " no-cache " token. [HTTP] response-keep-alive The Document was created from an HTTP response that contained a ` Keep-Alive ` header. response-scheme-not-http-or-https The Document was created from a response whose URL 's scheme was not an HTTP(S) scheme [FETCH] response-status-not-ok The Document was created from an HTTP response whose status was not an ok status [FETCH] rtc While unloading , a RTCPeerConnection or RTCDataChannel was shut down, so the page was not in a state that could be stored in the back/forward cache [WEBRTC] rtc-used-with-cache-control-no-store The Document was created from an HTTP response whose Cache-Control ` header included the no-store " token, and it has created a RTCPeerConnection or RTCDataChannel which might be used to receive sensitive information, so the page was not in a state that could be stored in the back/forward cache [HTTP] [WEBRTC] sensors The Document requested sensor access serviceworker-added The Document 's service worker client started to be controlled by a ServiceWorker while the page was in back/forward cache [SW] serviceworker-claimed The Document 's service worker client 's active service worker was claimed while the page was in back/forward cache [SW] serviceworker-postmessage The Document 's service worker client 's active service worker received a message while the page was in back/forward cache [SW] serviceworker-version-activated The Document 's service worker client 's active service worker 's version was activated while the page was in back/forward cache [SW] serviceworker-unregistered The Document 's service worker client 's active service worker 's service worker registration was unregistered while the page was in back/forward cache [SW] sharedworker This Document was in the owner set of a SharedWorkerGlobalScope User agents that support the back/forward cache for documents using shared workers can use more specific reasons such as "sharedworker-message" or "sharedworker-with-no-active-client" instead of this general reason, since the usage of shared workers itself is supported outside of the cases described in those reasons. sharedworker-message While the page was stored in back/forward cache , a message was received from a SharedWorkerGlobalScope whose owner set contains this Document sharedworker-with-no-active-client This Document was in the owner set of a SharedWorkerGlobalScope that is not actively needed smartcardconnection The Document had an active SmartCardConnection while unloading speechrecognition The Document had an active SpeechRecognition while unloading storageaccess The Document requested storage access permission by using the Storage Access API. unload-listener The Document registered an event listener for the unload event. video-capture The Document requested video capture permission by using Media Capture and Streams 's getUserMedia() with video. [MEDIASTREAM] webhid The Document called the WebHID API's requestDevice() method. webshare The Document used the Web Share API's navigator.share() method. websocket-used-with-cache-control-no-store The Document was created from an HTTP response whose Cache-Control ` header included the no-store " token, and it has created a WebSocket connection which might be used to receive sensitive information, so the page was not in a state that could be stored in the back/forward cache [HTTP] [WEBSOCKETS] webtransport While unloading , an open WebTransport connection was shut down, so the page was not in a state that could be stored in the back/forward cache [WEBTRANSPORT] webtransport-used-with-cache-control-no-store The Document was created from an HTTP response whose Cache-Control ` header included the no-store " token, and it has created a WebTransport connection which might be used to receive sensitive information, so the page was not in a state that could be stored in the back/forward cache [HTTP] [WEBTRANSPORT] webxrdevice The Document created a XRSystem NotRestoredReasons object has a backing struct not restored reasons or null, initially null. NotRestoredReasons object has a reasons array , a FrozenArray< NotRestoredReasonDetails or null, initially null. NotRestoredReasons object has a children array , a FrozenArray< NotRestoredReasons or null, initially null. The src getter steps are to return this 's backing struct 's src The id getter steps are to return this 's backing struct 's id The name getter steps are to return this 's backing struct 's name The url getter steps are: If this 's backing struct 's URL is null, then return null. Return this 's backing struct 's URL serialized The reasons getter steps are to return this 's reasons array The children getter steps are to return this 's children array To create a NotRestoredReasons object given a not restored reasons backingStruct and a realm realm Let notRestoredReasons be a new NotRestoredReasons object created in realm Set notRestoredReasons 's backing struct to backingStruct If backingStruct 's reasons is null, set notRestoredReasons 's reasons array to null. Otherwise: Let reasonsArray be an empty list For each reason of backingStruct 's reasons Create a NotRestoredReasonDetails object given reason and realm , and append it to reasonsArray Set notRestoredReasons 's reasons array to the result of creating a frozen array given reasonsArray If backingStruct 's children is null, set notRestoredReasons 's children array to null. Otherwise: Let childrenArray be an empty list For each child of backingStruct 's children Create a NotRestoredReasons object given child and realm and append it to childrenArray Set notRestoredReasons 's children array to the result of creating a frozen array given childrenArray Return notRestoredReasons not restored reasons is a struct with the following items src , a scalar value string or null, initially null. id , a string or null, initially null. name , a string or null, initially null. url , a URL or null, initially null. reasons , null or a list of not restored reason details , initially null. children , null or a list of not restored reasons , initially null. Document 's not restored reasons is its node navigable 's active session history entry 's document state 's not restored reasons , if Document 's node navigable is a top-level traversable otherwise null. 7.3 Infrastructure for sequences of documents This standard contains several related concepts for grouping sequences of documents. As a brief, non-normative summary: Navigables are a user-facing representation of a sequence of documents, i.e., they represent something that can be navigated between documents. Typical examples are tabs or windows in a web browser, or iframe s, or frame s in a frameset Traversable navigables are a special type of navigable which control the session history of themselves and of their descendant navigables. That is, in addition to their own series of documents, they represent a tree of further series of documents, plus the ability to linearly traverse back and forward through a flattened view of this tree. Browsing contexts are a developer-facing representation of a series of documents. They correspond 1:1 with WindowProxy objects. Each navigable can present a series of browsing contexts, with switches between those browsing contexts occuring under certain well-defined circumstances. Most of this standard works in the language of navigables, but certain APIs expose the existence of browsing context switches, and so some parts of the standard need to work in terms of browsing contexts. 7.3.1 Navigables navigable presents a Document to the user via its active session history entry . Each navigable has: An id , a new unique internal value parent navigable or null. current session history entry , a session history entry This can only be modified within the session history traversal queue of the parent traversable navigable An active session history entry , a session history entry This can only be modified from the event loop of the active session history entry 's document An is closing boolean, initially false. This is only ever set to true for top-level traversable navigables An is delaying load events boolean, initially false. This is only ever set to true in cases where the navigable's parent is non-null. The current session history entry and the active session history entry are usually the same, but they get out of sync when: Synchronous navigations are performed. This causes the active session history entry to temporarily step ahead of the current session history entry A non-displayable, non-error response is received when applying the history step . This updates the current session history entry but leaves the active session history entry as-is. navigable 's active document is its active session history entry 's document This can be safely read from within the session history traversal queue of the navigable's top-level traversable . Although a navigable 's active history entry can change synchronously, the new entry will always have the same Document navigable 's active browsing context is its active document 's browsing context . If this navigable is a traversable navigable , then its active browsing context will be a top-level browsing context navigable 's active WindowProxy is its active browsing context 's associated WindowProxy navigable 's active window is its active WindowProxy 's [[Window]] This will always equal the navigable's active document 's relevant global object ; this is kept in sync by the make active algorithm. navigable 's target name is its active session history entry 's document state 's navigable target name To get the node navigable of a node node , return the navigable whose active document is node 's node document , or null if there is no such navigable To initialize the navigable navigable navigable , given a document state documentState and an optional navigable -or-null parent (default null): Assert documentState 's document is non-null. Let entry be a new session history entry , with URL documentState 's document 's URL document state documentState The caller of this algorithm is responsible for initializing entry 's step ; it will be left as " pending " until that is complete. Set navigable 's current session history entry to entry Set navigable 's active session history entry to entry Set navigable 's parent to parent Set the initial visibility state of documentState 's document to navigable 's traversable navigable 's system visibility state 7.3.1.1 Traversable navigables traversable navigable is a navigable that also controls which session history entry should be the current session history entry and active session history entry for itself and its descendant navigables In addition to the properties of a navigable , a traversable navigable has: current session history step , a number, initially 0. Session history entries , a list of session history entries , initially a new list session history traversal queue session history traversal parallel queue , the result of starting a new session history traversal parallel queue running nested apply history step boolean, initially false. system visibility state , which is either " hidden " or visible ". See the page visibility section for the requirements on this item. An is created by web content boolean, initially false. To get the traversable navigable of navigable inputNavigable Let navigable be inputNavigable While navigable is not a traversable navigable , set navigable to navigable 's parent Return navigable 7.3.1.2 Top-level traversables top-level traversable is a traversable navigable with a null parent Currently, all traversable navigables are top-level traversables . Future proposals envision introducing non-top-level traversables. A user agent holds a top-level traversable set (a set of top-level traversables ). These are typically presented to the user in the form of browser windows or browser tabs. To get the top-level traversable of a navigable inputNavigable Let navigable be inputNavigable While navigable 's parent is not null, set navigable to navigable 's parent Return navigable To create a new top-level traversable given a browsing context -or-null opener , a string targetName , and an optional navigable openerNavigableForWebDriver Let document be null. If opener is null, then set document to the second return value of creating a new top-level browsing context and document Otherwise, set document to the second return value of creating a new auxiliary browsing context and document given opener Let documentState be a new document state , with document document initiator origin null if opener is null; otherwise, document 's origin origin document 's origin navigable target name targetName about base URL document 's about base URL Let traversable be a new traversable navigable Initialize the navigable traversable given documentState Let initialHistoryEntry be traversable 's active session history entry Set initialHistoryEntry 's step to 0. Append initialHistoryEntry to traversable 's session history entries If opener is non-null, then legacy-clone a traversable storage shed given opener 's top-level traversable and traversable [STORAGE] Append traversable to the user agent's top-level traversable set Invoke WebDriver BiDi navigable created with traversable and openerNavigableForWebDriver Return traversable To create a fresh top-level traversable given a URL initialNavigationURL and an optional POST resource -or-null initialNavigationPostResource (default null): Let traversable be the result of creating a new top-level traversable given null and the empty string. Navigate traversable to initialNavigationURL using traversable 's active document , with documentResource set to initialNavigationPostResource We treat these initial navigations as traversable navigating itself, which will ensure all relevant security checks pass. Return traversable 7.3.1.3 Child navigables Certain elements (for example, iframe elements) can present a navigable to the user. These elements are called navigable containers Each navigable container has a content navigable , which is either a navigable or null. It is initially null. The container of a navigable navigable is the navigable container whose content navigable is navigable , or null if there is no such element. The container document of a navigable navigable is the result of running these steps: If navigable 's container is null, then return null. Return navigable 's container 's node document This is equal to navigable 's container 's shadow-including root as navigable 's container has to be connected The container document of a Document document is the result of running these steps: If document 's node navigable is null, then return null. Return document 's node navigable 's container document navigable navigable is a child navigable of another navigable potentialParent when navigable 's parent is potentialParent . We can also just say that a navigable "is a child navigable ", which means that its parent is non-null. All child navigables are the content navigable of their container The content document of a navigable container container is the result of running these steps: If container 's content navigable is null, then return null. Let document be container 's content navigable 's active document If document 's origin and container 's node document 's origin are not same origin-domain , then return null. Return document The content window of a navigable container container is the result of running these steps: If container 's content navigable is null, then return null. Return container 's content navigable 's active WindowProxy 's object. To create a new child navigable , given an element element Let parentNavigable be element 's node navigable Let group be element 's node document 's browsing context 's top-level browsing context 's group Let browsingContext and document be the result of creating a new browsing context and document given element 's node document element , and group Let targetName be null. If element has a name content attribute, then set targetName to the value of that attribute. Let documentState be a new document state , with document document initiator origin document 's origin origin document 's origin navigable target name targetName about base URL document 's about base URL Let navigable be a new navigable Initialize the navigable navigable given documentState and parentNavigable Set element 's content navigable to navigable Let historyEntry be navigable 's active session history entry Let traversable be parentNavigable 's traversable navigable Append the following session history traversal steps to traversable Let parentDocState be parentNavigable 's active session history entry 's document state Let parentNavigableEntries be the result of getting session history entries for parentNavigable Let targetStepSHE be the first session history entry in parentNavigableEntries whose document state equals parentDocState Set historyEntry 's step to targetStepSHE 's step Let nestedHistory be a new nested history whose id is navigable 's id and entries list is « historyEntry ». Append nestedHistory to parentDocState 's nested histories Update for navigable creation/destruction given traversable Invoke WebDriver BiDi navigable created with traversable 7.3.1.4 Jake diagrams A useful method for visualizing sequences of documents, and in particular navigables and their session history entries , is the Jake diagram . A typical Jake diagram is the following: top /t-a /t-a#foo /t-b frames[0] /i-0-a /i-0-b frames[1] /i-1-a /i-1-b Here, each numbered column denotes a possible value for the traversable's session history step . Each labeled row depicts a navigable , as it transitions between different URLs and documents. The first, labeled top , being the top-level traversable , and the others being child navigables . The documents are given by the background color of each cell, with a new background color indicating a new document in that navigable . The URLs are given by the text content of the cells; usually they are given as relative URLs for brevity, unless a cross-origin case is specifically under investigation. A given navigable might not exist at a given step, in which case the corresponding cells are empty. The bold-italic step number depicts the current session history step of the traversable, and all cells with bold-italic URLs represent the current session history entry for that row's navigable. Thus, the above Jake diagram depicts the following sequence of events: top-level traversable is created, starting at the URL /t-a , with two child navigables starting at /i-0-a and /i-1-a respectively. The first child navigable is navigated to another document, with URL /i-0-b The second child navigable is navigated to another document, with URL /i-1-b The top-level traversable is navigated to the same document, updating its URL to /t-a#foo The top-level traversable is navigated to another document, with URL /t-b . (Notice how this document, of course, does not carry over the old document's child navigables.) The traversable was traversed by a delta of −3, back to step 1. Jake diagrams are a powerful tool for visualizing the interactions of multiple navigables, navigations, and traversals. They cannot capture every possible interaction — for example, they only work with a single level of nesting — but we will have ocassion to use them to illustrate several complex situations throughout this standard. Jake diagrams are named after their creator, the inimitable Jake Archibald. 7.3.1.5 Related navigable collections It is often helpful in this standard's algorithms to look at collections of navigables starting at a given Document . This section contains a curated set of algorithms for collecting those navigables. The return values of these algorithms are ordered so that parents appears before their children. Callers rely on this ordering. Starting with a Document , rather than a navigable , is generally better because it makes the caller cognizant of whether they are starting with a fully active Document or not. Although non- fully active Document s do have ancestor and descendant navigables, they often behave as if they don't (e.g., in the window.parent getter). The ancestor navigables of a Document document are given by these steps: Let navigable be document 's node navigable 's parent Let ancestors be an empty list. While navigable is not null: Prepend navigable to ancestors Set navigable to navigable 's parent Return ancestors The inclusive ancestor navigables of a Document document are given by these steps: Let navigables be document 's ancestor navigables Append document 's node navigable to navigables Return navigables The descendant navigables of a Document document are given by these steps: Let navigables be new list Let navigableContainers be a list of all shadow-including descendants of document that are navigable containers , in shadow-including tree order For each navigableContainer of navigableContainers If navigableContainer 's content navigable is null, then continue. Extend navigables with navigableContainer 's content navigable 's active document 's inclusive descendant navigables Return navigables The inclusive descendant navigables of a Document document are given by these steps: Let navigables be « document 's node navigable ». Extend navigables with document 's descendant navigables Return navigables These descendant-collecting algorithms are described as looking at the DOM tree of descendant Document objects. In reality, this is often not feasible since the DOM tree can be in another process from the caller of the algorithm. Instead, implementations generally replicate the appropriate trees across processes. The document-tree child navigables of a Document document are given by these steps: If document 's node navigable is null, then return the empty list. Let navigables be new list Let navigableContainers be a list of all descendants of document that are navigable containers , in tree order For each navigableContainer of navigableContainers If navigableContainer 's content navigable is null, then continue Append navigableContainer 's content navigable to navigables Return navigables 7.3.1.6 Navigable destruction To destroy a child navigable given a navigable container container Let navigable be container 's content navigable If navigable is null, then return. Set container 's content navigable to null. Inform the navigation API about child navigable destruction given navigable Destroy a document and its descendants given navigable 's active document Let parentDocState be container 's node navigable 's active session history entry 's document state Remove the nested history from parentDocState 's nested histories whose id equals navigable 's id Let traversable be container 's node navigable 's traversable navigable Append the following session history traversal steps to traversable Update for navigable creation/destruction given traversable Invoke WebDriver BiDi navigable destroyed with navigable To destroy top-level traversable traversable Let browsingContext be traversable 's active browsing context For each historyEntry in traversable 's session history entries in what order? Let document be historyEntry 's document If document is not null, then destroy a document and its descendants given document Remove browsingContext Remove traversable from the user interface (e.g., close or hide its tab in a tabbed browser). Remove traversable from the user agent's top-level traversable set Invoke WebDriver BiDi navigable destroyed with traversable User agents may destroy a top-level traversable at any time (typically, in response to user requests ). To close top-level traversable traversable If traversable 's is closing is true, then return. Definitely close traversable To definitely close top-level traversable traversable Let toUnload be traversable 's active document 's inclusive descendant navigables If the result of checking if unloading is canceled for toUnload is not " continue ", then return. Append the following session history traversal steps to traversable Let afterAllUnloads be an algorithm step which destroys traversable Unload a document and its descendants given traversable 's active document , null, and afterAllUnloads The close vs. definitely close separation allows other specifications to call close and have it be a no-op if the top-level traversable is already closing due to JavaScript code calling window.close() 7.3.1.7 Navigable target names Navigables can be given target names , which are strings allowing certain APIs (such as window.open() or the element's target attribute) to target navigations at that navigable. valid navigable target name is any string with at least one character that does not contain both an ASCII tab or newline and a U+003C (<), and it does not start with a U+005F (_). (Names starting with a U+005F (_) are reserved for special keywords.) valid navigable target name or keyword is any string that is either a valid navigable target 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 navigable that the link or script is in, "parent" means the parent of the navigable that the link or script is in, "top" means the top-level traversable of the navigable that the link or script is in, "new" means a new traversable navigable with a null parent (which may use an auxiliary browsing context , 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 navigable given below. To find a navigable by target name given a string name and a navigable currentNavigable Let currentDocument be currentNavigable 's active document Let sourceSnapshotParams be the result of snapshotting source snapshot params given currentDocument Let subtreesToSearch be an implementation-defined choice of one of the following: currentNavigable 's traversable navigable currentNavigable the inclusive ancestor navigables of currentDocument Issue #10848 tracks settling on one of these two possibilities, to achieve interoperability. For each subtreeToSearch of subtreesToSearch , in reverse order: Let documentToSearch be subtreeToSearch 's active document For each navigable of the inclusive descendant navigables of documentToSearch If currentNavigable is not allowed by sandboxing to navigate navigable given sourceSnapshotParams , then optionally continue Issue #10849 tracks making this check required, to achieve interoperability. If navigable 's target name is name , then return navigable Let currentTopLevelBrowsingContext be currentNavigable 's active browsing context 's top-level browsing context Let group be currentTopLevelBrowsingContext 's group For each topLevelBrowsingContext of group 's browsing context set , in an implementation-defined order (the user agent should pick a consistent ordering, such as the most recently opened, most recently focused, or more closely related): Issue #10850 tracks picking a specific ordering, to achieve interoperability. If currentTopLevelBrowsingContext is topLevelBrowsingContext , then continue Let documentToSearch be topLevelBrowsingContext 's active document For each navigable of the inclusive descendant navigables of documentToSearch If currentNavigable 's active browsing context is not familiar with navigable 's active browsing context , then continue If currentNavigable is not allowed by sandboxing to navigate navigable given sourceSnapshotParams , then optionally continue Issue #10849 tracks making this check required, to achieve interoperability. If navigable 's target name is name , then return navigable Return null. The rules for choosing a navigable , given a string name , a navigable currentNavigable , and a boolean noopener are as follows: Let chosen be null. Let windowType be " existing or none ". Let sandboxingFlagSet be currentNavigable '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 currentNavigable Otherwise, if name is an ASCII case-insensitive match for " _parent ", set chosen to currentNavigable 's parent , if any, and currentNavigable otherwise. Otherwise, if name is an ASCII case-insensitive match for " _top ", set chosen to currentNavigable 's traversable navigable Otherwise, if name is not an ASCII case-insensitive match for _blank " and noopener is false, then set chosen to the result of finding a navigable by target name given name and currentNavigable If chosen is null, then a new top-level traversable 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 currentNavigable '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 top-level traversable Consume user activation of currentNavigable 's active window Set windowType to " new and unrestricted ". Let currentDocument be currentNavigable 's active document If currentDocument 's opener policy 's value is " same-origin " or " same-origin-plus-COEP ", and currentDocument 's origin is not same origin with currentDocument 's relevant settings object 's top-level origin , then: Set noopener to true. Set name to " _blank ". Set windowType to " new with no opener ". In the presence of an opener policy , nested documents that are cross-origin with their top-level browsing context's active document always set noopener to true. Let targetName be the empty string. If name is not an ASCII case-insensitive match for " _blank ", then set targetName to name If noopener is true, then set chosen to the result of creating a new top-level traversable given null, targetName , and currentNavigable Otherwise: Set chosen to the result of creating a new top-level traversable given currentNavigable 's active browsing context targetName , and currentNavigable If sandboxingFlagSet 's sandboxed navigation browsing context flag is set, then set chosen 's active browsing context 's one permitted sandboxed navigator to currentNavigable 's active browsing context 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 active browsing context 's popup sandboxing flag set Set chosen 's is created by web content to true. If the newly created navigable chosen is immediately navigated , then the navigation will be done as a " replace " navigation. If the user agent has been configured such that in this instance it will choose currentNavigable Set chosen to currentNavigable If the user agent has been configured such that in this instance it will not find a navigable Do nothing. User agents are encouraged to provide a way for users to configure the user agent to always choose currentNavigable Return chosen and windowType 7.3.2 Browsing contexts browsing context is a programmatic representation of a series of documents, multiple of which can live within a single navigable . Each browsing context has a corresponding WindowProxy object, as well as the following: An opener browsing context , a browsing context or null, initially null. An opener origin at creation , an origin or null, initially null. An is popup boolean, initially false. The only mandatory impact in this specification of is popup is on the visible getter of the relevant BarProp objects. However, user agents might also use it for user interface considerations An is auxiliary boolean, initially false. An initial URL , a URL or null, initially null. virtual browsing context group ID integer, initially 0. This is used by 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 '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 browsing context 's top-level traversable is its active document 's node navigable 's top-level traversable browsing context whose is auxiliary is true is known as an auxiliary browsing context . Auxiliary browsing contexts are always top-level browsing contexts It's unclear whether a separate is auxiliary concept is necessary. In issue #5680 , it is indicated that we may be able to simplify this by using whether or not the opener browsing context is null. Modern specifications should avoid using the browsing context concept in most cases, unless they are dealing with the subtleties of browsing context group switches and agent cluster allocation . Instead, the Document and navigable concepts are usually more appropriate. Document 's browsing context is a browsing context or null, initially null. 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 nulled out 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, which will be done with replacement 7.3.2.1 Creating browsing contexts To create a new browsing context and document , given null or a Document object creator , null or an element embedder , and a browsing context group group Let browsingContext be a new browsing context Let unsafeContextCreationTime be the unsafe shared current time Let creatorOrigin be null. Let creatorBaseURL be null. If creator is non-null, then: Set creatorOrigin to creator 's origin Set creatorBaseURL to creator 's document base URL Set browsingContext 's virtual browsing context group ID to creator 's browsing context '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 about:blank sandboxFlags , and creatorOrigin Let permissionsPolicy be the result of creating a permissions policy given embedder and origin [PERMISSIONSPOLICY] 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 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 loadTimingInfo be a new document load timing info with its navigation start time set to the result of calling coarsen time with unsafeContextCreationTime and the new environment settings object 's cross-origin isolated capability Let document be a new Document , with: type html content type text/html mode quirks origin origin browsing context browsingContext permissions policy permissionsPolicy active sandboxing flag set sandboxFlags load timing info loadTimingInfo is initial about:blank true about base URL creatorBaseURL allow declarative shadow roots true custom element registry a new CustomElementRegistry object Let iframeReferrerPolicy be the result of determining the iframe element referrer policy given embedder Set document 's internal ancestor origin objects list to the result of running the internal ancestor origin objects list creation steps given document and iframeReferrerPolicy Set document 's ancestor origins list to the result of running the ancestor origins list creation steps given document If creator is non-null, then: Set document 's referrer to the serialization of creator 's URL Set document 's policy container to a clone of creator 's policy container If creator 's origin is same origin with creator 's relevant settings object 's top-level origin , then set document 's opener policy to creator 's browsing context 's top-level browsing context 's active document 's opener policy Assert document 's URL and document 's relevant settings object 's creation URL are about:blank Mark document as ready for post-load tasks Populate with html head body given document Make active document Completely finish loading document Return browsingContext and document To create a new top-level browsing context and document Let group and document be the result of creating a new browsing context group and document Return group 's browsing context set [0] and document To create a new auxiliary browsing context and document , given browsing context opener Let openerTopLevelBrowsingContext be opener 's top-level traversable 's active browsing context Let group be openerTopLevelBrowsingContext 's group Assert group is non-null, as navigating invokes this directly. Let browsingContext and document be the result of creating a new browsing context and document with opener 's active document , null, and group Set browsingContext 's is auxiliary to true. Append browsingContext to group Set browsingContext 's opener browsing context to opener Set browsingContext 's virtual browsing context group ID to openerTopLevelBrowsingContext 's virtual browsing context group ID Set browsingContext 's opener origin at creation to opener 's active document 's origin Return browsingContext and document To determine the origin , given a URL url , a sandboxing flag set sandboxFlags , and an origin -or-null sourceOrigin 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 url is about:srcdoc , then: Assert sourceOrigin is non-null. Return sourceOrigin If url matches about:blank and sourceOrigin is non-null, then return sourceOrigin Return url 's origin The cases that return sourceOrigin result in two Document s that end up with the same underlying origin , meaning that document.domain affects both. 7.3.2.2 Related browsing contexts browsing context potentialDescendant is said to be an ancestor of a browsing context potentialAncestor if the following algorithm returns true: Let potentialDescendantDocument be potentialDescendant 's active document If potentialDescendantDocument is not fully active , then return false. Let ancestorBCs be the list obtained by taking the browsing context of the active document of each member of potentialDescendantDocument 's ancestor navigables If ancestorBCs contains potentialAncestor , then return true. Return false. top-level browsing context is a browsing context whose active document 's node navigable is a traversable navigable It is not required to be a top-level traversable The top-level browsing context of a browsing context start is the result of the following algorithm: If start 's active document is not fully active , then return null. Let navigable be start 's active document 's node navigable While navigable 's parent is not null, set navigable to navigable 's parent Return navigable 's active browsing context The terms ancestor browsing context and top-level browsing context are rarely useful, since browsing contexts in general are usually the inappropriate specification concept to use Note in particular that when a browsing context 's active document is not fully active , it never counts as an ancestor or top-level browsing context, and as such these concepts are not useful when bfcache is in play. Instead, use concepts such as the ancestor navigables collection, the parent navigable , or a navigable's top-level traversable browsing context is familiar with a second browsing context if the following algorithm returns true: If 's active document 's origin is same origin with 's active document 's origin , then return true. If 's top-level browsing context is , then return true. If is an auxiliary browsing context and is familiar with 's opener browsing context , then return true. If there exists an ancestor browsing context of whose active document has the same origin as the active document of , then return true. This includes the case where is an ancestor browsing context of Return false. 7.3.2.3 Groupings of browsing contexts top-level browsing context has an associated group (null or a browsing context group ). It is initially null. 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 a ` Cross-Origin-Embedder-Policy ` header whose value is compatible with cross-origin isolation 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 and document Let group be a new browsing context group Append group to the user agent's browsing context group set Let browsingContext and document be the result of creating a new browsing context and document with null, null, and group Append browsingContext to group Return group and document To append top-level browsing context browsingContext to a browsing context group group Append browsingContext to group 's browsing context set Set browsingContext 's group to group To remove top-level browsing context browsingContext Assert browsingContext 's group is non-null. 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 by higher-level creation and destruction operations for Document s and browsing contexts When there are no Document objects whose browsing context equals a given browsing context (i.e., all such Document s have been destroyed ), and that browsing context 's WindowProxy is eligible for garbage collection, then the browsing context will never be accessed again. If it is a top-level browsing context , then at this point the user agent must remove it. 7.3.3 Fully active documents Document is said to be fully active when is the active document of a navigable navigable , and either navigable is a top-level traversable or navigable 's container document is fully active Because they are associated with an element, child navigables are always tied to a specific Document , their container document , in their parent navigable . User agents must not allow the user to interact with child navigables whose container documents are not themselves fully active The following example illustrates how a Document can be the active document of its node navigable , while not being fully active . 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 Navigable A title iframe src "b-1.html" > iframe button onclick "frames[0].location.href = 'b-2.html'" Click me button html lang "en" title Navigable 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 node navigables . They are also all fully active After clicking on the button , and thus loading a new Document from b-2.html into navigable B, we have the following results: The a.html Document remains both the active document of navigable A, and fully active The b-1.html Document is now not the active document of navigable B. As such it is also not fully active The new b-2.html Document is now the active document of navigable B, and is also fully active The c.html Document is still the active document of navigable 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 7.4 Navigation and session history Welcome to the dragon's maw. Navigation, session history, and the traversal through that session history are some of the most complex parts of this standard. The basic concept may not seem so difficult: The user is looking at a navigable that is presenting its active document . They navigate it to another URL The browser fetches the given URL from the network, using it to populate a new session history entry with a newly- created Document The browser updates the navigable 's active session history entry to the newly-populated one, and thus updates the active document that it is showing to the user. At some point later, the user presses the browser back button to go back to the previous session history entry The browser looks at the URL stored in that session history entry , and uses it to re-fetch and populate that entry's document The browser again updates the navigable 's active session history entry You can see some of the intertwined complexity peeking through here, in how traversal can cause a navigation (i.e., a network fetch to a stored URL), and how a navigation necessarily needs to interface with the session history list to ensure that when it finishes the user is looking at the right thing. But the real problems come in with the various edge cases and interacting web platform features: Child navigables (e.g., those contained in iframe s) can also navigate and traverse, but those navigations need to be linearized into a single session history list since the user only has a single back/forward interface for the entire traversable navigable (e.g., browser tab). Since the user can traverse back more than a single step in the session history (e.g., by holding down their back button), they can end up traversing multiple navigables at the same time when child navigables are involved. This needs to be synchronized across all of the involved navigables, which might involve multiple event loops or even agent clusters During navigation, servers can respond with 204 or 205 status codes or with ` Content-Disposition: attachment ` headers, which cause navigation to abort and the navigable to stay on its original active document . (This is much worse if it happens during a traversal-initiated navigation!) Various other HTTP headers, such as ` Location `, Refresh `, ` X-Frame-Options `, and those for Content Security Policy, contribute to either the fetching process , or the Document -creation process , or both. The ` Cross-Origin-Opener-Policy ` header even contributes to the browsing context selection and creation process! Some navigations (namely fragment navigations and single-page app navigations ) are synchronous, meaning that JavaScript code expects to observe the navigation's results instantly. This then needs to be synchronized with the view of the session history that all other navigables in the tree see, which can be subject to race conditions and necessitate resolving conflicting views of the session history. The platform has accumulated various exciting navigation-related features that need special-casing, such as javascript: URLs, srcdoc iframe s, and the beforeunload event. In what follows, we have attempted to guide the reader through these complexities by appropriately cordoning them off into labeled sections and algorithms, and giving appropriate words of introduction where possible. Nevertheless, if you wish to truly understand navigation and session history, the usual advice will be invaluable. 7.4.1 Session history 7.4.1.1 Session history entries session history entry is a struct with the following items step , a non-negative integer or " pending ", initially " pending ". URL , a URL document state , a document state classic history API state , which is serialized state , initially StructuredSerializeForStorage (null). navigation API state , which is a serialized state , initially StructuredSerializeForStorage (undefined). navigation API key , which is a string, initially set to the result of generating a random UUID navigation API ID , which is a string, initially set to the result of generating a random UUID scroll restoration mode , a scroll restoration mode , initially " auto ". scroll position data , which is scroll position data for the document 's restorable scrollable regions 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. To get a session history entry 's document return its document state 's document 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 7.4.1.2 Document state Document state holds state inside a session history entry regarding how to present and, if necessary, recreate, a Document . It has: document , a Document or null, initially null. When a history entry is active , it has a Document in its document state . However, when a Document is not fully active , it's possible for it to be destroyed to free resources. In such cases, this document item will be nulled out. The URL and other data in the session history entry and document state 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 traverse to the entry. If the Document is not destroyed , then during history traversal , it can be reactivated . The cache in which browsers store such Document s is often called a back-forward cache , or bfcache (or perhaps "blazingly fast" cache). history policy container , a policy container or null, initially null. request referrer , which is " no-referrer ", " client ", or a URL , initially client ". request referrer policy , which is a referrer policy , initially the default referrer policy The request referrer policy is distinct from the history policy container 's referrer policy . The former is used for fetches of this document, whereas the latter controls fetches by this document. An initiator origin , which is an origin or null, initially null. An origin , which is an origin or null, initially null. This is the origin that we set " about: "-schemed Document s' origin to. We store it here because it is also used when restoring these Document s during traversal, since they are reconstructed locally without visiting the network. It is also used to compare the origin before and after the session history entry is repopulated . If the origins change, the navigable target name is cleared. An about base URL , which is a URL or null, initially null. This will be populated only for " about: "-schemed Document s and will be the fallback base URL for those Document s. It is a snapshot of the initiator Document 's document base URL Nested histories , a list of nested histories , initially an empty list resource , a string, POST resource or null, initially null. A string is treated as HTML. It's used to store the source of an iframe srcdoc document reload pending boolean, initially false. An ever populated boolean, initially false. navigable target name string, initially the empty string. not restored reasons , a not restored reasons or null, initially null. User agents may destroy a document and its descendants given the documents of document states with non-null documents , as long as the Document is not fully active Apart from that restriction, this standard does not specify when user agents should destroy the document stored in a document state , versus keeping it cached. POST resource has: request body , a byte sequence or failure. This is only ever accessed in parallel , so it doesn't need to be stored in memory. However, it must return the same byte sequence each time. If this isn't possible due to resources changing on disk, or if resources can no longer be accessed, then this must be set to failure. request content-type , which is ` application/x-www-form-urlencoded `, multipart/form-data `, or ` text/plain `. nested history has: An id , a unique internal value This is used to associate the nested history with a navigable Entries , a list of session history entries This will later contain ways to identify a child navigable across reloads. Several contiguous entries in a session history can share the same document state . 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 state (and that are therefore merely different states of one particular document) are contiguous by construction. Document has a latest entry , a session history entry or null. This is the entry that was most recently represented by a given Document . A single Document can represent many session history entries over time, as many contiguous session history entries can share the same document state as explained above. 7.4.1.3 Centralized modifications of session history To maintain a single source of truth, all modifications to a traversable navigable 's session history entries need to be synchronized. This is especially important due to how session history is influenced by all of the descendant navigables , and thus by multiple event loops . To accomplish this, we use the session history traversal parallel queue structure. session history traversal parallel queue is very similar to a parallel queue . It has an algorithm set , an ordered set The items in a session history traversal parallel queue 's algorithm set are either algorithm steps, or synchronous navigation steps , which are a particular brand of algorithm steps involving a target navigable (a navigable ). To append session history traversal steps to a traversable navigable traversable given algorithm steps steps append steps to traversable 's session history traversal queue 's algorithm set To append session history synchronous navigation steps involving a navigable targetNavigable to a traversable navigable traversable given algorithm steps steps append steps as synchronous navigation steps targeting target navigable targetNavigable to traversable 's session history traversal queue 's algorithm set To start a new session history traversal parallel queue Let sessionHistoryTraversalQueue be a new session history traversal parallel queue Run the following steps in parallel While true: If sessionHistoryTraversalQueue 's algorithm set is empty, then continue Let steps be the result of dequeuing from sessionHistoryTraversalQueue 's algorithm set Run steps Return sessionHistoryTraversalQueue Synchronous navigation steps are tagged in the algorithm set to allow them to conditionally "jump the queue". This is handled within apply the history step Imagine the joint session history depicted by this Jake diagram top /a /b And the following code runs at the top level: history back (); location href '#foo' The desired result is: top /a /b /b#foo This isn't straightforward, as the sync navigation wins the race in terms of being observable, whereas the traversal wins the race in terms of queuing steps on the session history traversal parallel queue . To achieve this result, the following happens: history.back() appends steps intended to traverse by a delta of −1. location.href = '#foo' synchronously changes the active session history entry entry to a newly-created one, with the URL /b#foo , and appends synchronous steps to notify the central source of truth about that new entry. Note that this does not yet update the current session history entry current session history step , or the session history entries list; those updates cannot be done synchronously, and instead must be done as part of the queued steps. On the session history traversal parallel queue , the steps queued by history.back() run: The target history step is determined to be 0: the current session history step (i.e., 1) plus the intended delta of −1. We enter the main apply the history step algorithm. The entry at step 0, for the /a URL, has its document populated Meanwhile, the queue is checked for synchronous navigation steps . The steps queued by the location.href setter now run, and block the traversal from performing effects beyond document population (such as, unloading documents and switching active history entries) until they are finished. Those steps cause the following to happen: The entry with URL /b#foo is added, with its step determined to be 2: the current session history step (i.e., 1) plus 1. We fully switch to that newly added entry, including a nested call to apply the history step . This ultimately results in updating the document by dispatching events like hashchange Only once that is all complete, and the /a history entry has been fully populated with a document , do we move on with applying the history step given the target step of 0. At this point, the Document with URL /b#foo unloads , and we finish moving to our target history step 0, which makes the entry with URL /a become the active session history entry and 0 become the current session history step Here is another more complex example, involving races between populating two different iframe s, and a synchronous navigation once one of those iframes loads. We start with this setup: top /t frames[0] /i-0-a /i-0-b frames[1] /i-1-a /i-1-b and then call history.go(-2) . The following then occurs: history.go(-2) appends steps intended to traverse by a delta of −2. Once those steps run: The target step is determined to be 2 + (−2) = 0. In parallel, the fetches are made to populate the two iframes, fetching /i-0-a and /i-1-a respectively. Meanwhile, the queue is checked for synchronous navigation steps . There aren't any right now. In the fetch race, the fetch for /i-0-a wins. We proceed onward to finish all of apply the history step 's work for how the traversal impacts the frames[0] navigable , including updating its active session history entry to the entry with URL /i-0-a Before the fetch for /i-1-a finishes, we reach the point where scripts may run for the newly-created document in the frames[0] navigable 's active document . Some such script does run: location href '#foo' This synchronously changes the frames[0] navigable's active session history entry entry to a newly-created one, with the URL /i-0-a#foo , and appends synchronous steps to notify the central source of truth about that new entry. Unlike in the previous example , these synchronous steps do not "jump the queue" and update the traversable before we finish the fetch for /i-1-a . This is because the navigable in question, frames[0] , has already been altered as part of the traversal, so we know that with the current session history step being 2, adding the new entry as a step 3 doesn't make sense. Once the fetch for /i-1-a finally finishes, we proceed to finish updating the frames[1] navigable for the traversal, including updating its active session history entry to the entry with URL /i-1-a Now that both navigables have finished processing the traversal, we update the current session history step to the target step of 0. Now we can process the steps that were queued for the synchronous navigation: The /i-0-a#foo entry is added, with its step determined to be 1: the current session history step (i.e., 0) plus 1. This also clears existing forward history We fully switch to that newly added entry, including calling apply the history step . This ultimately results in updating the document by dispatching events like hashchange , as well as updating the current session history step to the target step of 1. The end result is: top /t frames[0] /i-0-a /i-0-a#foo frames[1] /i-1-a 7.4.1.4 Low-level operations on session history This section contains a miscellaneous grab-bag of operations that we perform throughout the standard when manipulating session history. The best way to get a sense of what they do is to look at their call sites. To get session history entries of a navigable navigable Let traversable be navigable 's traversable navigable Assert : this is running within traversable 's session history traversal queue If navigable is traversable , return traversable 's session history entries Let docStates be an empty ordered set of document states For each entry of traversable 's session history entries append entry 's document state to docStates For each docState of docStates For each nestedHistory of docState 's nested histories If nestedHistory 's id equals navigable 's id , return nestedHistory 's entries For each entry of nestedHistory 's entries append entry 's document state to docStates Assert : this step is not reached. To get session history entries for the navigation API of a navigable navigable given an integer targetStep Let rawEntries be the result of getting session history entries for navigable Let entriesForNavigationAPI be a new empty list Let startingIndex be the index of the session history entry in rawEntries who has the greatest step less than or equal to targetStep See this example to understand why it's the greatest step less than or equal to targetStep Append rawEntries startingIndex to entriesForNavigationAPI Let startingOrigin be rawEntries startingIndex ]'s document state 's origin Let be startingIndex − 1. While > 0: If rawEntries ]'s document state 's origin is not same origin with startingOrigin , then break Prepend rawEntries ] to entriesForNavigationAPI Set to − 1. Set to startingIndex + 1. While rawEntries 's size If rawEntries ]'s document state 's origin is not same origin with startingOrigin , then break Append rawEntries ] to entriesForNavigationAPI Set to + 1. Return entriesForNavigationAPI To clear the forward session history of a traversable navigable navigable Assert : this is running within navigable 's session history traversal queue Let step be the navigable 's current session history step Let entryLists be the ordered set navigable 's session history entries ». For each entryList of entryLists Remove every session history entry from entryList that has a step greater than step For each entry of entryList For each nestedHistory of entry 's document state 's nested histories append nestedHistory 's entries list to entryLists To get all used history steps that are part of traversable navigable traversable Assert : this is running within traversable 's session history traversal queue Let steps be an empty ordered set of non-negative integers. Let entryLists be the ordered set traversable 's session history entries ». For each entryList of entryLists For each entry of entryList Append entry 's step to steps For each nestedHistory of entry 's document state 's nested histories append nestedHistory 's entries list to entryLists Return steps sorted 7.4.2 Certain actions cause a navigable to navigate to a new resource. For example, following a hyperlink form submission , and the window.open() and location.assign() methods can all cause navigation. Although in this standard the word "navigation" refers specifically to the navigate algorithm, this doesn't always line up with web developer or user perceptions. For example: The URL and history update steps are often used during so-called "single-page app navigations" or "same-document navigations", but they do not trigger the navigate algorithm. Reloads and traversals are sometimes talked about as a type of navigation, since all three will often attempt to populate the history entry's document and thus could perform navigational fetches. See, e.g., the APIs exposed Navigation Timing . But they have their own entry point algorithms, separate from the navigate algorithm. [NAVIGATIONTIMING] Although fragment navigations are always done through the navigate algorithm, a user might perceive them as more like jumping around a single page, than as a true navigation. 7.4.2.1 Supporting concepts Before we can jump into the navigation algorithm itself, we need to establish several important structures that it uses. The source snapshot params struct is used to capture data from a Document initiating a navigation. It is snapshotted at the beginning of a navigation and used throughout the navigation's lifetime. It has the following items has transient activation a boolean sandboxing flags sandboxing flag set allows downloading a boolean fetch client an environment settings object or null, only to be used as a request client source policy container policy container To snapshot source snapshot params given a Document -or-null sourceDocument If sourceDocument is null, then return a new source snapshot params with has transient activation true sandboxing flags an empty sandboxing flag set allows downloading true fetch client null source policy container a new policy container This only occurs in the case of a browser UI-initiated navigation. Return a new source snapshot params with has transient activation true if sourceDocument 's relevant global object has transient activation ; otherwise false sandboxing flags sourceDocument 's active sandboxing flag set allows downloading false if sourceDocument 's active sandboxing flag set has the sandboxed downloads browsing context flag set; otherwise true fetch client sourceDocument 's relevant settings object source policy container clone of sourceDocument 's policy container The target snapshot params struct is used to capture data from a navigable being navigated. Like source snapshot params , it is snapshotted at the beginning of a navigation and used throughout the navigation's lifetime. It has the following items sandboxing flags sandboxing flag set iframe element referrer policy referrer policy To snapshot target snapshot params given a navigable targetNavigable , return a new target snapshot params with: sandboxing flags the result of determining the creation sandboxing flags given targetNavigable 's active browsing context and targetNavigable 's container iframe element referrer policy the result of determining the iframe element referrer policy given targetNavigable 's container 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 that algorithm are tracked via a navigation params struct , which has the following items id null or a navigation ID navigable the navigable to be navigated request null or a request that started the navigation response response that ultimately was navigated to (potentially a network error fetch controller null or a fetch controller commit early hints null or an algorithm accepting a Document , once it has been created COOP enforcement result an 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 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 iframe element referrer policy referrer policy , used in the internal ancestor origin objects list creation steps opener policy an opener policy to use for the new Document navigation timing type NavigationTimingType used for creating the navigation timing entry for the new Document about base URL URL or null used to populate the new Document 's about base URL user involvement user navigation involvement used when obtaining a browsing context for the new Document Once a navigation params struct is created, this standard does not mutate any of its items . They are only passed onward to other algorithms. navigation ID is a UUID string generated during navigation. It is used to interface with the WebDriver BiDi specification as well as to track the ongoing [WEBDRIVERBIDI] After Document creation, the relevant traversable navigable 's session history gets updated. The NavigationHistoryBehavior enumeration is used to indicate the desired type of session history update to the navigate algorithm. It is one of the following: push A regular navigation which adds a new session history entry , and will clear the forward session history replace A navigation that will replace the active session history entry auto The default value, which will be converted very early in the navigate algorithm into " push " or " replace ". Usually it becomes " push ", but under certain circumstances it becomes " replace " instead. history handling behavior is a NavigationHistoryBehavior that is either " push " or " replace ", i.e., that has been resolved away from any initial " auto " value. The navigation must be a replace , given a URL url and a Document document , if any of the following are true: url 's scheme is " javascript "; or document 's is initial about:blank is true. Other cases that often, but not always, force a " replace " navigation are: if the Document is not completely loaded ; or if the target URL equals the Document 's URL Various parts of the platform track whether a user is involved in a navigation. A user navigation involvement is one of the following: browser UI The navigation was initiated by the user via browser UI mechanisms. activation The navigation was initiated by the user via the activation behavior of an element. none The navigation was not initiated by the user. For convenience at certain call sites, the user navigation involvement for an Event event is defined as follows: Assert : this algorithm is being called as part of an activation behavior definition. Assert event 's type is click ". If event 's isTrusted is initialized to true, then return " activation ". Return " none ". 7.4.2.2 Beginning navigation To navigate navigable navigable to a URL url using an optional Document -or-null sourceDocument (default null), with an optional POST resource , string, or null documentResource (default null), an optional response -or-null response (default null), an optional boolean exceptionsEnabled (default false), an optional NavigationHistoryBehavior historyHandling (default " auto "), an optional serialized state -or-null navigationAPIState (default null), an optional entry list or null formDataEntryList (default null), an optional referrer policy referrerPolicy (default the empty string), an optional user navigation involvement userInvolvement (default " none "), an optional Element sourceElement (default null), an optional boolean initialInsertion (default false), and an optional navigation API method tracker -or-null apiMethodTracker (default null): Let cspNavigationType be " form-submission " if formDataEntryList is non-null; otherwise " other ". Let sourceSnapshotParams be the result of snapshotting source snapshot params given sourceDocument Let initiatorOriginSnapshot be a new opaque origin Let initiatorBaseURLSnapshot be about:blank If sourceDocument is null: Assert userInvolvement is browser UI ". If url 's scheme is " javascript ", then set initiatorOriginSnapshot to navigable 's active document 's origin Otherwise: Assert userInvolvement is not " browser UI ". If sourceDocument 's node navigable is not allowed by sandboxing to navigate navigable given sourceSnapshotParams If exceptionsEnabled is true, then throw a SecurityError DOMException Return. Set initiatorOriginSnapshot to sourceDocument 's origin Set initiatorBaseURLSnapshot to sourceDocument 's document base URL Let navigationId be the result of generating a random UUID [WEBCRYPTO] If the surrounding agent is equal to navigable 's active document 's relevant agent , then continue these steps. Otherwise, queue a global task on the navigation and traversal task source given navigable 's active window to continue these steps. We do this because we are about to look at a lot of properties of navigable 's active document , which are in theory only accessible over in the appropriate event loop . (But, we do not want to unconditionally queue a task, since — for example — same-event-loop fragment navigations need to take effect synchronously.) Another implementation strategy would be to replicate the relevant information across event loops, or into a canonical "browser process", so that it can be consulted without queueing a task. This could give different results than what we specify here in edge cases, where the relevant properties have changed over in the target event loop but not yet been replicated. Further testing is needed to determine which of these strategies best matches browser behavior, in such racy edge cases. If navigable 's active document 's unload counter is greater than 0, then invoke WebDriver BiDi navigation failed with navigable and a WebDriver BiDi navigation status whose id is navigationId status is " canceled ", and url is url , and return. Let container be navigable 's container If container is an iframe element and will lazy load element steps given container returns true, then stop intersection-observing a lazy loading element container and set container 's lazy load resumption steps to null. If historyHandling is " auto ", then: If url equals navigable 's active document 's URL , and initiatorOriginSnapshot is same origin with navigable 's active document 's origin , then set historyHandling to replace ". Otherwise, set historyHandling to " push ". If the navigation must be a replace given url and navigable 's active document , then set historyHandling to " replace ". If all of the following are true: documentResource is null; response is null; url equals navigable 's active session history entry 's URL with exclude fragments set to true; and url 's fragment is non-null, then: Navigate to a fragment given navigable url historyHandling userInvolvement sourceElement navigationAPIState , and navigationId Return. If navigable 's parent is non-null, then set navigable 's is delaying load events to true. Let targetSnapshotParams be the result of snapshotting target snapshot params given navigable Invoke WebDriver BiDi navigation started with navigable and a new WebDriver BiDi navigation status whose id is navigationId status is " pending ", and url is url If navigable 's ongoing navigation is " traversal ", then: Invoke WebDriver BiDi navigation failed with navigable and a new WebDriver BiDi navigation status whose id is navigationId status is " canceled ", and url is url Return. Any attempts to navigate a navigable that is currently traversing are ignored. Set the ongoing navigation for navigable to navigationId This will have the effect of aborting other ongoing navigations of navigable , since at certain points during navigation changes to the ongoing will cause further work to be abandoned. If url 's scheme is " javascript ", then: Queue a global task on the navigation and traversal task source given navigable 's active window to navigate to a javascript: URL given navigable url historyHandling sourceSnapshotParams initiatorOriginSnapshot userInvolvement cspNavigationType initialInsertion , and navigationId Return. If all of the following are true: userInvolvement is not " browser UI "; navigable 's active document 's origin is same origin-domain with sourceDocument 's origin navigable 's active document 's is initial about:blank is false; and url 's scheme is a fetch scheme then: Let be navigable 's active window 's navigation API Let entryListForFiring be formDataEntryList if documentResource is a POST resource ; otherwise, null. Let navigationAPIStateForFiring be navigationAPIState if navigationAPIState is not null; otherwise, StructuredSerializeForStorage (undefined). Let continue be the result of firing a push/replace/reload navigate event at with navigationType set to historyHandling isSameDocument set to false, userInvolvement set to userInvolvement sourceElement set to sourceElement formDataEntryList set to entryListForFiring destinationURL set to url navigationAPIState set to navigationAPIStateForFiring , and apiMethodTracker set to apiMethodTracker If continue is false, then return. It is possible for navigations with userInvolvement of " browser UI " or initiated by a cross origin-domain sourceDocument to fire navigate events, if they go through the earlier navigate to a fragment path. If sourceDocument is navigable 's container document , then reserve deferred fetch quota for navigable 's container given url 's origin In parallel , run these steps: Let unloadPromptCanceled be the result of checking if unloading is canceled for navigable 's active document 's inclusive descendant navigables If unloadPromptCanceled is not " continue ", or navigable 's ongoing navigation is no longer navigationId Invoke WebDriver BiDi navigation failed with navigable and a new WebDriver BiDi navigation status whose id is navigationId status is " canceled ", and url is url Abort these steps. Queue a global task on the navigation and traversal task source given navigable 's active window to abort a document and its descendants given navigable 's active document Let documentState be a new document state with request referrer policy referrerPolicy initiator origin initiatorOriginSnapshot resource documentResource navigable target name navigable 's target name The navigable target name can get cleared under various conditions later in the navigation process, before the document state is finalized. If url matches about:blank or is about:srcdoc , then: Set documentState 's origin to initiatorOriginSnapshot Set documentState 's about base URL to initiatorBaseURLSnapshot Let historyEntry be a new session history entry , with its URL set to url and its document state set to documentState Let navigationParams be null. If response is non-null: The navigate algorithm is only supplied with a response as part of the object and embed processing models, or for processing parts of multipart/x-mixed-replace responses after the initial response. Let sourcePolicyContainer be a clone of the sourceDocument 's policy container , if sourceDocument is not null; otherwise null. Let policyContainer be the result of determining navigation params policy container given response 's URL null, sourcePolicyContainer navigable 's container document 's policy container , and null. Let finalSandboxFlags be the union of targetSnapshotParams 's sandboxing flags and policyContainer 's CSP list 's CSP-derived sandboxing flags Let responseOrigin be the result of determining the origin given response 's URL finalSandboxFlags , and documentState 's initiator origin Let coop be a new opener policy Let coopEnforcementResult be a new opener policy enforcement result with url response 's URL origin responseOrigin opener policy coop Set navigationParams to a new navigation params , with id navigationId navigable navigable request null response response fetch controller null commit early hints null COOP enforcement result coopEnforcementResult reserved environment null origin responseOrigin policy container policyContainer final sandboxing flag set finalSandboxFlags iframe element referrer policy targetSnapshotParams 's iframe element referrer policy opener policy coop navigation timing type navigate about base URL documentState 's about base URL user involvement userInvolvement Attempt to populate the history entry's document for historyEntry given navigable , " navigate ", sourceSnapshotParams targetSnapshotParams userInvolvement navigationId navigationParams cspNavigationType , with allowPOST set to true and completionSteps set to the following step: Append session history traversal steps to navigable 's traversable to finalize a cross-document given navigable historyHandling userInvolvement , and historyEntry 7.4.2.3 Ending navigation Although the usual cross-document navigation case will first foray into populating a session history entry with a Document , all navigations that don't get aborted will ultimately end up calling into one of the below algorithms. 7.4.2.3.1 The usual cross-document navigation case To finalize a cross-document navigation given a navigable navigable , a history handling behavior historyHandling , a user navigation involvement userInvolvement , and a session history entry historyEntry Assert : this is running on navigable 's traversable navigable's session history traversal queue Set navigable 's is delaying load events to false. If historyEntry 's document is null, then return. This means that attempting to populate the history entry's document ended up not creating a document, as a result of e.g., the navigation being canceled by a subsequent navigation, a 204 No Content response, etc. If all of the following are true: navigable 's parent is null; historyEntry 's document 's browsing context is not an auxiliary browsing context whose opener browsing context is non-null; and historyEntry 's document 's origin is not navigable 's active document 's origin then set historyEntry 's document state 's navigable target name to the empty string. Let entryToReplace be navigable 's active session history entry if historyHandling is " replace ", otherwise null. Let traversable be navigable 's traversable navigable Let targetStep be null. Let targetEntries be the result of getting session history entries for navigable If entryToReplace is null, then: Clear the forward session history of traversable Set targetStep to traversable 's current session history step + 1. Set historyEntry 's step to targetStep Append historyEntry to targetEntries Otherwise: Replace entryToReplace with historyEntry in targetEntries Set historyEntry 's step to entryToReplace 's step If historyEntry 's document state 's origin is same origin with entryToReplace 's document state 's origin , then set historyEntry 's navigation API key to entryToReplace 's navigation API key Set targetStep to traversable 's current session history step Apply the push/replace history step targetStep to traversable given historyHandling and userInvolvement 7.4.2.3.2 The javascript: URL special case javascript: URLs have a dedicated label on the issue tracker documenting various problems with their specification. To navigate to a javascript: URL , given a navigable targetNavigable , a URL url , a history handling behavior historyHandling , a source snapshot params sourceSnapshotParams , an origin initiatorOrigin , a user navigation involvement userInvolvement , a string cspNavigationType , a boolean initialInsertion , and a ID navigationId Assert historyHandling is " replace ". If targetNavigable 's ongoing navigation is no longer navigationId , then return. Set the ongoing navigation for targetNavigable to null. If initiatorOrigin is not same origin-domain with targetNavigable 's active document 's origin , then return. Let request be a new request whose URL is url and whose policy container is sourceSnapshotParams 's source policy container This is a synthetic request solely for plumbing into the next step. It will never hit the network. If the result of should navigation request of type be blocked by Content Security Policy? given request and cspNavigationType is " Blocked ", then return. [CSP] Let newDocument be the result of evaluating a javascript: URL given targetNavigable url initiatorOrigin , and userInvolvement If newDocument is null: If initialInsertion is true and targetNavigable 's active document 's is initial about:blank is true, then run the iframe load event steps given targetNavigable 's container Return. In this case, some JavaScript code was executed, but no new Document was created, so we will not perform a navigation. Assert initiatorOrigin is newDocument 's origin Let entryToReplace be targetNavigable 's active session history entry Let oldDocState be entryToReplace 's document state Let documentState be a new document state with document newDocument history policy container clone of the oldDocState 's history policy container if it is non-null; null otherwise request referrer oldDocState 's request referrer request referrer policy oldDocState 's request referrer policy or should this be the referrerPolicy that was passed to navigate initiator origin initiatorOrigin origin initiatorOrigin about base URL oldDocState 's about base URL resource null ever populated true navigable target name oldDocState 's navigable target name Let historyEntry be a new session history entry , with URL entryToReplace 's URL document state documentState For the URL , we do not use url , i.e. the actual javascript: URL that the navigate algorithm was called with. This means javascript: URLs are never stored in session history, and so can never be traversed to. Append session history traversal steps to targetNavigable 's traversable to finalize a cross-document navigation with targetNavigable historyHandling userInvolvement , and historyEntry To evaluate a javascript: URL given a navigable targetNavigable , a URL url , an origin newDocumentOrigin , and a user navigation involvement userInvolvement Let urlString be the result of running the URL serializer on 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 Let settings be targetNavigable '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 script fetch options Let evaluationStatus be the result of running the classic script script Let result be null. If evaluationStatus is a normal completion, and evaluationStatus .[[Value]] is a String, then set result to evaluationStatus .[[Value]]. Otherwise, return null. Let response be a new response with URL targetNavigable 's active document 's URL header list « (` Content-Type `, ` text/html;charset=utf-8 `) » body the UTF-8 encoding of result as a body The encoding to UTF-8 means that unpaired surrogates will not roundtrip, once the HTML parser decodes the response body. Let policyContainer be targetNavigable 's active document 's policy container Let finalSandboxFlags be policyContainer 's CSP list 's CSP-derived sandboxing flags Let coop be targetNavigable 's active document 's opener policy Let coopEnforcementResult be a new opener policy enforcement result with url url origin newDocumentOrigin opener policy coop Let navigationParams be a new navigation params , with id navigationId navigable targetNavigable request null this will cause the referrer of the resulting Document to be null; is that correct? response response fetch controller null commit early hints null COOP enforcement result coopEnforcementResult reserved environment null origin newDocumentOrigin policy container policyContainer final sandboxing flag set finalSandboxFlags iframe element referrer policy targetSnapshotParams 's iframe element referrer policy opener policy coop navigation timing type navigate about base URL targetNavigable 's active document 's about base URL user involvement userInvolvement Return the result of loading an HTML document given navigationParams 7.4.2.3.3 Fragment navigations To navigate to a fragment given a navigable navigable , a URL url , a history handling behavior historyHandling , a user navigation involvement userInvolvement an Element -or-null sourceElement , a serialized state -or-null navigationAPIState , and a navigation ID navigationId Let be navigable 's active window 's navigation API Let destinationNavigationAPIState be navigable 's active session history entry 's navigation API state If navigationAPIState is not null, then set destinationNavigationAPIState to navigationAPIState Let continue be the result of firing a push/replace/reload navigate event at with navigationType set to historyHandling isSameDocument set to true, userInvolvement set to userInvolvement sourceElement set to sourceElement destinationURL set to url , and navigationAPIState set to destinationNavigationAPIState If continue is false, then return. Let historyEntry be a new session history entry , with URL url document state navigable 's active session history entry 's document state navigation API state destinationNavigationAPIState scroll restoration mode navigable 's active session history entry 's scroll restoration mode For navigations performed with navigation.navigate() , the value provided by the state option is used for the new navigation API state . (This will set it to the serialization of undefined, if no value is provided for that option.) For other fragment navigations, including user-initiated ones, the navigation API state is carried over from the previous entry. The classic history API state is never carried over. Let entryToReplace be navigable 's active session history entry if historyHandling is " replace ", otherwise null. Let history be navigable 's active document 's history object Let scriptHistoryIndex be history 's index Let scriptHistoryLength be history 's length If historyHandling is " push ", then: Set history 's state to null. Increment scriptHistoryIndex Set scriptHistoryLength to scriptHistoryIndex + 1. Set navigable 's active document 's URL to url Set navigable 's active session history entry to historyEntry Update document for history step application given navigable 's active document historyEntry , true, scriptHistoryIndex scriptHistoryLength , and historyHandling This algorithm will be called twice as a result of a single fragment navigation: once synchronously, where best-guess values scriptHistoryIndex and scriptHistoryLength are set, history.state is nulled out, and various events are fired; and once asynchronously, where the final values for index and length are set, history.state remains untouched, and no events are fired. Scroll to the fragment given navigable 's active document If the scrolling fails because the Document is new and the relevant ID has not yet been parsed, then the second asynchronous call to update document for history step application will take care of scrolling. Let traversable be navigable 's traversable navigable Append the following session history synchronous navigation steps involving navigable to traversable Finalize a same-document navigation given traversable navigable historyEntry entryToReplace historyHandling , and userInvolvement Invoke WebDriver BiDi fragment navigated with navigable and a new WebDriver BiDi navigation status whose id is navigationId url is url , and status is " complete ". To finalize a same-document navigation given a traversable navigable traversable , a navigable targetNavigable , a session history entry targetEntry , a session history entry -or-null entryToReplace , a history handling behavior historyHandling and a user navigation involvement userInvolvement This is used by both fragment navigations and by the URL and history update steps , which are the only synchronous updates to session history. By virtue of being synchronous, those algorithms are performed outside of the top-level traversable 's session history traversal queue . This puts them out of sync with the top-level traversable 's current session history step , so this algorithm is used to resolve conflicts due to race conditions. Assert : this is running on traversable 's session history traversal queue If targetNavigable 's active session history entry is not targetEntry , then return. Let targetStep be null. Let targetEntries be the result of getting session history entries for targetNavigable If entryToReplace is null, then: Clear the forward session history of traversable Set targetStep to traversable 's current session history step + 1. Set targetEntry 's step to targetStep Append targetEntry to targetEntries Otherwise: Replace entryToReplace with targetEntry in targetEntries Set targetEntry 's step to entryToReplace 's step Set targetStep to traversable 's current session history step Apply the push/replace history step targetStep to traversable given historyHandling and userInvolvement This is done even for " replace " navigations, as it resolves race conditions across multiple synchronous navigations. 7.4.2.3.4 Non-fetch schemes and external software The input to attempt to create a non-fetch scheme document is the non-fetch scheme navigation params struct . It is a lightweight version of navigation params which only carries parameters relevant to the non- fetch scheme navigation case. It has the following items id null or a navigation ID navigable the navigable experiencing the navigation URL URL target snapshot sandboxing flags the target snapshot params 's sandboxing flags present during navigation source snapshot has transient activation a copy of the source snapshot params 's has transient activation boolean present during activation initiator origin an origin possibly for use in a user-facing prompt to confirm the invocation of an external software package This differs slightly from a document state 's initiator origin in that a non-fetch scheme navigation params 's initiator origin follows redirects up to the last fetch scheme URL in a redirect chain that ends in a non- fetch scheme URL. navigation timing type NavigationTimingType used for creating the navigation timing entry for the new Document (if one is created) user involvement user navigation involvement used when obtaining a browsing context for the new Document (if one is created) To attempt to create a non-fetch scheme document given a non-fetch scheme navigation params navigationParams Let url be navigationParams 's URL Let navigable be navigationParams 's navigable If url is to be handled using a mechanism that does not affect navigable , e.g., because url 's scheme is handled externally, then: Hand-off to external software given url navigable navigationParams 's target snapshot sandboxing flags navigationParams 's source snapshot has transient activation , and navigationParams 's initiator origin Return null. Handle url 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 a registered handler for the given scheme. Return the result of displaying the inline content given navigable navigationParams 's id navigationParams 's timing type , and navigationParams 's user involvement 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 , a navigable navigable , a sandboxing flag set sandboxFlags , a boolean hasTransientActivation , and an origin initiatorOrigin , user agents should: If all of the following are true: navigable is not a top-level traversable sandboxFlags has its sandboxed custom protocols navigation browsing context flag set; and sandboxFlags has its sandboxed top-level navigation with user activation browsing context flag set, or hasTransientActivation is false, then return without invoking the external software package. Navigation inside an iframe toward external software can be seen by users as a new popup or a new top-level navigation. That's why its is allowed in sandboxed iframe only when one of allow-popups allow-top-navigation allow-top-navigation-by-user-activation or allow-top-navigation-to-custom-protocols is specified. 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 initiatorOrigin 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. 7.4.2.4 Preventing navigation A couple of scenarios can intervene early in the navigation process and put the whole thing to a halt. This can be especially exciting when multiple navigables are navigating at the same time, due to a session history traversal. navigable source is allowed by sandboxing to navigate a second navigable target , given a source snapshot params sourceSnapshotParams , if the following steps return true: If source is target , then return true. If source is an ancestor of target , then return true. If target is an ancestor of source , then: If target is not a top-level traversable , then return true. If sourceSnapshotParams 's has transient activation is true, and sourceSnapshotParams 's sandboxing flags 's sandboxed top-level navigation with user activation browsing context flag is set, then return false. If sourceSnapshotParams 's has transient activation is false, and sourceSnapshotParams 's sandboxing flags 's sandboxed top-level navigation without user activation browsing context flag is set, then return false. Return true. If target is a top-level traversable If source is the one permitted sandboxed navigator of target , then return true. If sourceSnapshotParams 's sandboxing flags 's sandboxed navigation browsing context flag is set, then return false. Return true. If sourceSnapshotParams 's sandboxing flags 's sandboxed navigation browsing context flag is set, then return false. Return true. To check if unloading is canceled for a list of navigables navigablesThatNeedBeforeUnload , given an optional traversable navigable traversable , an optional integer targetStep , and an optional user navigation involvement userInvolvementForNavigateEvent , run these steps. They return " canceled-by-beforeunload ", " canceled-by-navigate ", or continue ". Let documentsToFireBeforeunload be the active document of each item in navigablesThatNeedBeforeUnload Let unloadPromptShown be false. Let finalStatus be " continue ". If traversable was given, then: Assert targetStep and userInvolvementForNavigateEvent were given. Let targetEntry be the result of getting the target history entry given traversable and targetStep If targetEntry is not traversable 's current session history entry , and targetEntry 's document state 's origin is the same as traversable 's current session history entry 's document state 's origin , then: In this case, we're going to fire the navigate event for traversable here. Because under some circumstances it might be canceled, we need to do this separately from other traversal navigate events , which happen later. Additionally, because we want beforeunload events to fire before navigate events, this means we need to fire beforeunload for traversable here (if applicable), instead of doing it as part of the below loop over documentsToFireBeforeunload Let eventsFired be false. Let needsBeforeunload be true if navigablesThatNeedBeforeUnload contains traversable ; otherwise false. If needsBeforeunload is true, then remove traversable 's active document from documentsToFireBeforeunload Queue a global task on the navigation and traversal task source given traversable 's active window to perform the following steps: If needsBeforeunload is true, then: Let ( unloadPromptShownForThisDocument unloadPromptCanceledByThisDocument ) be the result of running the steps to fire beforeunload given traversable 's active document and false. If unloadPromptShownForThisDocument is true, then set unloadPromptShown to true. If unloadPromptCanceledByThisDocument is true, then set finalStatus to " canceled-by-beforeunload ". If finalStatus is " canceled-by-beforeunload ", then abort these steps. Let be traversable 's active window 's API Let navigateEventResult be the result of firing a traverse navigate event at given targetEntry and userInvolvementForNavigateEvent If navigateEventResult is false, then set finalStatus to canceled-by-navigate ". Set eventsFired to true. Wait until eventsFired is true. If finalStatus is not " continue ", then return finalStatus Let totalTasks be the size of documentsToFireBeforeunload Let completedTasks be 0. For each document of documentsToFireBeforeunload queue a global task on the navigation and traversal task source given document 's relevant global object to run the steps: Let ( unloadPromptShownForThisDocument unloadPromptCanceledByThisDocument ) be the result of running the steps to fire beforeunload given document and unloadPromptShown If unloadPromptShownForThisDocument is true, then set unloadPromptShown to true. If unloadPromptCanceledByThisDocument is true, then set finalStatus to " canceled-by-beforeunload ". Increment completedTasks Wait for completedTasks to be totalTasks Return finalStatus The steps to fire beforeunload given a Document document and a boolean unloadPromptShown are: Let unloadPromptCanceled be false. Increase the document 's unload counter by 1. Increase document 's relevant agent 's event loop 's termination nesting level by 1. Let eventFiringResult be the result of firing an event named beforeunload at document 's relevant global object , using BeforeUnloadEvent with the cancelable attribute initialized to true. Decrease document 's relevant agent 's event loop 's termination nesting level by 1. If all of the following are true: unloadPromptShown is false; document 's active sandboxing flag set does not have its sandboxed modals flag set; document 's relevant global object has sticky activation eventFiringResult is false, or the returnValue attribute of event is not the empty string; and showing an unload prompt is unlikely to be annoying, deceptive, or pointless, then: Set unloadPromptShown to true. Let userPromptHandler be the result of WebDriver BiDi user prompt opened with document 's relevant global object beforeunload ", and "". If userPromptHandler is " dismiss ", then set unloadPromptCanceled to true. If userPromptHandler is " none ", then: Ask the user to confirm that they wish to unload the document, and pause while waiting for the user's response. 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. If the user did not confirm the page navigation, then set unloadPromptCanceled to true. Invoke WebDriver BiDi user prompt closed with document 's relevant global object , " beforeunload ", and true if unloadPromptCanceled is false or false otherwise. Decrease document 's unload counter by 1. Return ( unloadPromptShown unloadPromptCanceled ). 7.4.2.5 Aborting navigation Each navigable has an ongoing navigation which is a navigation ID , " traversal ", or null, initially null. It is used to track navigation aborting and to prevent any navigations from taking place during traversal To set the ongoing navigation for a navigable navigable to newValue If navigable 's ongoing navigation is equal to newValue then return. Inform the navigation API about aborting navigation given navigable Set navigable 's ongoing navigation to newValue 7.4.3 Reloading and traversing To reload navigable navigable given an optional serialized state -or-null navigationAPIState (default null), an optional user navigation involvement userInvolvement (default " none "), and an optional navigation API method tracker -or-null apiMethodTracker (default null): If userInvolvement is not " browser UI ", then: Let be navigable 's active window 's navigation API Let destinationNavigationAPIState be navigable 's active session history entry 's navigation API state If navigationAPIState is not null, then set destinationNavigationAPIState to navigationAPIState Let continue be the result of firing a push/replace/reload navigate event at with navigationType set to " reload ", isSameDocument set to false, userInvolvement set to userInvolvement destinationURL set to navigable 's active session history entry 's URL navigationAPIState set to destinationNavigationAPIState , and apiMethodTracker set to apiMethodTracker If continue is false, then return. Set navigable 's active session history entry 's document state 's reload pending to true. Let traversable be navigable 's traversable navigable Append the following session history traversal steps to traversable Apply the reload history step to traversable given userInvolvement To traverse the history by a delta given a traversable navigable traversable , an integer delta , and an optional Document sourceDocument Let sourceSnapshotParams and initiatorToCheck be null. Let userInvolvement be " browser UI ". If sourceDocument is given, then: Set sourceSnapshotParams to the result of snapshotting source snapshot params given sourceDocument Set initiatorToCheck to sourceDocument 's node navigable Set userInvolvement to " none ". Append the following session history traversal steps to traversable Let allSteps be the result of getting all used history steps for traversable Let currentStepIndex be the index of traversable 's current session history step within allSteps Let targetStepIndex be currentStepIndex plus delta If allSteps targetStepIndex ] does not exist , then abort these steps. Apply the traverse history step allSteps targetStepIndex ] to traversable , given sourceSnapshotParams initiatorToCheck , and userInvolvement 7.4.4 Non-fragment synchronous "navigations" Apart from the navigate algorithm, session history entries can be pushed or replaced via one more mechanism, the URL and history update steps . The most well-known callers of these steps are the history.replaceState() and history.pushState() APIs, but various other parts of the standard also need to perform updates to the active history entry , and they use these steps to do so. The URL and history update steps , given a Document document , a URL newURL , an optional serialized state -or-null serializedData (default null), and an optional history handling behavior historyHandling (default " replace "), are: Let navigable be document 's node navigable Let activeEntry be navigable 's active session history entry Let newEntry be a new session history entry , with URL newURL serialized state if serializedData is not null, serializedData ; otherwise activeEntry 's classic history API state document state activeEntry 's document state scroll restoration mode activeEntry 's scroll restoration mode persisted user state activeEntry 's persisted user state If document 's is initial about:blank is true, then set historyHandling to " replace ". This means that pushState() on an initial about:blank Document behaves as a replaceState() call. Let entryToReplace be activeEntry if historyHandling is replace ", otherwise null. If historyHandling is " push ", then: Increment document 's history object 's index Set document 's history object 's length to its index + 1. These are temporary best-guess values for immediate synchronous access. If serializedData is not null, then restore the history object state given document and newEntry Set the URL given document to newURL Since this is neither a nor a history traversal , it does not cause a hashchange event to be fired. Set document 's latest entry to newEntry Set navigable 's active session history entry to newEntry Update the navigation API entries for a same-document navigation given document 's relevant global object 's navigation API newEntry , and historyHandling Let traversable be navigable 's traversable navigable Append the following session history synchronous navigation steps involving navigable to traversable Finalize a same-document navigation given traversable navigable newEntry entryToReplace historyHandling , and " none ". Invoke WebDriver BiDi history updated with navigable Although both fragment navigation and the URL and history update steps perform synchronous history updates, only fragment navigation contains a synchronous call to update document for history step application . The URL and history update steps instead perform a few select updates inside the above algorithm, omitting others. This is somewhat of an unfortunate historical accident, and generally leads to web-developer sadness about the inconsistency. For example, this means that popstate events fire for fragment navigations, but not for history.pushState() calls. 7.4.5 Populating a session history entry As explained in the overview , both and traversal involve creating a session history entry and then attempting to populate its document member, so that it can be presented inside the navigable This involves either: using an already-given response ; using the srcdoc resource stored in the session history entry ; or fetching . The process has several failure modes, which can either result in doing nothing (leaving the navigable on its currently- active Document ) or can result in populating the session history entry with an error document To attempt to populate the history entry's document for a session history entry entry , given a navigable navigable , a NavigationTimingType navTimingType , a source snapshot params sourceSnapshotParams , a target snapshot params targetSnapshotParams , a user navigation involvement userInvolvement , an optional navigation ID -or-null navigationId (default null), an optional navigation params -or-null navigationParams (default null), an optional string cspNavigationType (default " other "), an optional boolean allowPOST (default false), and optional algorithm steps completionSteps (default an empty algorithm): Assert : this is running in parallel Assert : if navigationParams is non-null, then navigationParams 's response is non-null. Let documentResource be entry 's document state 's resource If navigationParams is null, then: If documentResource is a string, then set navigationParams to the result of creating navigation params from a srcdoc resource given entry navigable targetSnapshotParams userInvolvement navigationId , and navTimingType Otherwise, if all of the following are true: entry 's URL 's scheme is a fetch scheme ; and documentResource is null, or allowPOST is true and documentResource 's request body is not failure, then set navigationParams to the result of creating navigation params by fetching given entry navigable sourceSnapshotParams targetSnapshotParams cspNavigationType userInvolvement navigationId , and navTimingType Otherwise, if entry 's URL 's scheme is not a fetch scheme , then set navigationParams to a new non-fetch scheme navigation params with id navigationId navigable navigable URL entry 's URL target snapshot sandboxing flags targetSnapshotParams 's sandboxing flags source snapshot has transient activation sourceSnapshotParams 's has transient activation initiator origin entry 's document state 's initiator origin navigation timing type navTimingType user involvement userInvolvement Queue a global task on the navigation and traversal task source given navigable 's active window , to run these steps: If navigable 's ongoing navigation no longer equals navigationId , then run completionSteps and abort these steps. Let saveExtraDocumentState be true. Usually, in the cases where we end up populating entry 's document state 's document , we then want to save some of the state from that Document into entry . This ensures that if there are future traversals to entry where its document has been destroyed , we can use that state when creating a new Document However, in some specific cases, saving the state would be unhelpful. For those, we set saveExtraDocumentState to false later in this algorithm. If navigationParams is a non-fetch scheme navigation params then: Set entry 's document state 's document to the result of running attempt to create a non-fetch scheme document given navigationParams This can result in setting entry 's document state 's document to null, e.g., when handing-off to external software Set saveExtraDocumentState to false. Otherwise, if any of the following are true: navigationParams is null; the result of should navigation response to navigation request of type in target be blocked by Content Security Policy? given navigationParams 's request navigationParams 's response navigationParams 's policy container 's CSP list cspNavigationType , and navigable is " Blocked "; navigationParams 's reserved environment is non-null and the result of checking a navigation response's adherence to its embedder policy given navigationParams 's response navigable , and navigationParams 's policy container 's embedder policy is false; or the result of checking a navigation response's adherence to X-Frame-Options given navigationParams 's response navigable navigationParams 's policy container 's CSP list , and navigationParams 's origin is false, then: Set entry 's document state 's document to the result of creating a document for inline content that doesn't have a DOM , given navigable , null, navTimingType , and userInvolvement . The inline content should indicate to the user the sort of error that occurred. Make document unsalvageable given entry 's document state 's document and " navigation-failure ". Set saveExtraDocumentState to false. If navigationParams is not null, then: Run the environment discarding steps for navigationParams 's reserved environment Invoke WebDriver BiDi navigation failed with navigable and a new WebDriver BiDi navigation status whose id is navigationId status is " canceled ", and url is navigationParams 's response 's URL Otherwise, if navigationParams 's response has a ` Content-Disposition ` header specifying the attachment disposition type, then: Let sourceAllowsDownloading be sourceSnapshotParams 's allows downloading Let targetAllowsDownloading be false if navigationParams 's final sandboxing flag set has the sandboxed downloads browsing context flag set; otherwise true. Let uaAllowsDownloading be true. Optionally, the user agent may set uaAllowsDownloading to false, if it believes doing so would safeguard the user from a potentially hostile download. If sourceAllowsDownloading targetAllowsDownloading , and uaAllowsDownloading are true, then: Handle as a download navigationParams 's response with navigable and navigationId This branch leaves entry 's document state 's document as null. Otherwise, if navigationParams 's response 's status is not 204 and is not 205, then set entry 's document state 's document to the result of loading a document given navigationParams sourceSnapshotParams , and entry 's document state 's initiator origin This can result in setting entry 's document state 's document to null, e.g., when handing-off to external software If entry 's document state 's document is not null, then: Set entry 's document state 's ever populated to true. If saveExtraDocumentState is true: Let document be entry 's document state 's document Set entry 's document state 's origin to document 's origin If document 's URL requires storing the policy container in history , then: Assert navigationParams is a params (i.e., neither null nor a non-fetch scheme navigation params ). Set entry 's document state 's history policy container to navigationParams 's policy container If entry 's document state 's request referrer is " client ", and navigationParams is a params (i.e., neither null nor a non-fetch scheme navigation params ), then: Assert navigationParams 's request is not null. Set entry 's document state 's request referrer to navigationParams 's request 's referrer Run completionSteps To create navigation params from a srcdoc resource given a session history entry entry , a navigable navigable , a target snapshot params targetSnapshotParams , a user navigation involvement userInvolvement , a navigation ID -or-null navigationId , and a NavigationTimingType navTimingType Let documentResource be entry 's document state 's resource Let response be a new response with URL about:srcdoc header list « (` Content-Type `, ` text/html `) » body the UTF-8 encoding of documentResource as a body Let responseOrigin be the result of determining the origin given response 's URL targetSnapshotParams 's sandboxing flags , and entry 's document state 's origin Let coop be a new opener policy Let coopEnforcementResult be a new opener policy enforcement result with url response 's URL origin responseOrigin opener policy coop Let policyContainer be the result of determining navigation params policy container given response 's URL entry 's document state 's history policy container , null, navigable 's container document 's policy container , and null. Return a new navigation params , with id navigationId navigable navigable request null response response fetch controller null commit early hints null COOP enforcement result coopEnforcementResult reserved environment null origin responseOrigin policy container policyContainer final sandboxing flag set targetSnapshotParams 's sandboxing flags iframe element referrer policy targetSnapshotParams 's iframe element referrer policy opener policy coop navigation timing type navTimingType about base URL entry 's document state 's about base URL user involvement userInvolvement To create navigation params by fetching given a session history entry entry , a navigable navigable , a source snapshot params sourceSnapshotParams , a target snapshot params targetSnapshotParams , a string cspNavigationType , a user navigation involvement userInvolvement , a navigation ID -or-null navigationId , and a NavigationTimingType navTimingType , perform the following steps. They return a navigation params , a non-fetch scheme navigation params , or null. This algorithm mutates entry Assert : this is running in parallel Let documentResource be entry 's document state 's resource Let request be a new request , with url entry 's URL client sourceSnapshotParams 's fetch client destination document The destination is updated below when navigable has a container credentials mode include use-URL-credentials flag set redirect mode manual replaces client id navigable 's active document 's relevant settings object 's id mode navigate referrer entry 's document state 's request referrer referrer policy entry 's document state 's request referrer policy policy container sourceSnapshotParams 's source policy container traversable for user prompts navigable 's top-level traversable If navigable is a top-level traversable , then set request 's top-level navigation initiator origin to entry 's document state 's initiator origin If request 's client is null: This only occurs in the case of a browser UI-initiated navigation. Set request 's origin to a new opaque origin Set request 's service-workers mode to " all ". Set request 's referrer to no-referrer ". If documentResource is a POST resource Set request 's method to ` POST `. Set request 's body to documentResource 's request body Set Content-Type to documentResource 's request content-type in request 's header list If entry 's document state 's reload pending is true, then set request 's reload-navigation flag Otherwise, if entry 's document state 's ever populated is true, then set request 's history-navigation flag If sourceSnapshotParams 's has transient activation is true, then set request 's user-activation to true. If navigable 's container is non-null: If the navigable 's container has a browsing context scope origin , then set request 's origin to that browsing context scope origin Set request 's destination to navigable 's container 's local name If sourceSnapshotParams 's fetch client is navigable 's container document 's relevant settings object , then set request 's initiator type to navigable 's container 's local name This ensure that only container-initiated navigations are reported to resource timing. Let response be null. Let responseOrigin be null. Let fetchController be null. Let coopEnforcementResult be a new opener policy enforcement result , with url navigable 's active document 's URL origin navigable 's active document 's origin opener policy navigable 's active document 's opener policy current context is navigation source true if navigable 's active document 's origin is same origin with entry 's document state 's initiator origin otherwise false Let finalSandboxFlags be an empty sandboxing flag set Let responsePolicyContainer be null. Let responseCOOP be a new opener policy Let locationURL be null. Let currentURL be request 's current URL Let commitEarlyHints be null. While true: 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. Set commitEarlyHints to null. Preloaded links from early hint headers remain in the preload cache after a same origin redirect, but get discarded when the redirect is cross-origin. If request 's reserved client is null, then: Let topLevelCreationURL be currentURL Let topLevelOrigin be null. If navigable is not a top-level traversable , then: Let parentEnvironment be navigable 's parent 's active document 's relevant settings object Set topLevelCreationURL to parentEnvironment 's top-level creation URL Set 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 navigable 's active browsing context 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 cspNavigationType is " Blocked ", then set response to a network error and break [CSP] Set response to null. If fetchController is null, then set fetchController to the result of fetching request , with processEarlyHintsResponse set to processEarlyHintsResponse as defined below, processResponse set to processResponse as defined below, and useParallelQueue set to true. Let processEarlyHintsResponse be the following algorithm given a response earlyResponse If commitEarlyHints is null, then set commitEarlyHints to the result of processing early hint headers given earlyResponse and request 's reserved client Let processResponse be the following algorithm given a response fetchedResponse Set response to fetchedResponse Otherwise, process the next manual redirect for fetchController This will result in calling the processResponse we supplied above, during our first iteration through the loop, and thus setting response Navigation handles redirects manually as navigation is the only place in the web platform that cares for redirects to mailto: URLs and such. Wait until either response is non-null, or navigable 's ongoing changes to no longer equal navigationId If the latter condition occurs, then abort fetchController , and return. Otherwise, proceed onward. If request 's body is null, then set entry 's document state 's resource to null. Fetch unsets the body for particular redirects. Set responsePolicyContainer to the result of creating a policy container from a fetch response given response and request 's reserved client Set finalSandboxFlags to the union of targetSnapshotParams 's sandboxing flags and responsePolicyContainer 's CSP list 's CSP-derived sandboxing flags Set responseOrigin to the result of determining the origin given response 's URL finalSandboxFlags , and entry 's document state 's initiator origin If response is a redirect, then response 's URL will be the URL that led to the redirect to response 's location URL ; it will not be the location URL itself. If navigable is a top-level traversable , then: Set responseCOOP to the result of obtaining an opener policy given response and request 's reserved client Set coopEnforcementResult to the result of enforcing the response's opener policy given navigable 's active browsing context response 's URL responseOrigin responseCOOP coopEnforcementResult , and request 's referrer If finalSandboxFlags 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 opener policy and sandbox the result of navigating to that response. If response is not a network error navigable is a child navigable , and the result of performing a cross-origin resource policy check with navigable 's container document 's origin navigable '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 navigable rather than navigable itself. 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 failure or null, then break Assert locationURL is a URL Set entry 's classic history API state to StructuredSerializeForStorage (null). Let oldDocState be entry 's document state Set entry 's document state to a new document state , with history policy container clone of the oldDocState 's history policy container if it is non-null; null otherwise request referrer oldDocState 's request referrer request referrer policy oldDocState 's request referrer policy initiator origin oldDocState 's initiator origin origin oldDocState 's origin about base URL oldDocState 's about base URL resource oldDocState 's resource ever populated oldDocState 's ever populated navigable target name oldDocState 's navigable target name For the navigation case, only entry referenced oldDocState , which was created early in the navigate algorithm . So for navigations, this is functionally just an update to entry 's document state . For the traversal case, it's possible adjacent session history entries also reference oldDocState , in which case they will continue doing so even after we've updated entry 's document state oldDocState 's history policy container is only ever non-null here in the traversal case, after we've populated it during a navigation to a URL that requires storing the policy container in history The setup is given by the following Jake diagram top /a /a#foo /a#bar /b Also assume that the document state shared by the entries in steps 0, 1, and 2 has a null document , i.e., bfcache is not in play. Now consider the scenario where we traverse back to step 2, but this time when fetching /a , the server responds with a ` Location header pointing to /c . That is, locationURL points to /c and so we have reached this step instead of breaking out of the loop. In this case, we replace the document state of the session history entry occupying step 2, but we do not replace the document state of the entries occupying steps 0 and 1. The resulting Jake diagram looks like this: top /a /a#foo /c#bar /b Note that we perform this replacement even if we end up in a redirect chain back to the original URL, for example if /c itself had a ` Location ` header pointing to /a . Such a case would end up like so: top /a /a#foo /a#bar /b If locationURL 's scheme is not an HTTP(S) scheme , then: Set entry 's document state 's resource to null. Break Set currentURL to locationURL Set entry 's URL to currentURL By the end of this loop we will be in one of these scenarios: locationURL is failure, because of an unparseable ` Location ` header. locationURL is null, either because response is a network error or because we successfully fetched a non- network error HTTP(S) response with no ` Location ` header. locationURL is a URL with a non- HTTP(S) scheme If locationURL is a URL whose scheme is not a fetch scheme , then return a new non-fetch scheme navigation params , with id navigationId navigable navigable URL locationURL target snapshot sandboxing flags targetSnapshotParams 's sandboxing flags source snapshot has transient activation sourceSnapshotParams 's has transient activation initiator origin responseOrigin navigation timing type navTimingType user involvement userInvolvement At this point, request 's current URL is the last URL in the redirect chain with a fetch scheme before redirecting to a non- fetch scheme URL . It is this URL 's origin that will be used as the initiator origin for navigations to non- fetch scheme URLs If any of the following are true: response is a network error locationURL is failure; or locationURL is a URL whose scheme is a fetch scheme then return null. We allow redirects to non- fetch scheme URLs , but redirects to fetch scheme URLs that aren't HTTP(S) are treated like network errors. Assert locationURL is null and response is not a network error Let resultPolicyContainer be the result of determining navigation params policy container given response 's URL entry 's document state 's history policy container sourceSnapshotParams 's source policy container , null, and responsePolicyContainer If navigable 's container is an iframe , and response 's timing allow passed flag is set, then set navigable 's container 's pending resource-timing start time to null. If the iframe is allowed to report to resource timing, we don't need to run its fallback steps as the normal reporting would happen. Return a new navigation params , with id navigationId navigable navigable request request response response fetch controller fetchController commit early hints commitEarlyHints opener policy responseCOOP reserved environment request 's reserved client origin responseOrigin policy container resultPolicyContainer final sandboxing flag set finalSandboxFlags COOP enforcement result coopEnforcementResult navigation timing type navTimingType about base URL entry 's document state 's about base URL user involvement userInvolvement An element has a browsing context scope origin if its Document 's node navigable is a top-level traversable or if all of its Document 's ancestor navigables 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 This definition is broken and needs investigation to see what it was intended to express: see issue #4703 To load a document given navigation params navigationParams source snapshot params sourceSnapshotParams and origin initiatorOrigin , perform the following steps. They return a Document or null. Let type be the computed type of navigationParams 's 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 navigable , then skip this step. Otherwise, if the type is one of the following types: an HTML MIME type Return the result of loading an HTML document , given navigationParams an XML MIME type that is not an explicitly supported XML MIME type Return the result of loading an XML document given navigationParams and type JavaScript MIME type JSON MIME type that is not an explicitly supported JSON MIME type text/css text/plain text/vtt Return the result of loading a text document given navigationParams and type multipart/x-mixed-replace Return the result of loading a multipart/x-mixed-replace document , given navigationParams sourceSnapshotParams , and initiatorOrigin a supported image, video, or audio type Return the result of loading a media document given navigationParams and type application/pdf text/pdf If the user agent's PDF viewer supported is true, return the result of creating a document for inline content that doesn't have a DOM given navigationParams 's navigable navigationParams 's id navigationParams 's navigation timing type , and navigationParams 's user involvement Otherwise, proceed onward. 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, or for which the user agent has dedicated processing rules. For example, a web browser with a built-in Atom feed viewer would be said to explicitly support the application/atom+xml MIME type. 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, or for which the user agent has dedicated processing rules. In both cases, the external application or user agent will either display the content inline directly in navigationParams 's navigable , or hand it off to external software . Both happen in the steps below. 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 return the result of creating a document for inline content that doesn't have a DOM given navigationParams 's navigable navigationParams 's id navigationParams 's navigation timing type , and navigationParams 's user involvement Otherwise, the document's type is such that the resource will not affect navigationParams 's navigable , e.g., because the resource is to be handed to an external application or because it is an unknown type that will be processed by handle as a download Hand-off to external software given navigationParams 's response navigationParams 's navigable navigationParams 's final sandboxing flag set sourceSnapshotParams 's has transient activation , and initiatorOrigin Return null. 7.4.6 Applying the history step For both navigation and traversal, once we have an idea of where we want to head to in the session history, much of the work comes about in applying that notion to the traversable navigable and the relevant Document . For navigations, this work generally occurs toward the end of the process; for traversals, it is the beginning. 7.4.6.1 Updating the traversable Ensuring a traversable ends up at the right session history step is particularly complex, as it can involve coordinating across multiple navigable descendants of the traversable, populating them in parallel, and then synchronizing back up to ensure everyone has the same view of the result. This is further complicated by the existence of synchronous same-document navigations being mixed together with cross-document navigations, and how web pages have come to have certain relative timing expectations. changing navigable continuation state is used to store information during the apply the history step algorithm, allowing parts of the algorithm to continue only after other parts have finished. It is a struct with: displayed document Document target entry session history entry navigable navigable update only A boolean Although all updates to the traversable navigable end up in the same apply the history step algorithm, each possible entry point comes along with some minor customizations: To update for navigable creation/destruction given a traversable navigable traversable Let step be traversable 's current session history step Return the result of applying the history step step to traversable given false, null, null, " none ", and null. To apply the push/replace history step given a non-negative integer step to a traversable navigable traversable , given a history handling behavior historyHandling and a user navigation involvement userInvolvement Return the result of applying the history step step to traversable given false, null, null, userInvolvement , and historyHandling Apply the push/replace history step never passes source snapshot params or an initiator navigable to apply the history step . This is because those checks are done earlier in the algorithm. To apply the reload history step to a traversable navigable traversable given user navigation involvement userInvolvement Let step be traversable 's current session history step Return the result of applying the history step step to traversable given true, null, null, userInvolvement , and " reload ". Apply the reload history step never passes source snapshot params or an initiator navigable to apply the history step . This is because reloading is always treated as if it were done by the navigable itself, even in cases like parent.location.reload() To apply the traverse history step given a non-negative integer step to a traversable navigable traversable , with source snapshot params sourceSnapshotParams navigable initiatorToCheck and user navigation involvement userInvolvement Return the result of applying the history step step to traversable given true, sourceSnapshotParams initiatorToCheck userInvolvement , and " traverse ". To resume applying the traverse history step given a non-negative integer step , a traversable navigable traversable , and user navigation involvement userInvolvement apply step to traversable given false, null, null, userInvolvement , and " traverse ". When resuming a traverse, we are already past the cancelation, initiator, and source snapshot checks, and this traversal has already been determined to be a same-document traversal. Hence, we can pass false and null for those arguments. Now for the algorithm itself. To apply the history step given a non-negative integer step to a traversable navigable traversable , with boolean checkForCancelation source snapshot params -or-null sourceSnapshotParams navigable -or-null initiatorToCheck user navigation involvement userInvolvement and NavigationType -or-null navigationType , perform the following steps. They return " initiator-disallowed ", " canceled-by-beforeunload ", " canceled-by-navigate ", or applied ". Assert : This is running within traversable 's session history traversal queue Let targetStep be the result of getting the used step given traversable and step If initiatorToCheck is not null, then: Assert sourceSnapshotParams is not null. For each navigable of get all navigables whose current session history entry will change or reload : if initiatorToCheck is not allowed by sandboxing to navigate navigable given sourceSnapshotParams , then return " initiator-disallowed ". Let navigablesCrossingDocuments be the result of getting all navigables that might experience a cross-document traversal given traversable and targetStep If checkForCancelation is true, and the result of checking if unloading is canceled given navigablesCrossingDocuments traversable targetStep , and userInvolvement is not " continue ", then return that result. Let changingNavigables be the result of get all navigables whose current session history entry will change or reload given traversable and targetStep Let nonchangingNavigablesThatStillNeedUpdates be the result of getting all navigables that only need history object length/index update given traversable and targetStep For each navigable of changingNavigables Let targetEntry be the result of getting the target history entry given navigable and targetStep Set navigable 's current session history entry to targetEntry Set the ongoing navigation for navigable to " traversal ". Let totalChangeJobs be the size of changingNavigables Let completedChangeJobs be 0. Let changingNavigableContinuations be an empty queue of changing navigable continuation states This queue is used to split the operations on changingNavigables into two parts. Specifically, changingNavigableContinuations holds data for the second part For each navigable of changingNavigables queue a global task on the navigation and traversal task source of navigable 's active window to run the steps: This set of steps are split into two parts to allow synchronous navigations to be processed before documents unload. State is stored in changingNavigableContinuations for the second part Let displayedEntry be navigable 's active session history entry Let targetEntry be navigable 's current session history entry Let changingNavigableContinuation be a changing navigable continuation state with: displayed document displayedEntry 's document target entry targetEntry navigable navigable update-only false If displayedEntry is targetEntry and targetEntry 's document state 's reload pending is false, then: Set changingNavigableContinuation 's update-only to true. Enqueue changingNavigableContinuation on changingNavigableContinuations Abort these steps. This case occurs due to a synchronous navigation which already updated the active session history entry Switch on navigationType reload Assert targetEntry 's document state 's reload pending is true. traverse Assert targetEntry 's document state 's ever populated is true. replace Assert targetEntry 's step is displayedEntry 's step and targetEntry 's document state 's ever populated is false. push Assert targetEntry 's step is displayedEntry 's step + 1 and targetEntry 's document state 's ever populated is false. Let oldOrigin be targetEntry 's document state 's origin If all of the following are true: navigable is not traversable targetEntry is not navigable 's current session history entry ; and oldOrigin is the same as navigable 's current session history entry 's document state 's origin then: Let be navigable 's active window 's navigation API Fire a traverse navigate event at given targetEntry and userInvolvement If targetEntry 's document is null, or targetEntry 's document state 's reload pending is true, then: Let navTimingType be " back_forward " if targetEntry 's document is null; otherwise reload ". Let targetSnapshotParams be the result of snapshotting target snapshot params given navigable Let potentiallyTargetSpecificSourceSnapshotParams be sourceSnapshotParams If potentiallyTargetSpecificSourceSnapshotParams is null, then set it to the result of snapshotting source snapshot params given navigable 's active document In this case there is no clear source of the traversal/reload. We treat this situation as if navigable navigated itself, but note that some properties of targetEntry 's original initiator are preserved in targetEntry 's document state , such as the initiator origin and referrer , which will appropriately influence the navigation. Set targetEntry 's document state 's reload pending to false. Let allowPOST be targetEntry 's document state 's reload pending In parallel attempt to populate the history entry's document for targetEntry , given navigable potentiallyTargetSpecificSourceSnapshotParams targetSnapshotParams userInvolvement , with allowPOST set to allowPOST and completionSteps set to queue a global task on the navigation and traversal task source given navigable 's active window to run afterDocumentPopulated Otherwise, run afterDocumentPopulated immediately In both cases, let afterDocumentPopulated be the following steps: If targetEntry 's document is null, then set changingNavigableContinuation 's update-only to true. This means we tried to populate the document, but were unable to do so, e.g. because of the server returning a 204. These kinds of failed navigations or traversals will not be signaled to the navigation API (e.g., through the promises of any navigation API method tracker , or the navigateerror event). Doing so would leak information about the timing of responses from other origins, in the cross-origin case, and providing different results in the cross-origin vs. same-origin cases was deemed too confusing. However, implementations could use this opportunity to clear any promise handlers for the navigation.transition.finished promise, as they are guaranteed at this point to never run. And, they might wish to report a warning to the console if any part of the navigation API initiated these navigations, to make it clear to the web developer why their promises will never settle and events will never fire. If targetEntry 's document 's origin is not oldOrigin , then set targetEntry 's classic history API state to StructuredSerializeForStorage (null). This clears history state when the origin changed vs a previous load of targetEntry without a redirect occuring. This can happen due to a change in CSP sandbox headers. If all of the following are true: navigable 's parent is null; targetEntry 's document 's browsing context is not an auxiliary browsing context whose opener browsing context is non-null; and targetEntry 's document 's origin is not oldOrigin then set targetEntry 's document state 's navigable target name to the empty string. Enqueue changingNavigableContinuation on changingNavigableContinuations The rest of this job runs later in this algorithm. Let navigablesThatMustWaitBeforeHandlingSyncNavigation be an empty set While completedChangeJobs does not equal totalChangeJobs If traversable 's running nested apply history step is false, then: While traversable 's session history traversal queue 's algorithm set contains one or more synchronous navigation steps with a target navigable not contained in navigablesThatMustWaitBeforeHandlingSyncNavigation Let steps be the first item in traversable 's session history traversal queue 's algorithm set that is synchronous navigation steps with a target navigable not contained in navigablesThatMustWaitBeforeHandlingSyncNavigation Remove steps from traversable 's session history traversal queue 's algorithm set Set traversable 's running nested apply history step to true. Run steps Set traversable 's running nested apply history step to false. Synchronous navigations that are intended to take place before this traversal jump the queue at this point, so they can be added to the correct place in traversable 's session history entries before this traversal potentially unloads their document. More details can be found here Let changingNavigableContinuation be the result of dequeuing from changingNavigableContinuations If changingNavigableContinuation is nothing, then continue Let displayedDocument be changingNavigableContinuation 's displayed document Let targetEntry be changingNavigableContinuation 's target entry Let navigable be changingNavigableContinuation 's navigable Let ( scriptHistoryLength scriptHistoryIndex ) be the result of getting the history object length and index given traversable and targetStep These values might have changed since they were last calculated. Append navigable to navigablesThatMustWaitBeforeHandlingSyncNavigation Once a navigable has reached this point in traversal, additionally queued synchronous navigation steps are likely to be intended to occur after this traversal rather than before it, so they no longer jump the queue. More details can be found here Let entriesForNavigationAPI be the result of getting session history entries for the navigation API given navigable and targetStep If changingNavigableContinuation 's update-only is true, or targetEntry 's document is displayedDocument , then: This is a same-document navigation: we proceed without unloading. Set the ongoing navigation for navigable to null. This allows new navigations of navigable to start, whereas during the traversal they were blocked. Queue a global task on the navigation and traversal task source given navigable 's active window to perform afterPotentialUnloads Otherwise: Assert navigationType is not null. Deactivate displayedDocument , given userInvolvement targetEntry navigationType , and afterPotentialUnloads In both cases, let afterPotentialUnloads be the following steps: Let previousEntry be navigable 's active session history entry If changingNavigableContinuation 's update-only is false, then activate history entry targetEntry for navigable Let updateDocument be an algorithm step which performs update document for history step application given targetEntry 's document targetEntry changingNavigableContinuation 's update-only scriptHistoryLength scriptHistoryIndex navigationType entriesForNavigationAPI , and previousEntry If targetEntry 's document is equal to displayedDocument , then perform updateDocument Otherwise, queue a global task on the navigation and traversal task source given targetEntry 's document 's relevant global object to perform updateDocument Increment completedChangeJobs Let totalNonchangingJobs be the size of nonchangingNavigablesThatStillNeedUpdates This step onwards deliberately waits for all the previous operations to complete, as they include processing synchronous navigations which will also post tasks to update history length and index. Let completedNonchangingJobs be 0. Let ( scriptHistoryLength scriptHistoryIndex ) be the result of getting the history object length and index given traversable and targetStep For each navigable of nonchangingNavigablesThatStillNeedUpdates queue a global task on the navigation and traversal task source given navigable 's active window to run the steps: Let document be navigable 's active document Set document 's history object 's index to scriptHistoryIndex Set document 's history object 's length to scriptHistoryLength Increment completedNonchangingJobs Wait for completedNonchangingJobs to equal totalNonchangingJobs Set traversable 's current session history step to targetStep Return " applied ". To deactivate a document for a cross-document navigation given a Document displayedDocument , a user navigation involvement userNavigationInvolvement , a session history entry targetEntry NavigationType navigationType , and afterPotentialUnloads which is an algorithm that receives no arguments: Let navigable be displayedDocument 's node navigable Let potentiallyTriggerViewTransition be false. Let isBrowserUINavigation be true if userNavigationInvolvement is " browser UI "; otherwise false. Set potentiallyTriggerViewTransition to the result of calling can navigation trigger a cross-document view-transition? given displayedDocument targetEntry 's document navigationType , and isBrowserUINavigation If potentiallyTriggerViewTransition is false, then: Let firePageSwapBeforeUnload be the following step: Fire the pageswap event given displayedDocument targetEntry navigationType , and null. Set the ongoing navigation for navigable to null. This allows new navigations of navigable to start, whereas during the traversal they were blocked. Unload a document and its descendants given displayedDocument targetEntry 's document afterPotentialUnloads , and firePageSwapBeforeUnload Otherwise, queue a global task on the navigation and traversal task source given navigable 's active window to run the steps: Let proceedWithNavigationAfterViewTransitionCapture be the following step: Append the following session history traversal steps to navigable 's traversable navigable Set the ongoing navigation for navigable to null. This allows new navigations of navigable to start, whereas during the traversal they were blocked. Unload a document and its descendants given displayedDocument targetEntry 's document , and afterPotentialUnloads Let viewTransition be the result of setting up a cross-document view-transition given displayedDocument targetEntry 's document navigationType , and proceedWithNavigationAfterViewTransitionCapture Fire the pageswap event given displayedDocument targetEntry navigationType , and viewTransition If viewTransition is null, then run proceedWithNavigationAfterViewTransitionCapture In the case where a view transition started, the view transitions algorithms are responsible for calling proceedWithNavigationAfterViewTransitionCapture To fire the pageswap event given a Document displayedDocument , a session history entry targetEntry , a NavigationType navigationType , and a ViewTransition -or-null viewTransition Assert : this is running as part of a task queued on displayedDocument 's relevant agent 's event loop Let be displayedDocument 's relevant global object 's navigation API Let activation be null. If all of the following are true: targetEntry 's document 's origin is same origin with displayedDocument 's origin and targetEntry 's document 's was created via cross-origin redirects is false, or targetEntry 's document 's latest entry is not null, then: Let destinationEntry be determined by switching on navigationType reload The current entry of traverse The NavigationHistoryEntry in 's entry list whose session history entry is targetEntry push replace A new NavigationHistoryEntry in displayedDocument 's relevant realm with its session history entry set to targetEntry Set activation to a new NavigationActivation created in displayedDocument 's relevant realm , with old entry the current entry of new entry destinationEntry navigation type navigationType This means that a cross-origin redirect during a navigation would result in a null activation in the old document's PageSwapEvent , unless the new document is being restored from bfcache Fire an event named pageswap at displayedDocument 's relevant global object , using PageSwapEvent with its activation set to activation and its viewTransition set to viewTransition To activate history entry session history entry entry for navigable navigable Save persisted state to the navigable 's active session history entry Let newDocument be entry 's document Assert newDocument 's is initial about:blank is false, i.e., we never traverse back to the initial about:blank Document because it always gets replaced when we navigate away from it. Set navigable 's active session history entry to entry Make active newDocument Set the initial visibility state of newDocument to navigable 's traversable navigable 's system visibility state To get the used step given a traversable navigable traversable , and a non-negative integer step , perform the following steps. They return a non-negative integer. Let steps be the result of getting all used history steps within traversable Return the greatest item in steps that is less than or equal to step This caters for situations where there's no session history entry with step step , due to the removal of a navigable To get the history object length and index given a traversable navigable traversable , and a non-negative integer step , perform the following steps. They return a tuple of two non-negative integers. Let steps be the result of getting all used history steps within traversable Let scriptHistoryLength be the size of steps Assert steps contains step It is assumed that step has been adjusted by getting the used step Let scriptHistoryIndex be the index of step in steps Return ( scriptHistoryLength scriptHistoryIndex ). To get all navigables whose current session history entry will change or reload given a traversable navigable traversable , and a non-negative integer targetStep , perform the following steps. They return a list of navigables Let results be an empty list Let navigablesToCheck be « traversable ». This list is extended in the loop below. For each navigable of navigablesToCheck Let targetEntry be the result of getting the target history entry given navigable and targetStep If targetEntry is not navigable 's current session history entry or targetEntry 's document state 's reload pending is true, then append navigable to results If targetEntry 's document is navigable 's document , and targetEntry 's document state 's reload pending is false, then extend navigablesToCheck with the child navigables of navigable Adding child navigables to navigablesToCheck means those navigables will also be checked by this loop. Child navigables are only checked if the navigable 's active document will not change as part of this traversal. Return results To get all navigables that only need history object length/index update given a traversable navigable traversable , and a non-negative integer targetStep perform the following steps. They return a list of navigables Other navigables might not be impacted by the traversal. For example, if the response is a 204, the currently active document will remain. Additionally, going 'back' after a 204 will change the current session history entry , but the active session history entry will already be correct. Let results be an empty list Let navigablesToCheck be « traversable ». This list is extended in the loop below. For each navigable of navigablesToCheck Let targetEntry be the result of getting the target history entry given navigable and targetStep If targetEntry is navigable 's current session history entry and targetEntry 's document state 's reload pending is false, then: Append navigable to results Extend navigablesToCheck with navigable 's child navigables Adding child navigables to navigablesToCheck means those navigables will also be checked by this loop. child navigables are only checked if the navigable 's active document will not change as part of this traversal. Return results To get the target history entry given a navigable navigable , and a non-negative integer step , perform the following steps. They return a session history entry Let entries be the result of getting session history entries for navigable Return the item in entries that has the greatest step less than or equal to step To see why getting the target history entry returns the entry with the greatest step less than or equal to the input step, consider the following Jake diagram top /t /t#foo frames[0] /i-0-a /i-0-b For the input step 1, the target history entry for the top navigable is the /t entry, whose step is 0, while the target history entry for the frames[0] navigable is the /i-0-b entry, whose step is 1: top /t /t#foo frames[0] /i-0-a /i-0-b Similarly, given the input step 3 we get the top entry whose step is 3, and the frames[0] entry whose step is 1: top /t /t#foo frames[0] /i-0-a /i-0-b To get all navigables that might experience a cross-document traversal given a traversable navigable traversable , and a non-negative integer targetStep perform the following steps. They return a list of navigables From traversable 's session history traversal queue 's perspective, these documents are candidates for going cross-document during the traversal described by targetStep . They will not experience a cross-document traversal if the status code for their target document is HTTP 204 No Content. Note that if a given navigable might experience a cross-document traversal, this algorithm will return navigable but not its child navigables . Those would end up unloaded , not traversed. Let results be an empty list Let navigablesToCheck be « traversable ». This list is extended in the loop below. For each navigable of navigablesToCheck Let targetEntry be the result of getting the target history entry given navigable and targetStep If targetEntry 's document is not navigable 's document or targetEntry 's document state 's reload pending is true, then append navigable to results Although navigable 's active history entry can change synchronously, the new entry will always have the same Document , so accessing navigable 's document is reliable. Otherwise, extend navigablesToCheck with navigable 's child navigables Adding child navigables to navigablesToCheck means those navigables will also be checked by this loop. Child navigables are only checked if the navigable 's active document will not change as part of this traversal. Return results 7.4.6.2 Updating the document To update document for history step application given a Document document , a session history entry entry , a boolean doNotReactivate , integers scriptHistoryLength and scriptHistoryIndex NavigationType -or-null navigationType , an optional list of session history entries entriesForNavigationAPI , and an optional session history entry previousEntryForActivation Let documentIsNew be true if document 's latest entry is null; otherwise false. Let documentsEntryChanged be true if document 's latest entry is not entry ; otherwise false. Set document 's history object 's index to scriptHistoryIndex Set document 's history object 's length to scriptHistoryLength Let be history 's relevant global object 's navigation API If documentsEntryChanged is true, then: Let oldURL be document 's latest entry 's URL Set document 's latest entry to entry Restore the history object state given document and entry If documentIsNew is false, then: Assert navigationType is not null. Update the navigation API entries for a same-document navigation given entry , and navigationType Fire an event named popstate at document 's relevant global object , using PopStateEvent , with the state attribute initialized to document 's history object 's state and hasUAVisualTransition initialized to true if a visual transition, to display a cached rendered state of the latest entry , was done by the user agent. Restore persisted state given entry If oldURL 's fragment is not equal to entry 's URL 's fragment , then queue a global task on the DOM manipulation task source given document 's relevant global object to fire an event named hashchange at document 's relevant global object , using HashChangeEvent , with the oldURL attribute initialized to the serialization of oldURL and the newURL attribute initialized to the serialization of entry 's URL Otherwise: Assert entriesForNavigationAPI is given. Restore persisted state given entry Initialize the navigation API entries for a new document given entriesForNavigationAPI , and entry If all the following are true: previousEntryForActivation is given; navigationType is non-null; and navigationType is " reload " or previousEntryForActivation 's document is not document then: If 's activation is null, then set 's activation to a new NavigationActivation object in 's relevant realm Let previousEntryIndex be the result of getting the navigation API entry index of previousEntryForActivation within If previousEntryIndex is non-negative, then set activation 's old entry to 's entry list previousEntryIndex ]. Otherwise, if all the following are true: navigationType is " replace "; previousEntryForActivation 's document state 's origin is same origin with document 's origin ; and previousEntryForActivation 's document 's initial about:blank is false, then set activation 's old entry to a new NavigationHistoryEntry in 's relevant realm , whose session history entry is previousEntryForActivation Set activation 's new entry to 's current entry Set activation 's navigation type to navigationType If documentIsNew is true, then: Assert document 's during-loading navigation ID for WebDriver BiDi is not null. Invoke WebDriver BiDi navigation committed with navigable and a new WebDriver BiDi navigation status whose id is document 's during-loading navigation ID for WebDriver BiDi status is " committed ", and url is document 's URL Try to scroll to the fragment for document At this point scripts may run for the newly-created document document Otherwise, if documentsEntryChanged is false and doNotReactivate is false, then: Assert entriesForNavigationAPI is given. Reactivate document given entry and entriesForNavigationAPI documentsEntryChanged can be false for one of two reasons: either we are restoring from bfcache , or we are asynchronously finishing up a synchronous navigation which already synchronously set document 's latest entry . The doNotReactivate argument distinguishes between these two cases. To restore the history object state given Document document and session history entry entry Let targetRealm be document 's relevant realm Let state be StructuredDeserialize entry 's classic history API state targetRealm ). If this throws an exception, catch it and let state be null. Set document 's history object 's state to state To make active Document document Let window be document 's relevant global object Set document 's browsing context 's WindowProxy 's [[Window]] internal slot value to window Set window 's relevant settings object 's execution ready flag To reactivate Document document given a session history entry reactivatedEntry and a list of session history entries entriesForNavigationAPI This algorithm updates document after it has come out of bfcache , i.e., after it has been made fully active again. Other specifications that want to watch for this change to the fully active state are encouraged to add steps into this algorithm, so that the ordering of events that happen in effect of the change is clear. For each formControl of form controls in document with an autofill field name of " off ", invoke the reset algorithm for formControl If document 's suspended timer handles is not empty Assert document 's suspension time is not zero. Let suspendDuration be the current high resolution time minus document 's suspension time Let activeTimers be document 's relevant global object 's map of active timers For each handle in document 's suspended timer handles , if activeTimers handle exists , then increase activeTimers handle ] by suspendDuration Update the navigation API entries for reactivation given document 's relevant global object 's navigation API entriesForNavigationAPI , and reactivatedEntry If document 's current document readiness is " complete ", and document 's page showing is false: Set document 's page showing to true. Set document 's has been revealed to false. Update the visibility state of document to " visible ". Fire a page transition event named pageshow at document 's relevant global object with true. 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 navigation and traversal 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 document If document 's indicated part is still null, then try to scroll to the fragment for document To make document unsalvageable , given a Document document and a string reason Let details be a new not restored reason details whose reason is reason Append details to document 's bfcache blocking details Set document 's salvageable state to false. To build not restored reasons for document state given Document document Let notRestoredReasonsForDocument be a new not restored reasons Set notRestoredReasonsForDocument 's URL to document 's URL Let container be document 's node navigable 's container If container is an iframe element: Let src be the empty string. If container has a src attribute: Let src be the result of encoding-parsing-and-serializing a URL given container 's src attribute's value, relative to container 's node document If src is failure, then set src to container 's src attribute's value. Set notRestoredReasonsForDocument 's src to src Set notRestoredReasonsForDocument 's id to container 's id attribute's value, or the empty string if it has no such attribute. Set notRestoredReasonsForDocument 's name to container 's name attribute's value, or the empty string if it has no such attribute. Set notRestoredReasonsForDocument 's reasons to a clone of document 's bfcache blocking details For each navigable of document 's document-tree child navigables Let childDocument be navigable 's active document Build not restored reasons for document state given childDocument Append childDocument 's not restored reasons to notRestoredReasonsForDocument 's children Set document 's node navigable 's active session history entry 's document state 's not restored reasons to notRestoredReasonsForDocument To build not restored reasons for a top-level traversable and its descendants given top-level traversable topLevelTraversable Build not restored reasons for document state given topLevelTraversable 's active document Let crossOriginDescendants be an empty list For each childNavigable of topLevelTraversable 's active document 's descendant navigables If childNavigable 's active document 's origin is not same origin with topLevelTraversable 's active document 's origin , then append childNavigable to crossOriginDescendants Let crossOriginDescendantsPreventsBfcache be false. For each crossOriginNavigable of crossOriginDescendants Let reasonsForCrossOriginChild be crossOriginNavigable 's active document 's document state 's not restored reasons If reasonsForCrossOriginChild 's reasons is not empty, set crossOriginDescendantsPreventsBfcache to true. Set reasonsForCrossOriginChild 's URL to null. Set reasonsForCrossOriginChild 's reasons to null. Set reasonsForCrossOriginChild 's children to null. If crossOriginDescendantsPreventsBfcache is true, make document unsalvageable given topLevelTraversable 's active document and " masked ". 7.4.6.3 Revealing the document Document has a boolean has been revealed , initially false. It is used to ensure that the pagereveal event is fired once for each activation of the Document (once when it's rendered initially, and once for each reactivation ). To reveal Document document If document 's has been revealed is true, then return. Set document 's has been revealed to true. Let transition be the result of resolving inbound cross-document view-transition for document Fire an event named pagereveal at document 's relevant global object , using PageRevealEvent with its viewTransition set to transition If transition is not null, then: Prepare to run script given document 's relevant settings object Activate transition Clean up after running script given document 's relevant settings object Activating a view transition might resolve/reject promises, so by wrapping the activation with prepare/cleanup we ensure those promises are handled before the next rendering step. Though pagereveal is guaranteed to be fired during the first update the rendering step that displays an up-to-date version of the page, user agents are free to display a cached frame of the page before firing it. This prevents the presence of a pagereveal handler from delaying the presentation of such cached frame. 7.4.6.4 Scrolling to a fragment To scroll to the fragment given a Document document If document 's indicated part is null, then set document 's target element to null. Otherwise, if document 's indicated part is top of the document , then: Set document 's target element to null. Scroll to the beginning of the document for document [CSSOMVIEW] Return. Otherwise: Assert document 's indicated part is an element. Let target be document 's indicated part Set document 's target element to target Run the ancestor revealing algorithm on 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 Document 's indicated part is the one that its URL 's fragment identifies, or null if the fragment does not identify anything. 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 an HTML document document , its indicated part is the result of selecting the indicated part given document and document 's URL To select the indicated part given a Document document and a URL url If document 's URL does not equal url with exclude fragments set to true, then return null. Let fragment be url 's fragment If fragment is the empty string, then return the special value top of the document Let potentialIndicatedElement be the result of finding a potential indicated element given document and fragment If potentialIndicatedElement is not null, then return potentialIndicatedElement Let fragmentBytes be the result of percent-decoding fragment Let decodedFragment be the result of running UTF-8 decode without BOM on fragmentBytes Set potentialIndicatedElement to the result of finding a potential indicated element given document and decodedFragment If potentialIndicatedElement is not null, then return potentialIndicatedElement If decodedFragment is an ASCII case-insensitive match for the string top , then return the top of the document Return null. To find a potential indicated element given a Document document and a string fragment , run these steps: If there is an element in the document tree whose root is document and 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 whose root is document that has a name attribute whose value is equal to fragment , then return the first such element in tree order Return null. 7.4.6.5 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 ", and entry 's document 's relevant global object 's navigation API 's suppress normal scroll restoration during ongoing navigation is false, then restore scroll position data given entry 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. If suppress normal scroll restoration during ongoing navigation is true, then restoring scroll position data might still happen at a later point, as part of finishing the relevant NavigateEvent , or via a navigateEvent.scroll() method call. 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 the Text Telephone URL , or Email state, if the persisted state includes the directionality of user input in such controls. Restoring the value of form controls as part of this process does not fire any input or change events, but can trigger the formStateRestoreCallback of form-associated custom elements Each Document has a boolean has been scrolled by the user , initially false. If the user scrolls the document, the user agent must set that document's has been scrolled by the user to true. The restorable scrollable regions of a Document document are document 's viewport , and all of document 's scrollable regions excepting any navigable containers Child navigable scroll restoration is handled as part of state restoration for the session history entry for those navigables Document s. To restore scroll position data given a session history entry entry Let document be entry 's document If document 's has been scrolled by the user is true, then the user agent should return. The user agent should attempt to use entry 's scroll position data to restore the scroll positions of entry 's document 's restorable scrollable regions . The user agent may continue to attempt to do so periodically, until document 's has been scrolled by the user becomes true. This is formulated as an attempt , which is potentially repeated until success or until the user scrolls, due to the fact that relevant content indicated by the scroll position data might take some time to load from the network. Scroll restoration might be affected by scroll anchoring. [CSSSCROLLANCHORING] 7.5 Document lifecycle 7.5.1 Shared document creation infrastructure When loading a document using one of the below algorithms, we use the following steps to create and initialize a Document object given a type type content type contentType , and navigation params navigationParams Document objects are also created when creating a new browsing context and document ; such initial about:blank Document are never created by this algorithm. Also, browsing context -less Document objects can be created via various APIs, such as document.implementation.createHTMLDocument() Let browsingContext be the result of obtaining a browsing context to use for a navigation response given navigationParams This can result in a browsing context group switch , in which case browsingContext will be a newly-created browsing context instead of being navigationParams 's navigable 's active browsing context . In such a case, the created Window Document , and agent will not end up being used; because the created Document 's origin is opaque , we will end up creating a new agent and Window later in this algorithm to go along with the new Document Let permissionsPolicy be the result of creating a permissions policy from a response given navigationParams 's navigable 's container 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 navigationParams 's navigable '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 Let window be null. If browsingContext 's active document 's is initial about:blank is true, and browsingContext 's active document 's origin is same origin-domain with navigationParams 's origin , then set window to browsingContext 's active window 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 navigationParams 's 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 realmExecutionContext be the result of creating a new 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. Set window to the global object of realmExecutionContext 's Realm component. Let topLevelCreationURL be creationURL Let topLevelOrigin be navigationParams 's origin If navigable 's container is not null, then: Let parentEnvironment be navigable '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 realmExecutionContext 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 loadTimingInfo be a new document load timing info with its navigation start time set to navigationParams 's response 's timing info 's start time Let document be a new Document , with type type content type contentType origin navigationParams 's origin browsing context browsingContext policy container navigationParams 's policy container permissions policy permissionsPolicy active sandboxing flag set navigationParams 's final sandboxing flag set opener policy navigationParams 's cross-origin opener policy load timing info loadTimingInfo was created via cross-origin redirects navigationParams 's response 's has cross-origin redirects during-loading navigation ID for WebDriver BiDi navigationParams 's id URL creationURL current document readiness loading about base URL navigationParams 's about base URL allow declarative shadow roots true custom element registry a new CustomElementRegistry object Set window 's associated Document to document Set document 's internal ancestor origin objects list to the result of running the internal ancestor origin objects list creation steps given document and navigationParams 's iframe element referrer policy Set document 's ancestor origins list to the result of running the ancestor origins list creation steps given document 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. If navigationParams 's fetch controller is not null, then: Let fullTimingInfo be the result of extracting the full timing info from navigationParams 's fetch controller Let redirectCount be 0 if navigationParams 's response 's has cross-origin redirects is true; otherwise navigationParams 's request 's redirect count Create the navigation timing entry for document , given fullTimingInfo redirectCount navigationTimingType navigationParams 's response 's service worker timing info and navigationParams 's response 's body info Create the navigation timing entry for document , with navigationParams 's response 's timing info redirectCount navigationParams 's navigation timing type , and navigationParams 's response 's service worker timing info 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 If navigationParams 's commit early hints is not null, then call navigationParams 's commit early hints with document Process link headers given document navigationParams 's response , and pre-media ". If navigationParams 's navigable is a top-level traversable , then process the ` Speculation-Rules header given document and navigationParams 's response This is conditional because speculative loads are only considered for top-level traversables , so it would be wasteful to fetch these rules otherwise. Potentially free deferred fetch quota for document 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 To populate with html head body given a Document document Let html be the result of creating an element given document , " html ", and the HTML namespace Let head be the result of creating an element given document , " head ", and the HTML namespace Let body be the result of creating an element given document , " body ", and the HTML namespace Append html to document Append head to html Append body to html 7.5.2 Loading HTML documents To load an HTML document , given params navigationParams Let document be the result of creating and initializing a Document object given " html ", " text/html ", and navigationParams If document 's URL is about:blank , then populate with html head body given document This special case, where even non- initial about:blank Document s are synchronously given their element nodes, is necessary for compatible with deployed content. In other words, it is not compatible to instead go down the "otherwise" branch and feed the empty byte sequence into an HTML parser to asynchronously populate document Otherwise, 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 first task that the networking task source places on the task queue while fetching runs must process link headers given document navigationParams 's response , and " media ", after the task has been processed by the HTML parser Before any script execution occurs, the user agent must wait for scripts may run for the newly-created document to be true for document 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 document 's relevant global object to have the parser process the implied EOF character, which eventually causes load event to be fired. Return document 7.5.3 Loading XML documents 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 document , given " xml ", type , and navigationParams , and return that Document . 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 first task that the networking task source places on the task queue while fetching runs must process link headers given document navigationParams 's response , and " media ", after the task has been processed by the XML parser 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. Before any script execution occurs, the user agent must wait for scripts may run for the newly-created document to be true for the newly-created Document Once parsing is complete, the user agent must set document 's during-loading navigation ID for WebDriver BiDi to null. For HTML documents this is reset when parsing is complete, after firing the load event. Error messages from the parse process (e.g., XML namespace well-formedness errors) may be reported inline by mutating the Document 7.5.4 Loading text documents To load a text document , given a params navigationParams and a string type Let document be the result of creating and initializing a Document object given " html ", type , and navigationParams Set document 's parser cannot change the mode flag to true. Set document 's mode to " no-quirks ". 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. document 's encoding must be set to the character encoding used to decode the document during parsing. The first task that the networking task source places on the task queue while fetching runs must process link headers given document navigationParams 's response , and " media ", after the task has been processed by the HTML parser Before any script execution occurs, the user agent must wait for scripts may run for the newly-created document to be true for document When no more bytes are available, the user agent must queue a global task on the networking task source given document 's relevant global object to have the parser process the implied EOF character, which eventually causes load event to be fired. User agents may add content to the head element of 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. Return document 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 ). 7.5.5 Loading multipart/x-mixed-replace documents To load a multipart/x-mixed-replace document , given navigation params navigationParams source snapshot params sourceSnapshotParams and origin initiatorOrigin Parse navigationParams 's response 's body using the rules for multipart types. [RFC2046] Let firstPartNavigationParams be a copy of navigationParams Set firstPartNavigationParams 's response to a new response representing the first part of navigationParams 's response 's body 's multipart stream. Let document be the result of loading a document given firstPartNavigationParams sourceSnapshotParams , and initiatorOrigin For each additional body part obtained from navigationParams 's response , the user agent must navigate document 's node navigable to navigationParams 's request 's URL , using document , with response set to navigationParams 's response and historyHandling set to " replace ". Return document 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.5.6 Loading media documents To load a media document , given navigationParams and a string type Let document be the result of creating and initializing a Document object given " html ", type , and navigationParams Set document 's mode to " no-quirks ". Populate with html head body given document 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. User agents may add content to the head element of document , or attributes to 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 Process link headers given document navigationParams 's response , and media ". Act as if the user agent had stopped parsing document Return document 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 Before any script execution occurs, the user agent must wait for scripts may run for the newly-created document to be true for the Document 7.5.7 Loading a document for inline content that doesn't have a DOM When the user agent is to create a document to display a user agent page or PDF viewer inline provided a navigable navigable , a navigation ID navigationId , a NavigationTimingType navTimingType , and a user navigation involvement userInvolvement , the user agent should: Let origin be a new opaque origin Let coop be a new opener policy Let coopEnforcementResult be a new opener policy enforcement result with url response 's URL origin origin opener policy coop Let navigationParams be a new navigation params with id navigationId navigable navigable request null response a new response origin origin fetch controller null commit early hints null COOP enforcement result coopEnforcementResult reserved environment null policy container a new policy container final sandboxing flag set an empty set iframe element referrer policy the empty string opener policy coop navigation timing type navTimingType about base URL null user involvement userInvolvement 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. Act as if the user agent had stopped parsing document This is done to avoid leaking information to the parent page about whether a navigation has been blocked by CSP, or if the response was a network error . In the case where the container is an iframe element, stopping parsing causes the iframe load event steps to run. Return document Because we ensure the resulting Document 's origin is opaque , and the resulting Document cannot run script with access to the DOM, the existence and properties of this Document are not observable to web developer code. This means that most of the above values, e.g., the text/html type , do not matter. Similarly, most of the items in navigationParams don't have any observable effect, besides preventing the Document -creation algorithm from getting confused, and so are set to default values. 7.5.8 Finishing the loading process 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 node navigable 's container This will be null in the case where document is the initial about:blank Document in a frame or iframe , since at the point of browsing context creation which calls this algorithm, the container relationship has not yet been established. (That happens in a subsequent step of create a new child navigable .) The consequence of this is that the following steps do nothing, i.e., we do not fire an asynchronous load event on the container element for such cases. Instead, a synchronous load event is fired in a special initial-insertion case when processing the iframe attributes 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.5.9 Unloading documents Document has a salvageable state, which must initially be true, and a page showing boolean, which is initially false. The page showing boolean 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). Document has a DOMHighResTimeStamp suspension time initially 0. Document has a list of suspended timer handles initially empty. 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 unload Document oldDocument , given an optional Document newDocument Assert : this is running as part of a task queued on oldDocument 's relevant agent 's event loop Let unloadTimingInfo be a new document unload timing info If newDocument is not given, then set unloadTimingInfo to null. In this case there is no new document that needs to know about how long it took oldDocument to unload. Otherwise, if newDocument 's event loop is not oldDocument 's event loop , then the user agent may be unloading oldDocument in parallel . In that case, the user agent should set unloadTimingInfo to null. In this case newDocument 's loading is not impacted by how long it takes to unload oldDocument , so it would be meaningless to communicate that timing info. Let intendToKeepInBfcache be true if the user agent intends to keep oldDocument alive in a session history entry , such that it can later be used for history traversal This must be false if oldDocument is not salvageable , or if there are any descendants of oldDocument which the user agent does not intend to keep alive in the same way (including due to their lack of salvageability ). Let eventLoop be oldDocument 's relevant agent 's event loop Increase eventLoop 's termination nesting level by 1. Increase oldDocument 's unload counter by 1. If intendToKeepInBfcache is false, then set oldDocument 's salvageable state to false. If oldDocument 's page showing is true: Set oldDocument 's page showing to false. Fire a page transition event named pagehide at oldDocument 's relevant global object with oldDocument 's salvageable state. Update the visibility state of oldDocument to hidden ". If unloadTimingInfo is not null, then set unloadTimingInfo 's unload event start time to the current high resolution time given newDocument 's relevant global object coarsened given oldDocument 's relevant settings object 's cross-origin isolated capability If oldDocument 's salvageable state is false, then fire an event named unload at oldDocument '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 newDocument 's relevant global object coarsened given oldDocument 's relevant settings object 's cross-origin isolated capability Decrease eventLoop 's termination nesting level by 1. Set oldDocument 's suspension time to the current high resolution time given document 's relevant global object Set oldDocument 's suspended timer handles to the result of getting the keys for the map of active timers Set oldDocument 's has been scrolled by the user to false. Run any unloading document cleanup steps for oldDocument that are defined by this specification and other applicable specifications If oldDocument 's node navigable is a top-level traversable build not restored reasons for a top-level traversable and its descendants given oldDocument 's node navigable If oldDocument 's salvageable state is false, then destroy oldDocument Decrease oldDocument 's unload counter by 1. If newDocument is given, newDocument 's was created via cross-origin redirects is false, and newDocument 's origin is the same as oldDocument 's origin , then set newDocument 's previous document unload timing to unloadTimingInfo To unload a document and its descendants , given a Document document , an optional Document -or-null newDocument (default null), an optional set of steps afterAllUnloads , and an optional set of steps firePageSwapSteps Assert : this is running within document 's node navigable 's traversable navigable 's session history traversal queue Let childNavigables be document 's child navigables Let numberUnloaded be 0. For each childNavigable of childNavigables in what order? queue a global task on the navigation and traversal task source given childNavigable 's active window to perform the following steps: Let incrementUnloaded be an algorithm step which increments numberUnloaded Unload a document and its descendants given childNavigable 's active document , null, and incrementUnloaded Wait until numberUnloaded equals childNavigable 's size Queue a global task on the navigation and traversal task source given document 's relevant global object to perform the following steps: If firePageSwapSteps is given, then run firePageSwapSteps Unload document , passing along newDocument if it is not null. If afterAllUnloads was given, then run it. 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 make document unsalvageable given document and " websocket ". For each WebTransport object transport whose relevant global object is window , run the context cleanup steps given transport If document 's salvageable state is false, then: For each EventSource object eventSource whose relevant global object is equal to window forcibly close eventSource Clear window 's map of active timers It would be better if specification authors sent a pull request to add calls from here into their specifications directly, instead of using the unloading document cleanup steps hook, to ensure well-defined cross-specification call order. As of the time of this writing the following specifications are known to have unloading document cleanup steps , which will be run in an unspecified order: Fullscreen API Web NFC WebDriver BiDi Compute Pressure File API Media Capture and Streams Picture-in-Picture Screen Orientation Service Workers WebLocks API WebAudio API WebRTC [FULLSCREEN] [WEBNFC] [WEBDRIVERBIDI] [COMPUTEPRESSURE] [FILEAPI] [MEDIASTREAM] [PICTUREINPICTURE] [SCREENORIENTATION] [SW] [WEBLOCKS] [WEBAUDIO] [WEBRTC] Issue #8906 tracks the work to make the order of these steps clear. 7.5.10 Destroying documents To destroy Document document Assert : this is running as part of a task queued on document 's relevant agent 's event loop Abort document Set document 's salvageable state to false. Let ports be the list of MessagePort s whose relevant global object 's associated Document is document For each port in ports disentangle port Run any unloading document cleanup steps for document that are defined by this specification and other applicable specifications Remove any tasks whose document is document from any task queue (without running those tasks). Set document 's browsing context to null. Set document 's node navigable 's active session history entry 's document state 's document 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 Even after destruction, the Document object itself might still be accessible to script, in the case where we are destroying a child navigable To destroy a document and its descendants given a Document document and an optional set of steps afterAllDestruction , perform the following steps in parallel If document is not fully active , then: Let reason be a string from user-agent specific blocking reasons . If none apply, then let reason be " masked ". Make document unsalvageable given document and reason If document 's node navigable is a top-level traversable build not restored reasons for a top-level traversable and its descendants given document 's node navigable Let childNavigables be document 's child navigables Let numberDestroyed be 0. For each childNavigable of childNavigables in what order? queue a global task on the navigation and traversal task source given childNavigable 's active window to perform the following steps: Let incrementDestroyed be an algorithm step which increments numberDestroyed Destroy a document and its descendants given childNavigable 's active document and incrementDestroyed Wait until numberDestroyed equals childNavigable 's size Queue a global task on the navigation and traversal task source given document 's relevant global object to perform the following steps: Destroy document If afterAllDestruction was given, then run it. 7.5.11 Aborting a document load To abort Document document Assert : this is running as part of a task queued on document 's relevant agent 's event loop 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 make document unsalvageable given document and fetch ". If document 's during-loading navigation ID for WebDriver BiDi is non-null, then: Invoke WebDriver BiDi navigation aborted with document 's node navigable and a new WebDriver BiDi navigation status whose id is document 's during-loading navigation ID for WebDriver BiDi status is " canceled ", and url is document 's URL Set document 's during-loading navigation ID for WebDriver BiDi to null. If document has an active parser , then: Set document 's active parser was aborted to true. Abort that parser Make document unsalvageable given document and parser-aborted ". To abort a document and its descendants given a Document document Assert : this is running as part of a task queued on document 's relevant agent 's event loop Let descendantNavigables be document 's descendant navigables For each descendantNavigable of descendantNavigables in what order? queue a global task on the navigation and traversal task source given descendantNavigable 's active window to perform the following steps: Abort descendantNavigable 's active document If descendantNavigable 's active document 's salvageable is false, then set document 's salvageable to false. Abort document To stop loading navigable navigable Let document be navigable 's active document If document 's unload counter is 0, and navigable 's ongoing navigation is a navigation ID , then set the ongoing for navigable to null. This will have the effect of aborting any ongoing navigations of navigable , since at certain points during navigation, changes to the ongoing will cause further work to be abandoned. Abort a document and its descendants given document Through their user interface , user agents also allow stopping traversals, i.e. cases where the ongoing navigation is " traversal ". The above algorithm does not account for this. (On the other hand, user agents do not allow window.stop() to stop traversals, so the above algorithm is correct for that caller.) See issue #6905 7.6 Speculative loading Speculative loading is the practice of performing navigation actions, such as prefetching, ahead of navigation starting. This makes subsequent navigations faster. Developers can initiate speculative loads by using speculation rules . User agents might also perform speculative loads in certain implementation-defined scenarios, such as typing into the address bar. 7.6.1 Speculation rules Speculation rules are how developers instruct the browser about speculative loading operations that the developer believes will be beneficial. They are delivered as JSON documents, via either: inline script elements with their type attribute set to " speculationrules "; or resources fetched from a URL specified in the ` Speculation-Rules ` HTTP response header. The following JSON document is parsed into a speculation rule set specifying a number of desired conditions for the user agent to start a referrer-initiated navigational prefetch "prefetch" "urls" "/chapters/5" }, "eagerness" "moderate" "where" "and" "href_matches" "/*" }, "not" "selector_matches" ".no-prefetch" A JSON document representing a speculation rule set must meet the following speculation rule set authoring requirements It must be valid JSON. [JSON] The JSON must represent a JSON object, with at most three keys " tag ", prefetch " and " prerender ". In this standard, " prerender " is optionally converted to prefetch at parse time . Some implementations might implement different behavior for prerender, as specified in Prerendering Revamped [PRERENDERING-REVAMPED] The value corresponding to the " tag " key, if present, must be a speculation rule tag The values corresponding to the " prefetch " and " prerender " keys, if present, must be arrays of valid speculation rules valid speculation rule is a JSON object that meets the following requirements: It must have at most the following keys: " source ", " urls ", " where ", " relative_to ", eagerness ", " referrer_policy ", " tag ", " requires ", " expects_no_vary_search ", or " target_hint ". In this standard, target_hint " is ignored The value corresponding to the " source " key, if present, must be either " list " or " document ". If the value corresponding to the " source " key is " list ", then the " urls " key must be present, and the where " key must be absent. If the value corresponding to the " source " key is " document ", then the " urls " key must be absent. The " urls " and " where " keys must not both be present. If the value corresponding to the " source " key is " document " or the " where " key is present, then the " relative_to " key must be absent. The value corresponding to the " urls " key, if present, must be an array of valid URL strings The value corresponding to the " where " key, if present, must be a valid document rule predicate The value corresponding to the " relative_to " key, if present, must be either " ruleset " or " document ". The value corresponding to the " eagerness " key, if present, must be speculation rule eagerness The value corresponding to the " referrer_policy " key, if present, must be a referrer policy The value corresponding to the " tag " key, if present, must be a speculation rule tag The value corresponding to the " requires " key, if present, must be an array of speculation rule requirements The value corresponding to the " expects_no_vary_search " key, if present, must be a string that is parseable as a ` No-Vary-Search ` header value. valid document rule predicate is a JSON object that meets the following requirements: It must contain exactly one of the keys " and ", " or ", " not ", " href_matches ", or selector_matches ". It must not contain any keys apart from the above or " relative_to ". If it contains the key " relative_to ", then it must also contain the key " href_matches ". The value corresponding to the " relative_to " key, if present, must be either " ruleset " or " document ". The value corresponding to the " and " or " or keys, if present, must be arrays of valid document rule predicates The value corresponding to the " not " key, if present, must be a valid document rule predicate The value corresponding to the " href_matches " key, if present, must be either a valid URL pattern input or an array of valid URL pattern inputs The value corresponding to the " selector_matches " key, if present, must be either a string matching or an array of strings that match valid URL pattern input is either: scalar value string that can be successfully parsed as a URL pattern constructor string, or; a JSON object whose keys are drawn from the members of the URLPatternInit dictionary and whose values are scalar value strings 7.6.1.1 Data model speculation rule set is a struct with the following items prefetch rules , a list of speculation rules , initially empty In the future, other rules will be possible, e.g., prerender rules. See Prerendering Revamped for such not-yet-accepted extensions. [PRERENDERING-REVAMPED] speculation rule is a struct with the following items URLs , an ordered set of URLs predicate , a document rule predicate or null eagerness , a speculation rule eagerness referrer policy , a referrer policy tags , an ordered set of speculation rule tags requirements , an ordered set of speculation rule requirements No-Vary-Search hint , a URL search variance document rule predicate is one of the following: document rule conjunction document rule disjunction document rule negation document rule URL pattern predicate ; or document rule selector predicate document rule conjunction is a struct with the following items clauses , a list of document rule predicates document rule disjunction is a struct with the following items clauses , a list of document rule predicates document rule negation is a struct with the following items clause , a document rule predicate document rule URL pattern predicate is a struct with the following items patterns , a list of URL patterns document rule selector predicate is a struct with the following items selectors , a list of selectors speculation rule eagerness is one of the following strings immediate The developer believes that performing the associated speculative loads is very likely to be worthwhile, and they might also expect that load to require significant lead time to complete. User agents should usually enact the speculative load candidate as soon as practical, subject only to considerations such as user preferences, device conditions, and resource limits. eager User agents should enact the speculative load candidate on even a slight suggestion that the user may navigate to this URL in the future. For instance, the user might have moved the cursor toward a link or hovered it, even momentarily, or paused scrolling when the link is one of the more prominent ones in the viewport. The author is seeking to capture as many navigations as possible, as early as possible. moderate User agents should enact the candidate if user behavior suggests the user may navigate to this URL in the near future. For instance, the user might have scrolled a link into the viewport and shown signs of being likely to click it, e.g., by moving the cursor over it for some time. The developer is seeking a balance between " eager " and conservative ". conservative User agents should enact the candidate only when the user is very likely to navigate to this URL at any moment. For instance, the user might have begun to interact with a link. The developer is seeking to capture some of the benefits of speculative loading with a fairly small tradeoff of resources. speculation rule eagerness is less eager than another speculation rule eagerness if follows in the above list. speculation rule eagerness is at least as eager as another speculation rule eagerness if is not less eager than speculation rule tag is either an ASCII string whose code points are all in the range U+0020 to U+007E inclusive, or null. This code point range restriction ensures the value can be sent in an HTTP header with no escaping or modification. speculation rule requirement is the string " anonymous-client-ip-when-cross-origin ". In the future, more possible requirements might be defined. 7.6.1.2 Parsing Since speculative loading is a progressive enhancement, this standard is fairly conservative in its parsing behavior. In particular, unknown keys or invalid values usually cause parsing failure, since it is safer to do nothing than to possibly misinterpret a speculation rule. That said, parsing failure for a single speculation rule still allows other speculation rules to be processed. It is only in the case of top-level misconfiguration that the entire speculation rule set is discarded. To parse a speculation rule set string given a string input Document document , and a URL baseURL Let parsed be the result of parsing a JSON string to an Infra value given input If parsed is not a map , then throw a TypeError indicating that the top-level value needs to be a JSON object. Let result be a new speculation rule set Let tag be null. If parsed [" tag "] exists If parsed [" tag "] is not a speculation rule tag , then throw a TypeError indicating that the speculation rule tag is invalid. Set tag to parsed [" tag "]. Let typesToTreatAsPrefetch be « " prefetch " ». The user agent may append prerender " to typesToTreatAsPrefetch Since this specification only includes prefetching, this allows user agents to treat requests for prerendering as requests for prefetching. User agents which implement prerendering, per the Prerendering Revamped specification, will instead interpret these as prerender requests. [PRERENDERING-REVAMPED] For each type of typesToTreatAsPrefetch If parsed type exists If parsed type ] is a list , then for each rule of parsed type ]: Let rule be the result of parsing a speculation rule given rule tag document , and baseURL If rule is null, then continue Append rule to result 's prefetch rules Otherwise, the user agent may report a warning to the console indicating that the rules list for type needs to be a JSON array. Return result To parse a speculation rule given a map input , a speculation rule tag rulesetLevelTag , a Document document , and a URL baseURL If input is not a map The user agent may report a warning to the console indicating that the rule needs to be a JSON object. Return null. If input has any key other than " source ", " urls ", " where ", " relative_to ", " eagerness ", " referrer_policy ", " tag ", " requires ", " expects_no_vary_search ", or " target_hint ": The user agent may report a warning to the console indicating that the rule has unrecognized keys. Return null. target_hint " has no impact on the processing model in this standard. However, implementations of Prerendering Revamped can use it for prerendering rules, and so requiring user agents to fail parsing such rules would be counterproductive. [PRERENDERING-REVAMPED] Let source be null. If input [" source "] exists , then set source to input [" source "]. Otherwise, if input [" urls "] exists and input [" where "] does not exist , then set source to " list ". Otherwise, if input [" where "] exists and input [" urls "] does not exist , then set source to " document ". If source is neither " list " nor " document ": The user agent may report a warning to the console indicating that a source could not be inferred or an invalid source was specified. Return null. Let urls be an empty list Let predicate be null. If source is " list ": If input [" where "] exists The user agent may report a warning to the console indicating that there were conflicting sources for this rule. Return null. If input [" relative_to "] exists If input [" relative_to "] is neither " ruleset " nor " document ": The user agent may report a warning to the console indicating that the supplied relative-to value was invalid. Return null. If input [" relative_to "] is " document ", then set baseURL to document 's document base URL If input [" urls "] does not exist or is not a list The user agent may report a warning to the console indicating that the supplied URL list was invalid. Return null. For each urlString of input [" urls "]: If urlString is not a string: The user agent may report a warning to the console indicating that the supplied URL must be a string. Return null. Let parsedURL be the result of URL parsing urlString with baseURL If parsedURL is failure, or parsedURL 's scheme is not an HTTP(S) scheme The user agent may report a warning to the console indicating that the supplied URL string was unparseable. Continue Append parsedURL to urls If source is " document ": If input [" urls "] or input [" relative_to "] exists The user agent may report a warning to the console indicating that there were conflicting sources for this rule. Return null. If input [" where "] does not exist , then set predicate to a document rule conjunction whose clauses is an empty list Such a predicate will match all links. Otherwise, set predicate to the result of parsing a document rule predicate given input [" where "], document , and baseURL If predicate is null, then return null. Let eagerness be " immediate " if source is " list "; otherwise, " conservative ". If input [" eagerness "] exists If input [" eagerness "] is not a speculation rule eagerness The user agent may report a warning to the console indicating that the eagerness was invalid. Return null. Set eagerness to input [" eagerness "]. Let referrerPolicy be the empty string. If input [" referrer_policy "] exists If input [" referrer_policy "] is not a referrer policy The user agent may report a warning to the console indicating that the referrer policy was invalid. Return null. Set referrerPolicy to input [" referrer_policy "]. Let tags be an empty ordered set If rulesetLevelTag is not null, then append rulesetLevelTag to tags If input [" tag "] exists If input [" tag "] is not a speculation rule tag The user agent may report a warning to the console indicating that the tag was invalid. Return null. Append input [" tag "] to tags If tags is empty , then append null to tags Assert tags 's size is either 1 or 2. Let requirements be an empty ordered set If input [" requires "] exists If input [" requires "] is not a list The user agent may report a warning to the console indicating that the requirements were not understood. Return null. For each requirement of input [" requires "]: If requirement is not a speculation rule requirement The user agent may report a warning to the console indicating that the requirement was not understood. Return null. Append requirement to requirements Let noVarySearchHint be the default URL search variance If input [" expects_no_vary_search "] exists If input [" expects_no_vary_search "] is not a string The user agent may report a warning to the console indicating that the No-Vary-Search ` hint was invalid. Return null. Set noVarySearchHint to the result of parsing a URL search variance given input [" expects_no_vary_search "]. Return a speculation rule with: URLs urls predicate predicate eagerness eagerness referrer policy referrerPolicy tags tags requirements requirements No-Vary-Search hint noVarySearchHint To parse a document rule predicate given a value input , a Document document , and a URL baseURL If input is not a map The user agent may report a warning to the console indicating that the document rule predicate was invalid. Return null. If input does not contain exactly one of " and ", " or ", " not ", " href_matches ", or " selector_matches ": The user agent may report a warning to the console indicating that the document rule predicate was empty or ambiguous. Return null. Let predicateType be the single key found in the previous step. If predicateType is " and " or " or ": If input has any key other than predicateType The user agent may report a warning to the console indicating that the document rule predicate had unexpected extra options. Return null. If input predicateType ] is not a list The user agent may report a warning to the console indicating that the document rule predicate had an invalid clause list. Return null. Let clauses be an empty list For each rawClause of input predicateType ]: Let clause be the result of parsing a document rule predicate given rawClause document , and baseURL If clause is null, then return null. Append clause to clauses If predicateType is " and ", then return a document rule conjunction whose clauses is clauses Return a document rule disjunction whose clauses is clauses If predicateType is " not ": If input has any key other than " not ": The user agent may report a warning to the console indicating that the document rule predicate had unexpected extra options. Return null. Let clause be the result of parsing a document rule predicate given input predicateType ], document , and baseURL If clause is null, then return null. Return a document rule negation whose clause is clause If predicateType is " href_matches ": If input has any key other than " href_matches " or " relative_to ": The user agent may report a warning to the console indicating that the document rule predicate had unexpected extra options. Return null. If input [" relative_to "] exists If input [" relative_to "] is neither " ruleset " nor " document ": The user agent may report a warning to the console indicating that the supplied relative-to value was invalid. Return null. If input [" relative_to "] is " document ", then set baseURL to document 's document base URL Let rawPatterns be input [" href_matches "]. If rawPatterns is not a list , then set rawPatterns to rawPatterns ». Let patterns be an empty list For each rawPattern of rawPatterns Let pattern be the result of building a URL pattern from an Infra value given rawPattern and baseURL . If this step throws an exception, catch the exception and set pattern to null. If pattern is null: The user agent may report a warning to the console indicating that the supplied URL pattern was invalid. Return null. Append pattern to patterns Return a document rule URL pattern predicate whose patterns is patterns If predicateType is " selector_matches ": If input has any key other than " selector_matches ": The user agent may report a warning to the console indicating that the document rule predicate had unexpected extra options. Return null. Let rawSelectors be input [" selector_matches "]. If rawSelectors is not a list , then set rawSelectors to « rawSelectors ». Let selectors be an empty list For each rawSelector of rawSelectors Let parsedSelectorList be failure. If rawSelector is a string, then set parsedSelectorList to the result of parsing a selector given rawSelector If parsedSelectorList is failure: The user agent may report a warning to the console indicating that the supplied selector list was invalid. Return null. For each selector of parsedSelectorList append selector to selectors Return a document rule selector predicate whose selectors is selectors Assert : this step is never reached, as one of the previous branches was taken. 7.6.1.3 Processing model speculative load candidate is a struct with the following items URL , a URL No-Vary-Search hint , a URL search variance eagerness , a speculation rule eagerness referrer policy , a referrer policy tags , an ordered set of speculation rule tags prefetch candidate is a speculative load candidate with the following additional item anonymization policy , a prefetch IP anonymization policy prefetch IP anonymization policy is either null or a cross-origin prefetch IP anonymization policy cross-origin prefetch IP anonymization policy is a struct whose single item is its origin , an origin speculative load candidate candidateA is redundant with another speculative load candidate candidateB if the following steps return true: If candidateA 's No-Vary-Search hint is not equal to candidateB 's No-Vary-Search hint , then return false. If candidateA 's URL is not equivalent modulo search variance to candidateB 's URL given candidateA 's No-Vary-Search hint , then return false. Return true. The requirement that the No-Vary-Search hints be equivalent is somewhat strict. It means that some cases which could theoretically be treated as matching, are not treated as such. Thus, redundant speculative loads could happen. However, allowing more lenient matching makes the check no longer an equivalence relation, and producing such matches would require an implementation strategy that does a full comparison, instead of a simpler one using normalized URL keys. This is in line with the best practices for server operators, and attendant HTTP cache implementation notes, in No Vary Search § 6 Comparing In practice, we do not expect this to cause redundant speculative loads, since server operators and the corresponding speculation rules-writing web developers will follow best practices and use static ` No-Vary-Search ` header values/speculation rule hints. Consider three speculative load candidates has a URL of and a No-Vary-Search hint parsed from params=("a") has a URL of and a No-Vary-Search hint parsed from params=("b") has a URL of and a No-Vary-Search hint parsed from params=("a") With the current definition of redundant with , none of these candidates are redundant with each other. A speculation rule set which contained all three could cause three separate speculative loads. A definition which did not require equivalent No-Vary-Search hints could consider and to match (using 's No-Vary-Search hint ), and and to match (using 's No-Vary-Search hint ). But it could not consider and to match, so it would not be transitive, and thus not an equivalence relation. Every Document has speculation rule sets , a list of speculation rule sets , initially empty. Every Document has a consider speculative loads microtask queued , a boolean, initially false. To consider speculative loads for a Document document If document 's node navigable is not a top-level traversable , then return. Supporting speculative loads into child navigables has some complexities and is not currently defined. It might be possible to define it in the future. If document 's consider speculative loads microtask queued is true, then return. Set document 's consider speculative loads microtask queued to true. Queue a microtask given document to run the following steps: Set document 's consider speculative loads microtask queued to false. Run the inner consider speculative loads steps for document In addition to the call sites explicitly given in this standard: When style recalculation would cause selector matching results to change, the user agent must consider speculative loads for the relevant Document When the user indicates interest in hyperlinks , in one of the implementation-defined ways that the user agent uses to implement the speculation rule eagerness heuristics, the user agent may consider speculative loads for the hyperlink's node document For example, a user agent which implements " conservative " eagerness by watching for pointerdown events would want to consider speculative loads as part of reacting to such events. In this standard, every call to consider speculative loads is given just a Document , and the algorithm re-computes all possible candidates in a stateless way. A real implementation would likely cache previous computations, and pass along information from the call site to make updates more efficient. For example, if an element's href attribute is changed, that specific element could be passed along in order to update only the related speculative load candidate Note that because of how consider speculative loads queues a microtask, by the time the inner consider speculative loads steps are run, multiple updates (or cancelations ) might be processed together. The inner consider speculative loads steps for a Document document are: If document is not fully active , then return. Let prefetchCandidates be an empty list For each ruleSet of document 's speculation rule sets For each rule of ruleSet 's prefetch rules Let anonymizationPolicy be null. If rule 's requirements contains anonymous-client-ip-when-cross-origin ", then set anonymizationPolicy to a cross-origin prefetch IP anonymization policy whose origin is document 's origin For each url of rule 's URLs Let referrerPolicy be the result of computing a speculative load referrer policy given rule and null. Append a new prefetch candidate with URL url No-Vary-Search hint rule 's No-Vary-Search hint eagerness rule 's eagerness referrer policy referrerPolicy tags rule 's tags anonymization policy anonymizationPolicy to prefetchCandidates If rule 's predicate is not null: Let links be the result of finding matching links given document and rule 's predicate For each link of links Let referrerPolicy be the result of computing a speculative load referrer policy given rule and link Append a new prefetch candidate with URL link 's url No-Vary-Search hint rule 's No-Vary-Search hint eagerness rule 's eagerness referrer policy referrerPolicy tags rule 's tags anonymization policy anonymizationPolicy to prefetchCandidates For each prefetchRecord of document 's prefetch records If prefetchRecord 's source is not " speculation rules ", then continue Assert prefetchRecord 's state is not " canceled ". If prefetchRecord is not still being speculated given prefetchCandidates , then cancel and discard prefetchRecord given document Let prefetchCandidateGroups be an empty list For each candidate of prefetchCandidates Let group be « candidate ». Extend group with all items in prefetchCandidates , apart from candidate itself, which are redundant with candidate and whose eagerness is at least as eager as candidate 's eagerness If prefetchCandidateGroups contains another group whose items are the same as group ignoring order, then continue Append group to prefetchCandidateGroups The following speculation rules generate two redundant prefetch candidates "prefetch" "tag" "a" "urls" "next.html" }, "tag" "b" "urls" "next.html" ], "referrer_policy" "no-referrer" This step will create a single group containing them both, in the given order. (The second pass through will not create a group, since its contents would be the same as the first group, just in a different order.) This means that if the user agent chooses to execute the "may" step below to enact the group, it will enact the first candidate, and ignore the second. Thus, the request will be made with the default referrer policy , instead of using " no-referrer ". However, the collect tags from speculative load candidates algorithm will collect tags from both candidates in the group, so the ` Sec-Speculation-Tags header value will be ` "a", "b" `. This indicates to server operators that either rule could have caused the speculative load. For each group of prefetchCandidateGroups The user agent may run the following steps: Let prefetchCandidate be group [0]. Let tagsToSend be the result of collecting tags from speculative load candidates given group Let prefetchRecord be a new prefetch record with source speculation rules URL prefetchCandidate 's URL No-Vary-Search hint prefetchCandidate 's No-Vary-Search hint referrer policy prefetchCandidate 's referrer policy anonymization policy prefetchCandidate 's anonymization policy tags tagsToSend Start a referrer-initiated navigational prefetch given document and prefetchRecord When deciding whether to execute this "may" step, user agents should consider prefetchCandidate 's eagerness , in accordance to the current behavior of the user and the definitions of speculation rule eagerness prefetchCandidate 's No-Vary-Search hint can also be useful in implementing the heuristics defined for the speculation rule eagerness values. For example, a user hovering of a link whose URL is equivalent modulo search variance to prefetchCandidate 's URL given prefetchCandidate 's No-Vary-Search hint could indicate to the user agent that performing this step would be useful. When deciding whether to execute this "may" step, user agents should prioritize user preferences (express or implied, such as data-saver or battery-saver modes) over the eagerness supplied by the web developer. To compute a speculative load referrer policy given a speculation rule rule and an element, area element, or null link If rule 's referrer policy is not the empty string, then return rule 's referrer policy If link is null, then return the empty string. Return link 's hyperlink referrer policy To collect tags from speculative load candidates given a list of speculative load candidates candidates Let tags be an empty ordered set For each candidate of candidates For each tag of candidate 's tags append tag to tags Sort in ascending order tags , with tagA being less than tagB if tagA is null, or if tagA is code unit less than tagB Return tags To find matching links given a Document document and a document rule predicate predicate Let links be an empty list For each shadow-including descendant descendant of document , in shadow-including tree order If descendant is not an or area element with an href attribute, then continue If descendant is not being rendered or is part of skipped contents , then continue Such links, though present in document , aren't available for the user to interact with, and thus are unlikely to be good candidates. In addition, they might not have their style or layout computed, which might make selector matching less efficient in user agents which skip some or all of that work for these elements. If descendant 's url is null, or its scheme is not an HTTP(S) scheme , then continue If predicate matches descendant , then append descendant to links Return links document rule predicate predicate matches an or area element el if the following steps return true, switching on predicate 's type: document rule conjunction For each clause of predicate 's clauses If clause does not match el , then return false. Return true. document rule disjunction For each clause of predicate 's clauses If clause matches el then return true. Return false. document rule negation If predicate 's clause matches el , then return false. Return true. document rule URL pattern predicate For each pattern of predicate 's patterns If performing a match given pattern and el 's url gives a non-null value, then return true. Return false. document rule selector predicate For each selector of predicate 's selectors If performing a match given selector and el with the scoping root set to el 's root returns success, then return true. Return false. Speculation rules features use the speculation rules task source , which is a task source Because speculative loading is generally less important than processing tasks for the purpose of the current document, implementations might give tasks enqueued here an especially low priority. 7.6.2 Navigational prefetching For now, the navigational prefetching process is defined in the Prefetch specification. Moving it into this standard is tracked in issue #11123 [PREFETCH] This standard refers to the following concepts defined there: prefetch record , and its items source URL No-Vary-Search hint referrer policy anonymization policy tags and state cancel and discard still being speculated prefetch records start a referrer-initiated navigational prefetch 7.6.3 The ` Speculation-Rules ` header The ` Speculation-Rules ` HTTP response header allows the developer to request that the user agent fetch and apply a given speculation rule set to the current Document . It is a structured header whose value must be a list of strings that are all valid URL strings To process the ` Speculation-Rules ` header given a Document document and a response response Let parsedList be the result of getting a structured field value given ` Speculation-Rules ` and " list " from response 's header list If parsedList is null, then return. For each item of parsedList If item is not a string , then continue Let url be the result of URL parsing item with document 's document base URL If url is failure, then continue In parallel Optionally, wait for an implementation-defined amount of time. This allows the implementation to prioritize other work ahead of loading speculation rules, as especially during Document creation and header processing, there are often many more important things going on. Queue a global task on the speculation rules task source given document 's relevant global object to perform the following steps: Let request be a new request whose URL is url destination is " speculationrules ", and mode is cors ". Fetch request with the following processResponseConsumeBody steps given response response and null, failure, or a byte sequence bodyBytes If bodyBytes is null or failure, then abort these steps. If response 's status is not an ok status , then abort these steps. If the result of extracting a MIME type from response 's header list does not have an essence of application/speculationrules+json ", then abort these steps. Let bodyText be the result of UTF-8 decoding bodyBytes Let ruleSet be the result of parsing a speculation rule set string given bodyText document , and response 's URL . If this throws an exception, then abort these steps. Append ruleSet to document 's speculation rule sets Consider speculative loads for document 7.6.4 The ` Sec-Speculation-Tags ` header The ` Sec-Speculation-Tags ` HTTP request header specifies the web developer-provided tags associated with the speculative navigation request. It can also be used to distinguish speculative navigation requests from speculative subresource requests, since Sec-Purpose ` can be sent by both categories of requests. The header is a structured header whose value must be a list . The list can contain either token or string values. String values represent developer-provided tags, whereas token values represent predefined tags. As of now, the only predefined tag is null , which indicates a speculative navigation request with no developer-defined tag. 7.6.5 Security considerations 7.6.5.1 Cross-site requests Speculative loads can be initiated by web pages to cross-site destinations. However, because such cross-site speculative loads are always done without credentials , as explained below , ambient authority is limited to requests that are already possible via other mechanisms on the platform. The ` Speculation-Rules ` header can also be used to issue requests, for JSON documents whose body will be parsed as a speculation rule set string . However, they use the " same-origin credentials mode , the " cors mode , and responses which do not use the application/speculationrules+json MIME type essence are ignored, so they are not useful in mounting attacks. 7.6.5.2 Injected content Because links in a document can be selected for speculative loading via document rule predicates , developers need to be cautious if such links might contain user-generated markup. For example, if the href of a link can be entered by one user and displayed to all other users, a malicious user might choose a value like " /logout ", causing other users' browsers to automatically log out of the site when that link is speculatively loaded. Using a document rule selector predicate to exclude such potentially-dangerous links, or using a document rule URL pattern predicate to allowlist known-safe links, are useful techniques in this regard. As with all uses of the script element, developers need to be cautious about inserting user-provided content into tag could be used to break out of the script element context and inject attacker-controlled markup. The ", or having a element that contains a ul element (as the ul element's start tag would imply the end tag for the ). This can enable cross-site scripting attacks. An example of this would be a page that lets the user enter some font family names that are then inserted into a CSS style block via the DOM and which then uses the innerHTML IDL attribute to get the HTML serialization of that style element: if the user enters " as a font family name, innerHTML will return markup that, if parsed in a different context, would contain a script node, even though no script node existed in the original DOM. For example, consider the following markup: form id "outer" >< div > form >< form id "inner" >< input This will be parsed into: html head body form id =" outer div form id =" inner input The input element will be associated with the inner form element. Now, if this tree structure is serialized and reparsed, the