

Web APIs
========



When writing code for the Web, there are a large number of Web APIs available. Below is a list of all the APIs and interfaces (object types) that you may be able to use while developing your Web app or site.

 Web APIs are typically used with JavaScript, although this doesn't always have to be the case.



Specifications
--------------



This is a list of all the APIs that are available.


 ### A

 * [Audio Output Devices API](audio_output_devices_api)  Experimental

 ### B

 * [Background Fetch API](background_fetch_api)  Experimental
* [Background Sync](background_synchronization_api)  Experimental
* [Background Tasks](background_tasks_api)
* [Barcode Detection API](barcode_detection_api)  Experimental
* [Battery API](battery_status_api)
* [Beacon](beacon_api)
* [Bluetooth API](web_bluetooth_api)  Experimental
* [Broadcast Channel API](broadcast_channel_api)

 ### C

 * [CSS Counter Styles](css_counter_styles)
* [CSS Custom Highlight API](css_custom_highlight_api)  Experimental
* [CSS Font Loading API](css_font_loading_api)
* [CSS Painting API](css_painting_api)  Experimental
* [CSS Properties and Values API](css_properties_and_values_api)
* [CSS Typed Object Model API](css_typed_om_api)
* [CSSOM](css_object_model)
* [Canvas API](canvas_api)
* [Channel Messaging API](channel_messaging_api)
* [Clipboard API](clipboard_api)
* [Compression Streams API](compression_streams_api)
* [Console API](console_api)
* [Contact Picker API](contact_picker_api)  Experimental
* [Content Index API](content_index_api)  Experimental
* [Cookie Store API](cookie_store_api)  Experimental
* [Credential Management API](credential_management_api)

 ### D

 * [DOM](document_object_model)
* [Device Orientation Events](device_orientation_events)

 ### E

 * [Encoding API](encoding_api)
* [Encrypted Media Extensions](encrypted_media_extensions_api)
* [EyeDropper API](eyedropper_api)  Experimental

 ### F

 * [FedCM API](fedcm_api)  Experimental
* [Fetch API](fetch_api)
* [File API](file_api)
* [File System Access API](file_system_access_api)
* [File and Directory Entries API](file_and_directory_entries_api)
* [Fullscreen API](fullscreen_api)

 ### G

 * [Gamepad API](gamepad_api)
* [Geolocation API](geolocation_api)
* [Geometry Interfaces](geometry_interfaces)

 ### H

 * [HTML DOM](html_dom_api)
* [HTML Drag and Drop API](html_drag_and_drop_api)
* [HTML Sanitizer API](html_sanitizer_api)  Experimental
* [History API](history_api)

 ### I

 * [Idle Detection API](idle_detection_api)  Experimental
* [Image Capture API](mediastream_image_capture_api)  Experimental
* [IndexedDB](indexeddb_api)
* [Ink API](ink_api)  Experimental
* [Intersection Observer API](intersection_observer_api)

 ### K

 * [Keyboard API](keyboard_api)  Experimental

 ### L

 * [Launch Handler API](launch_handler_api)  Experimental
* [Local Font Access API](local_font_access_api)  Experimental

 ### M

 * [Media Capabilities API](media_capabilities_api)
* [Media Capture and Streams](media_capture_and_streams_api)
* [Media Session API](media_session_api)
* [Media Source Extensions](media_source_extensions_api)  Experimental
* [MediaStream Recording](mediastream_recording_api)

 ### N

 * [Navigation API](navigation_api)  Experimental
* [Network Information API](network_information_api)  Experimental

 ### P

 * [Page Visibility API](page_visibility_api)
* [Payment Handler API](payment_handler_api)  Experimental
* [Payment Request API](payment_request_api)
* [Performance API](performance_api)
* [Periodic Background Sync](web_periodic_background_synchronization_api)  Experimental
* [Permissions API](permissions_api)
* [Picture-in-Picture API](picture-in-picture_api)
* [Pointer Events](pointer_events)
* [Pointer Lock API](pointer_lock_api)
* [Presentation API](presentation_api)  Experimental
* [Prioritized Task Scheduling API](prioritized_task_scheduling_api)
* [Proximity Events](proximity_events)  Experimental   Deprecated
* [Push API](push_api)

 ### R

 * [Reporting API](reporting_api)  Experimental
* [Resize Observer API](resize_observer_api)

 ### S

 * [Screen Capture API](screen_capture_api)
* [Screen Orientation API](screen_orientation_api)
* [Screen Wake Lock API](screen_wake_lock_api)
* [Selection API](selection_api)
* [Sensor API](sensor_apis)
* [Server Sent Events](server-sent_events)
* [Service Workers API](service_worker_api)
* [Storage](storage_api)
* [Storage Access API](storage_access_api)
* [Streams](streams_api)

 ### T

 * [Touch Events](touch_events)
* [Trusted Types API](trusted_types_api)

 ### U

 * [UI Events](ui_events)
* [URL API](url_api)
* [URL Pattern API](url_pattern_api)  Experimental
* [User-Agent Client Hints API](user-agent_client_hints_api)  Experimental

 ### V

 * [Vibration API](vibration_api)
* [View Transitions API](view_transitions_api)  Experimental
* [VirtualKeyboard API](virtualkeyboard_api)  Experimental
* [Visual Viewport](visual_viewport_api)

 ### W

 * [Web Animations](web_animations_api)
* [Web Audio API](web_audio_api)
* [Web Authentication API](web_authentication_api)
* [Web Components](web_components)
* [Web Crypto API](web_crypto_api)
* [Web Locks API](web_locks_api)
* [Web MIDI API](web_midi_api)
* [Web NFC API](web_nfc_api)  Experimental
* [Web Notifications](notifications_api)
* [Web Share API](web_share_api)
* [Web Speech API](web_speech_api)
* [Web Storage API](web_storage_api)
* [Web Workers API](web_workers_api)
* [WebCodecs API](webcodecs_api)
* [WebGL](webgl_api)
* [WebGPU API](webgpu_api)  Experimental
* [WebHID API](webhid_api)  Experimental
* [WebOTP API](webotp_api)
* [WebRTC](webrtc_api)
* [WebTransport API](webtransport_api)  Experimental
* [WebUSB API](webusb_api)  Experimental
* [WebVR API](webvr_api)  Non-standard   Deprecated
* [WebVTT](webvtt_api)
* [WebXR Device API](webxr_device_api)  Experimental
* [Websockets API](websockets_api)
* [Window Controls Overlay API](window_controls_overlay_api)  Experimental

 ### X

 * [XMLHttpRequest](xmlhttprequest)

 
Interfaces
----------



This is a list of all the interfaces (that is, types of objects) that are available.


 ### A


* [`AbortController`](abortcontroller)
* [`AbortSignal`](abortsignal)
* [`AbsoluteOrientationSensor`](absoluteorientationsensor)
* [`AbstractRange`](abstractrange)
* [`Accelerometer`](accelerometer)  Experimental
* [`AesCbcParams`](aescbcparams)
* [`AesCtrParams`](aesctrparams)
* [`AesGcmParams`](aesgcmparams)
* [`AesKeyGenParams`](aeskeygenparams)
* [`AmbientLightSensor`](ambientlightsensor)  Experimental
* [`AnalyserNode`](analysernode)
* [`ANGLE_instanced_arrays`](angle_instanced_arrays)
* [`Animation`](animation)
* [`AnimationEffect`](animationeffect)
* [`AnimationEvent`](animationevent)
* [`AnimationPlaybackEvent`](animationplaybackevent)
* [`AnimationTimeline`](animationtimeline)
* [`Attr`](attr)
* [`AudioBuffer`](audiobuffer)
* [`AudioBufferSourceNode`](audiobuffersourcenode)
* [`AudioContext`](audiocontext)
* [`AudioData`](audiodata)  Experimental
* [`AudioDecoder`](audiodecoder)  Experimental
* [`AudioDestinationNode`](audiodestinationnode)
* [`AudioEncoder`](audioencoder)  Experimental
* [`AudioListener`](audiolistener)
* [`AudioNode`](audionode)
* [`AudioParam`](audioparam)
* [`AudioParamDescriptor`](audioparamdescriptor)
* [`AudioParamMap`](audioparammap)
* [`AudioProcessingEvent`](audioprocessingevent)  Deprecated
* [`AudioScheduledSourceNode`](audioscheduledsourcenode)
* [`AudioSinkInfo`](audiosinkinfo)  Experimental
* [`AudioTrack`](audiotrack)
* [`AudioTrackList`](audiotracklist)
* [`AudioWorklet`](audioworklet)
* [`AudioWorkletGlobalScope`](audioworkletglobalscope)
* [`AudioWorkletNode`](audioworkletnode)
* [`AudioWorkletProcessor`](audioworkletprocessor)
* [`AuthenticatorAssertionResponse`](authenticatorassertionresponse)
* [`AuthenticatorAttestationResponse`](authenticatorattestationresponse)
* [`AuthenticatorResponse`](authenticatorresponse)

 ### B


* [`BackgroundFetchEvent`](backgroundfetchevent)  Experimental
* [`BackgroundFetchManager`](backgroundfetchmanager)  Experimental
* [`BackgroundFetchRecord`](backgroundfetchrecord)  Experimental
* [`BackgroundFetchRegistration`](backgroundfetchregistration)  Experimental
* [`BackgroundFetchUpdateUIEvent`](backgroundfetchupdateuievent)  Experimental
* [`BarcodeDetector`](barcodedetector)  Experimental
* [`BarProp`](barprop)
* [`BaseAudioContext`](baseaudiocontext)
* [`BatteryManager`](batterymanager)
* [`BeforeInstallPromptEvent`](beforeinstallpromptevent)  Experimental   Non-standard
* [`BeforeUnloadEvent`](beforeunloadevent)
* [`BiquadFilterNode`](biquadfilternode)
* [`Blob`](blob)
* [`BlobEvent`](blobevent)
* [`Bluetooth`](bluetooth)  Experimental
* [`BluetoothCharacteristicProperties`](bluetoothcharacteristicproperties)  Experimental
* [`BluetoothDevice`](bluetoothdevice)  Experimental
* [`BluetoothRemoteGATTCharacteristic`](bluetoothremotegattcharacteristic)  Experimental
* [`BluetoothRemoteGATTDescriptor`](bluetoothremotegattdescriptor)  Experimental
* [`BluetoothRemoteGATTServer`](bluetoothremotegattserver)  Experimental
* [`BluetoothRemoteGATTService`](bluetoothremotegattservice)  Experimental
* [`BluetoothUUID`](bluetoothuuid)
* [`BroadcastChannel`](broadcastchannel)
* [`ByteLengthQueuingStrategy`](bytelengthqueuingstrategy)

 ### C


* [`Cache`](cache)
* [`CacheStorage`](cachestorage)
* [`CanMakePaymentEvent`](canmakepaymentevent)  Experimental
* [`CanvasCaptureMediaStreamTrack`](canvascapturemediastreamtrack)
* [`CanvasGradient`](canvasgradient)
* [`CanvasPattern`](canvaspattern)
* [`CanvasRenderingContext2D`](canvasrenderingcontext2d)
* [`CaptureController`](capturecontroller)  Experimental
* [`CaretPosition`](caretposition)  Experimental
* [`CDATASection`](cdatasection)
* [`ChannelMergerNode`](channelmergernode)
* [`ChannelSplitterNode`](channelsplitternode)
* [`CharacterData`](characterdata)
* [`Client`](client)
* [`Clients`](clients)
* [`Clipboard`](clipboard)
* [`ClipboardEvent`](clipboardevent)
* [`ClipboardItem`](clipboarditem)
* [`CloseEvent`](closeevent)
* [`Comment`](comment)
* [`CompositionEvent`](compositionevent)
* [`CompressionStream`](compressionstream)
* [`console`](console)
* [`ConstantSourceNode`](constantsourcenode)
* [`ContactAddress`](contactaddress)  Experimental
* [`ContactsManager`](contactsmanager)  Experimental
* [`ContentIndex`](contentindex)  Experimental
* [`ContentIndexEvent`](contentindexevent)  Experimental
* [`ContentVisibilityAutoStateChangeEvent`](contentvisibilityautostatechangeevent)  Experimental
* [`ConvolverNode`](convolvernode)
* [`CookieChangeEvent`](cookiechangeevent)  Experimental
* [`CookieStore`](cookiestore)  Experimental
* [`CookieStoreManager`](cookiestoremanager)  Experimental
* [`CountQueuingStrategy`](countqueuingstrategy)
* [`Credential`](credential)
* [`CredentialsContainer`](credentialscontainer)
* [`Crypto`](crypto)
* [`CryptoKey`](cryptokey)
* [`CryptoKeyPair`](cryptokeypair)
* [`CSPViolationReportBody`](cspviolationreportbody)
* [`CSS`](css)
* [`CSSAnimation`](cssanimation)
* [`CSSConditionRule`](cssconditionrule)
* [`CSSContainerRule`](csscontainerrule)
* [`CSSCounterStyleRule`](csscounterstylerule)
* [`CSSFontFaceRule`](cssfontfacerule)
* [`CSSFontFeatureValuesRule`](cssfontfeaturevaluesrule)
* [`CSSFontPaletteValuesRule`](cssfontpalettevaluesrule)
* [`CSSGroupingRule`](cssgroupingrule)
* [`CSSImageValue`](cssimagevalue)
* [`CSSImportRule`](cssimportrule)
* [`CSSKeyframeRule`](csskeyframerule)
* [`CSSKeyframesRule`](csskeyframesrule)
* [`CSSKeywordValue`](csskeywordvalue)
* [`CSSLayerBlockRule`](csslayerblockrule)
* [`CSSLayerStatementRule`](csslayerstatementrule)
* [`CSSMathInvert`](cssmathinvert)
* [`CSSMathMax`](cssmathmax)
* [`CSSMathMin`](cssmathmin)
* [`CSSMathNegate`](cssmathnegate)
* [`CSSMathProduct`](cssmathproduct)
* [`CSSMathSum`](cssmathsum)
* [`CSSMathValue`](cssmathvalue)
* [`CSSMatrixComponent`](cssmatrixcomponent)
* [`CSSMediaRule`](cssmediarule)
* [`CSSNamespaceRule`](cssnamespacerule)
* [`CSSNumericArray`](cssnumericarray)
* [`CSSNumericValue`](cssnumericvalue)
* [`CSSPageRule`](csspagerule)
* [`CSSPerspective`](cssperspective)
* [`CSSPositionValue`](csspositionvalue)  Non-standard   Deprecated
* [`CSSPrimitiveValue`](cssprimitivevalue)  Deprecated
* [`CSSPropertyRule`](csspropertyrule)
* [`CSSPseudoElement`](csspseudoelement)  Experimental
* [`CSSRotate`](cssrotate)
* [`CSSRule`](cssrule)
* [`CSSRuleList`](cssrulelist)
* [`CSSScale`](cssscale)
* [`CSSSkew`](cssskew)
* [`CSSSkewX`](cssskewx)
* [`CSSSkewY`](cssskewy)
* [`CSSStyleDeclaration`](cssstyledeclaration)
* [`CSSStyleRule`](cssstylerule)
* [`CSSStyleSheet`](cssstylesheet)
* [`CSSStyleValue`](cssstylevalue)
* [`CSSSupportsRule`](csssupportsrule)
* [`CSSTransformComponent`](csstransformcomponent)
* [`CSSTransformValue`](csstransformvalue)
* [`CSSTransition`](csstransition)
* [`CSSTranslate`](csstranslate)
* [`CSSUnitValue`](cssunitvalue)
* [`CSSUnparsedValue`](cssunparsedvalue)
* [`CSSValue`](cssvalue)  Deprecated
* [`CSSValueList`](cssvaluelist)  Deprecated
* [`CSSVariableReferenceValue`](cssvariablereferencevalue)
* [`CustomElementRegistry`](customelementregistry)
* [`CustomEvent`](customevent)
* [`CustomStateSet`](customstateset)  Experimental

 ### D


* [`DataTransfer`](datatransfer)
* [`DataTransferItem`](datatransferitem)
* [`DataTransferItemList`](datatransferitemlist)
* [`DecompressionStream`](decompressionstream)
* [`DedicatedWorkerGlobalScope`](dedicatedworkerglobalscope)
* [`DelayNode`](delaynode)
* [`DeprecationReportBody`](deprecationreportbody)  Experimental
* [`DeviceMotionEvent`](devicemotionevent)
* [`DeviceMotionEventAcceleration`](devicemotioneventacceleration)
* [`DeviceMotionEventRotationRate`](devicemotioneventrotationrate)
* [`DeviceOrientationEvent`](deviceorientationevent)
* [`DeviceProximityEvent`](deviceproximityevent)  Non-standard   Deprecated
* [`DirectoryEntrySync`](directoryentrysync)  Non-standard   Deprecated
* [`DirectoryReaderSync`](directoryreadersync)  Non-standard   Deprecated
* [`Document`](document)
* [`DocumentFragment`](documentfragment)
* [`DocumentTimeline`](documenttimeline)
* [`DocumentType`](documenttype)
* [`DOMError`](domerror)  Deprecated
* [`DOMException`](domexception)
* [`DOMHighResTimeStamp`](domhighrestimestamp)
* [`DOMImplementation`](domimplementation)
* [`DOMMatrix` (WebKitCSSMatrix)](dommatrix)
* [`DOMMatrixReadOnly`](dommatrixreadonly)
* [`DOMParser`](domparser)
* [`DOMPoint`](dompoint)
* [`DOMPointReadOnly`](dompointreadonly)
* [`DOMQuad`](domquad)
* [`DOMRect`](domrect)
* [`DOMRectReadOnly`](domrectreadonly)
* [`DOMStringList`](domstringlist)
* [`DOMStringMap`](domstringmap)
* [`DOMTokenList`](domtokenlist)
* [`DragEvent`](dragevent)
* [`DynamicsCompressorNode`](dynamicscompressornode)

 ### E


* [`EcdhKeyDeriveParams`](ecdhkeyderiveparams)
* [`EcdsaParams`](ecdsaparams)
* [`EcKeyGenParams`](eckeygenparams)
* [`EcKeyImportParams`](eckeyimportparams)
* [`Element`](element)
* [`ElementInternals`](elementinternals)
* [`EncodedAudioChunk`](encodedaudiochunk)  Experimental
* [`EncodedVideoChunk`](encodedvideochunk)
* [`ErrorEvent`](errorevent)
* [`Event`](event)
* [`EventCounts`](eventcounts)
* [`EventSource`](eventsource)
* [`EventTarget`](eventtarget)
* [`ExtendableCookieChangeEvent`](extendablecookiechangeevent)
* [`ExtendableEvent`](extendableevent)
* [`ExtendableMessageEvent`](extendablemessageevent)
* [`EyeDropper`](eyedropper)  Experimental

 ### F


* [`FeaturePolicy`](featurepolicy)  Experimental
* [`FederatedCredential`](federatedcredential)  Experimental
* [`FetchEvent`](fetchevent)
* [`File`](file)
* [`FileEntrySync`](fileentrysync)  Non-standard   Deprecated
* [`FileList`](filelist)
* [`FileReader`](filereader)
* [`FileReaderSync`](filereadersync)
* [`FileSystem`](filesystem)
* [`FileSystemDirectoryEntry`](filesystemdirectoryentry)
* [`FileSystemDirectoryHandle`](filesystemdirectoryhandle)
* [`FileSystemDirectoryReader`](filesystemdirectoryreader)
* [`FileSystemEntry`](filesystementry)
* [`FileSystemFileEntry`](filesystemfileentry)
* [`FileSystemFileHandle`](filesystemfilehandle)
* [`FileSystemHandle`](filesystemhandle)
* [`FileSystemSync`](filesystemsync)  Non-standard   Deprecated
* [`FileSystemSyncAccessHandle`](filesystemsyncaccesshandle)
* [`FileSystemWritableFileStream`](filesystemwritablefilestream)
* [`FocusEvent`](focusevent)
* [`FontData`](fontdata)  Experimental
* [`FontFace`](fontface)
* [`FontFaceSet`](fontfaceset)
* [`FontFaceSetLoadEvent`](fontfacesetloadevent)
* [`FormData`](formdata)
* [`FormDataEvent`](formdataevent)
* [`FragmentDirective`](fragmentdirective)  Experimental

 ### G


* [`GainNode`](gainnode)
* [`Gamepad`](gamepad)
* [`GamepadButton`](gamepadbutton)
* [`GamepadEvent`](gamepadevent)
* [`GamepadHapticActuator`](gamepadhapticactuator)
* [`GamepadPose`](gamepadpose)  Experimental
* [`Geolocation`](geolocation)
* [`GeolocationCoordinates`](geolocationcoordinates)
* [`GeolocationPosition`](geolocationposition)
* [`GeolocationPositionError`](geolocationpositionerror)
* [`GestureEvent`](gestureevent)  Non-standard
* [`GPU`](gpu)  Experimental
* [`GPUAdapter`](gpuadapter)  Experimental
* [`GPUAdapterInfo`](gpuadapterinfo)  Experimental
* [`GPUBindGroup`](gpubindgroup)  Experimental
* [`GPUBindGroupLayout`](gpubindgrouplayout)  Experimental
* [`GPUBuffer`](gpubuffer)  Experimental
* [`GPUCanvasContext`](gpucanvascontext)  Experimental
* [`GPUCommandBuffer`](gpucommandbuffer)  Experimental
* [`GPUCommandEncoder`](gpucommandencoder)  Experimental
* [`GPUCompilationInfo`](gpucompilationinfo)  Experimental
* [`GPUCompilationMessage`](gpucompilationmessage)  Experimental
* [`GPUComputePassEncoder`](gpucomputepassencoder)  Experimental
* [`GPUComputePipeline`](gpucomputepipeline)  Experimental
* [`GPUDevice`](gpudevice)  Experimental
* [`GPUDeviceLostInfo`](gpudevicelostinfo)  Experimental
* [`GPUError`](gpuerror)  Experimental
* [`GPUExternalTexture`](gpuexternaltexture)  Experimental
* [`GPUInternalError`](gpuinternalerror)  Experimental
* [`GPUOutOfMemoryError`](gpuoutofmemoryerror)  Experimental
* [`GPUPipelineError`](gpupipelineerror)  Experimental
* [`GPUPipelineLayout`](gpupipelinelayout)  Experimental
* [`GPUQuerySet`](gpuqueryset)  Experimental
* [`GPUQueue`](gpuqueue)  Experimental
* [`GPURenderBundle`](gpurenderbundle)  Experimental
* [`GPURenderBundleEncoder`](gpurenderbundleencoder)  Experimental
* [`GPURenderPassEncoder`](gpurenderpassencoder)  Experimental
* [`GPURenderPipeline`](gpurenderpipeline)  Experimental
* [`GPUSampler`](gpusampler)  Experimental
* [`GPUShaderModule`](gpushadermodule)  Experimental
* [`GPUSupportedFeatures`](gpusupportedfeatures)  Experimental
* [`GPUSupportedLimits`](gpusupportedlimits)  Experimental
* [`GPUTexture`](gputexture)  Experimental
* [`GPUTextureView`](gputextureview)  Experimental
* [`GPUUncapturedErrorEvent`](gpuuncapturederrorevent)  Experimental
* [`GPUValidationError`](gpuvalidationerror)  Experimental
* [`GravitySensor`](gravitysensor)
* [`Gyroscope`](gyroscope)

 ### H


* [`HashChangeEvent`](hashchangeevent)
* [`Headers`](headers)
* [`HID`](hid)  Experimental
* [`HIDConnectionEvent`](hidconnectionevent)  Experimental
* [`HIDDevice`](hiddevice)  Experimental
* [`HIDInputReportEvent`](hidinputreportevent)  Experimental
* [`Highlight`](highlight)  Experimental
* [`HighlightRegistry`](highlightregistry)  Experimental
* [`History`](history)
* [`HkdfParams`](hkdfparams)
* [`HmacImportParams`](hmacimportparams)
* [`HmacKeyGenParams`](hmackeygenparams)
* [`HMDVRDevice`](hmdvrdevice)  Non-standard   Deprecated
* [`HTMLAnchorElement`](htmlanchorelement)
* [`HTMLAreaElement`](htmlareaelement)
* [`HTMLAudioElement`](htmlaudioelement)
* [`HTMLBaseElement`](htmlbaseelement)
* [`HTMLBodyElement`](htmlbodyelement)
* [`HTMLBRElement`](htmlbrelement)
* [`HTMLButtonElement`](htmlbuttonelement)
* [`HTMLCanvasElement`](htmlcanvaselement)
* [`HTMLCollection`](htmlcollection)
* [`HTMLDataElement`](htmldataelement)
* [`HTMLDataListElement`](htmldatalistelement)
* [`HTMLDetailsElement`](htmldetailselement)
* [`HTMLDialogElement`](htmldialogelement)
* [`HTMLDivElement`](htmldivelement)
* [`HTMLDListElement`](htmldlistelement)
* [`HTMLDocument`](htmldocument)
* [`HTMLElement`](htmlelement)
* [`HTMLEmbedElement`](htmlembedelement)
* [`HTMLFieldSetElement`](htmlfieldsetelement)
* [`HTMLFontElement`](htmlfontelement)  Deprecated
* [`HTMLFormControlsCollection`](htmlformcontrolscollection)
* [`HTMLFormElement`](htmlformelement)
* [`HTMLFrameSetElement`](htmlframesetelement)  Deprecated
* [`HTMLHeadElement`](htmlheadelement)
* [`HTMLHeadingElement`](htmlheadingelement)
* [`HTMLHRElement`](htmlhrelement)
* [`HTMLHtmlElement`](htmlhtmlelement)
* [`HTMLIFrameElement`](htmliframeelement)
* [`HTMLImageElement`](htmlimageelement)
* [`HTMLInputElement`](htmlinputelement)
* [`HTMLLabelElement`](htmllabelelement)
* [`HTMLLegendElement`](htmllegendelement)
* [`HTMLLIElement`](htmllielement)
* [`HTMLLinkElement`](htmllinkelement)
* [`HTMLMapElement`](htmlmapelement)
* [`HTMLMarqueeElement`](htmlmarqueeelement)  Deprecated
* [`HTMLMediaElement`](htmlmediaelement)
* [`HTMLMenuElement`](htmlmenuelement)
* [`HTMLMenuItemElement`](htmlmenuitemelement)  Non-standard   Deprecated
* [`HTMLMetaElement`](htmlmetaelement)
* [`HTMLMeterElement`](htmlmeterelement)
* [`HTMLModElement`](htmlmodelement)
* [`HTMLObjectElement`](htmlobjectelement)
* [`HTMLOListElement`](htmlolistelement)
* [`HTMLOptGroupElement`](htmloptgroupelement)
* [`HTMLOptionElement`](htmloptionelement)
* [`HTMLOptionsCollection`](htmloptionscollection)
* [`HTMLOutputElement`](htmloutputelement)
* [`HTMLParagraphElement`](htmlparagraphelement)
* [`HTMLParamElement`](htmlparamelement)  Deprecated
* [`HTMLPictureElement`](htmlpictureelement)
* [`HTMLPreElement`](htmlpreelement)
* [`HTMLProgressElement`](htmlprogresselement)
* [`HTMLQuoteElement`](htmlquoteelement)
* [`HTMLScriptElement`](htmlscriptelement)
* [`HTMLSelectElement`](htmlselectelement)
* [`HTMLSlotElement`](htmlslotelement)
* [`HTMLSourceElement`](htmlsourceelement)
* [`HTMLSpanElement`](htmlspanelement)
* [`HTMLStyleElement`](htmlstyleelement)
* [`HTMLTableCaptionElement`](htmltablecaptionelement)
* [`HTMLTableCellElement`](htmltablecellelement)
* [`HTMLTableColElement`](htmltablecolelement)
* [`HTMLTableElement`](htmltableelement)
* [`HTMLTableRowElement`](htmltablerowelement)
* [`HTMLTableSectionElement`](htmltablesectionelement)
* [`HTMLTemplateElement`](htmltemplateelement)
* [`HTMLTextAreaElement`](htmltextareaelement)
* [`HTMLTimeElement`](htmltimeelement)
* [`HTMLTitleElement`](htmltitleelement)
* [`HTMLTrackElement`](htmltrackelement)
* [`HTMLUListElement`](htmlulistelement)
* [`HTMLUnknownElement`](htmlunknownelement)
* [`HTMLVideoElement`](htmlvideoelement)

 ### I


* [`IDBCursor`](idbcursor)
* [`IDBCursorWithValue`](idbcursorwithvalue)
* [`IDBDatabase`](idbdatabase)
* [`IDBFactory`](idbfactory)
* [`IDBIndex`](idbindex)
* [`IDBKeyRange`](idbkeyrange)
* [`IDBLocaleAwareKeyRange`](idblocaleawarekeyrange)  Experimental   Non-standard
* [`IDBObjectStore`](idbobjectstore)
* [`IDBOpenDBRequest`](idbopendbrequest)
* [`IDBRequest`](idbrequest)
* [`IDBTransaction`](idbtransaction)
* [`IDBVersionChangeEvent`](idbversionchangeevent)
* [`IdentityCredential`](identitycredential)  Experimental
* [`IdleDeadline`](idledeadline)
* [`IdleDetector`](idledetector)  Experimental
* [`IIRFilterNode`](iirfilternode)
* [`ImageBitmap`](imagebitmap)
* [`ImageBitmapRenderingContext`](imagebitmaprenderingcontext)
* [`ImageCapture`](imagecapture)  Experimental
* [`ImageData`](imagedata)
* [`ImageDecoder`](imagedecoder)  Experimental
* [`ImageTrack`](imagetrack)  Experimental
* [`ImageTrackList`](imagetracklist)  Experimental
* [`Ink`](ink)  Experimental
* [`InkPresenter`](inkpresenter)  Experimental
* [`InputDeviceCapabilities`](inputdevicecapabilities)  Experimental
* [`InputDeviceInfo`](inputdeviceinfo)
* [`InputEvent`](inputevent)
* [`InstallEvent`](installevent)  Non-standard   Deprecated
* [`IntersectionObserver`](intersectionobserver)
* [`IntersectionObserverEntry`](intersectionobserverentry)
* [`InterventionReportBody`](interventionreportbody)  Experimental

 ### K


* [`Keyboard`](keyboard)  Experimental
* [`KeyboardEvent`](keyboardevent)
* [`KeyboardLayoutMap`](keyboardlayoutmap)  Experimental
* [`KeyframeEffect`](keyframeeffect)

 ### L


* [`LargestContentfulPaint`](largestcontentfulpaint)  Experimental
* [`LaunchParams`](launchparams)  Experimental
* [`LaunchQueue`](launchqueue)  Experimental
* [`LayoutShift`](layoutshift)  Experimental
* [`LayoutShiftAttribution`](layoutshiftattribution)  Experimental
* [`LinearAccelerationSensor`](linearaccelerationsensor)
* [`Location`](location)
* [`Lock`](lock)
* [`LockManager`](lockmanager)

 ### M


* [`Magnetometer`](magnetometer)  Experimental
* [`MathMLElement`](mathmlelement)
* [`MediaCapabilities`](mediacapabilities)
* [`MediaDeviceInfo`](mediadeviceinfo)
* [`MediaDevices`](mediadevices)
* [`MediaElementAudioSourceNode`](mediaelementaudiosourcenode)
* [`MediaEncryptedEvent`](mediaencryptedevent)
* [`MediaError`](mediaerror)
* [`MediaImage`](mediaimage)
* [`MediaKeyMessageEvent`](mediakeymessageevent)
* [`MediaKeys`](mediakeys)
* [`MediaKeySession`](mediakeysession)
* [`MediaKeyStatusMap`](mediakeystatusmap)
* [`MediaKeySystemAccess`](mediakeysystemaccess)
* [`MediaList`](medialist)
* [`MediaMetadata`](mediametadata)
* [`MediaQueryList`](mediaquerylist)
* [`MediaQueryListEvent`](mediaquerylistevent)
* [`MediaRecorder`](mediarecorder)
* [`MediaRecorderErrorEvent`](mediarecordererrorevent)  Non-standard   Deprecated
* [`MediaSession`](mediasession)
* [`MediaSource`](mediasource)
* [`MediaSourceHandle`](mediasourcehandle)  Experimental
* [`MediaStream`](mediastream)
* [`MediaStreamAudioDestinationNode`](mediastreamaudiodestinationnode)
* [`MediaStreamAudioSourceNode`](mediastreamaudiosourcenode)
* [`MediaStreamEvent`](mediastreamevent)  Non-standard   Deprecated
* [`MediaStreamTrack`](mediastreamtrack)
* [`MediaStreamTrackAudioSourceNode`](mediastreamtrackaudiosourcenode)
* [`MediaStreamTrackEvent`](mediastreamtrackevent)
* [`MediaStreamTrackGenerator`](mediastreamtrackgenerator)  Experimental   Non-standard
* [`MediaStreamTrackProcessor`](mediastreamtrackprocessor)  Experimental
* [`MediaTrackConstraints`](mediatrackconstraints)
* [`MediaTrackSettings`](mediatracksettings)
* [`MediaTrackSupportedConstraints`](mediatracksupportedconstraints)
* [`MerchantValidationEvent`](merchantvalidationevent)  Deprecated
* [`MessageChannel`](messagechannel)
* [`MessageEvent`](messageevent)
* [`MessagePort`](messageport)
* [`Metadata`](metadata)  Experimental   Non-standard
* [`MIDIAccess`](midiaccess)
* [`MIDIConnectionEvent`](midiconnectionevent)
* [`MIDIInput`](midiinput)
* [`MIDIInputMap`](midiinputmap)
* [`MIDIMessageEvent`](midimessageevent)
* [`MIDIOutput`](midioutput)
* [`MIDIOutputMap`](midioutputmap)
* [`MIDIPort`](midiport)
* [`MimeType`](mimetype)  Deprecated
* [`MimeTypeArray`](mimetypearray)  Deprecated
* [`MouseEvent`](mouseevent)
* [`MouseScrollEvent`](mousescrollevent)  Non-standard   Deprecated
* [`MutationEvent`](mutationevent)  Deprecated
* [`MutationObserver`](mutationobserver)
* [`MutationRecord`](mutationrecord)

 ### N


* [`NamedNodeMap`](namednodemap)
* [`NavigateEvent`](navigateevent)  Experimental
* [`Navigation`](navigation)  Experimental
* [`NavigationCurrentEntryChangeEvent`](navigationcurrententrychangeevent)  Experimental
* [`NavigationDestination`](navigationdestination)  Experimental
* [`NavigationHistoryEntry`](navigationhistoryentry)  Experimental
* [`NavigationPreloadManager`](navigationpreloadmanager)
* [`NavigationTransition`](navigationtransition)  Experimental
* [`Navigator`](navigator)
* [`NavigatorUAData`](navigatoruadata)  Experimental
* [`NDEFMessage`](ndefmessage)  Experimental
* [`NDEFReader`](ndefreader)  Experimental
* [`NDEFReadingEvent`](ndefreadingevent)  Experimental
* [`NDEFRecord`](ndefrecord)  Experimental
* [`NetworkInformation`](networkinformation)  Experimental
* [`Node`](node)
* [`NodeIterator`](nodeiterator)
* [`NodeList`](nodelist)
* [`Notification`](notification)
* [`NotificationEvent`](notificationevent)
* [`NotifyAudioAvailableEvent`](notifyaudioavailableevent)  Non-standard   Deprecated

 ### O


* [`OES_draw_buffers_indexed`](oes_draw_buffers_indexed)
* [`OfflineAudioCompletionEvent`](offlineaudiocompletionevent)
* [`OfflineAudioContext`](offlineaudiocontext)
* [`OffscreenCanvas`](offscreencanvas)
* [`OffscreenCanvasRenderingContext2D`](offscreencanvasrenderingcontext2d)
* [`OrientationSensor`](orientationsensor)
* [`OscillatorNode`](oscillatornode)
* [`OTPCredential`](otpcredential)  Experimental
* [`OverconstrainedError`](overconstrainederror)

 ### P


* [`PageTransitionEvent`](pagetransitionevent)
* [`PaintWorkletGlobalScope`](paintworkletglobalscope)  Experimental
* [`PannerNode`](pannernode)
* [`PasswordCredential`](passwordcredential)  Experimental
* [`Path2D`](path2d)
* [`PaymentAddress`](paymentaddress)  Non-standard   Deprecated
* [`PaymentManager`](paymentmanager)  Experimental
* [`PaymentMethodChangeEvent`](paymentmethodchangeevent)
* [`PaymentRequest`](paymentrequest)
* [`PaymentRequestEvent`](paymentrequestevent)  Experimental
* [`PaymentRequestUpdateEvent`](paymentrequestupdateevent)
* [`PaymentResponse`](paymentresponse)
* [`Pbkdf2Params`](pbkdf2params)
* [`Performance`](performance)
* [`PerformanceElementTiming`](performanceelementtiming)  Experimental
* [`PerformanceEntry`](performanceentry)
* [`PerformanceEventTiming`](performanceeventtiming)
* [`PerformanceLongTaskTiming`](performancelongtasktiming)  Experimental
* [`PerformanceMark`](performancemark)
* [`PerformanceMeasure`](performancemeasure)
* [`PerformanceNavigation`](performancenavigation)  Deprecated
* [`PerformanceNavigationTiming`](performancenavigationtiming)
* [`PerformanceObserver`](performanceobserver)
* [`PerformanceObserverEntryList`](performanceobserverentrylist)
* [`PerformancePaintTiming`](performancepainttiming)
* [`PerformanceResourceTiming`](performanceresourcetiming)
* [`PerformanceServerTiming`](performanceservertiming)
* [`PerformanceTiming`](performancetiming)  Deprecated
* [`PeriodicSyncEvent`](periodicsyncevent)  Experimental
* [`PeriodicSyncManager`](periodicsyncmanager)  Experimental
* [`PeriodicWave`](periodicwave)
* [`Permissions`](permissions)
* [`PermissionStatus`](permissionstatus)
* [`PictureInPictureEvent`](pictureinpictureevent)
* [`PictureInPictureWindow`](pictureinpicturewindow)
* [`Plugin`](plugin)  Deprecated
* [`PluginArray`](pluginarray)  Deprecated
* [`Point`](webkitpoint)  Non-standard   Deprecated
* [`PointerEvent`](pointerevent)
* [`PopStateEvent`](popstateevent)
* [`PositionSensorVRDevice`](positionsensorvrdevice)  Non-standard   Deprecated
* [`Presentation`](presentation)  Experimental
* [`PresentationAvailability`](presentationavailability)  Experimental
* [`PresentationConnection`](presentationconnection)  Experimental
* [`PresentationConnectionAvailableEvent`](presentationconnectionavailableevent)  Experimental
* [`PresentationConnectionCloseEvent`](presentationconnectioncloseevent)  Experimental
* [`PresentationConnectionList`](presentationconnectionlist)  Experimental
* [`PresentationReceiver`](presentationreceiver)  Experimental
* [`PresentationRequest`](presentationrequest)  Experimental
* [`ProcessingInstruction`](processinginstruction)
* [`ProgressEvent`](progressevent)
* [`PromiseRejectionEvent`](promiserejectionevent)
* [`PublicKeyCredential`](publickeycredential)
* [`PublicKeyCredentialRequestOptions`](publickeycredentialrequestoptions)
* [`PushEvent`](pushevent)
* [`PushManager`](pushmanager)
* [`PushMessageData`](pushmessagedata)
* [`PushSubscription`](pushsubscription)
* [`PushSubscriptionOptions`](pushsubscriptionoptions)

 ### R


* [`RadioNodeList`](radionodelist)
* [`Range`](range)
* [`ReadableByteStreamController`](readablebytestreamcontroller)
* [`ReadableStream`](readablestream)
* [`ReadableStreamBYOBReader`](readablestreambyobreader)
* [`ReadableStreamBYOBRequest`](readablestreambyobrequest)
* [`ReadableStreamDefaultController`](readablestreamdefaultcontroller)
* [`ReadableStreamDefaultReader`](readablestreamdefaultreader)
* [`RelativeOrientationSensor`](relativeorientationsensor)
* [`RemotePlayback`](remoteplayback)
* [`Report`](report)
* [`ReportBody`](reportbody)
* [`ReportingObserver`](reportingobserver)
* [`Request`](request)
* [`ResizeObserver`](resizeobserver)
* [`ResizeObserverEntry`](resizeobserverentry)
* [`ResizeObserverSize`](resizeobserversize)
* [`Response`](response)
* [`RsaHashedImportParams`](rsahashedimportparams)
* [`RsaHashedKeyGenParams`](rsahashedkeygenparams)
* [`RsaOaepParams`](rsaoaepparams)
* [`RsaPssParams`](rsapssparams)
* [`RTCCertificate`](rtccertificate)
* [`RTCDataChannel`](rtcdatachannel)
* [`RTCDataChannelEvent`](rtcdatachannelevent)
* [`RTCDtlsTransport`](rtcdtlstransport)
* [`RTCDTMFSender`](rtcdtmfsender)
* [`RTCDTMFToneChangeEvent`](rtcdtmftonechangeevent)
* [`RTCError`](rtcerror)
* [`RTCErrorEvent`](rtcerrorevent)
* [`RTCIceCandidate`](rtcicecandidate)
* [`RTCIceCandidatePair`](rtcicecandidatepair)
* [`RTCIceCandidatePairStats`](rtcicecandidatepairstats)
* [`RTCIceCandidateStats`](rtcicecandidatestats)
* [`RTCIceParameters`](rtciceparameters)
* [`RTCIceServer`](rtciceserver)
* [`RTCIceTransport`](rtcicetransport)
* [`RTCIdentityAssertion`](rtcidentityassertion)  Experimental
* [`RTCInboundRtpStreamStats`](rtcinboundrtpstreamstats)
* [`RTCOutboundRtpStreamStats`](rtcoutboundrtpstreamstats)
* [`RTCPeerConnection`](rtcpeerconnection)
* [`RTCPeerConnectionIceErrorEvent`](rtcpeerconnectioniceerrorevent)
* [`RTCPeerConnectionIceEvent`](rtcpeerconnectioniceevent)
* [`RTCRemoteOutboundRtpStreamStats`](rtcremoteoutboundrtpstreamstats)
* [`RTCRtpCapabilities`](rtcrtpcapabilities)
* [`RTCRtpCodecCapability`](rtcrtpcodeccapability)
* [`RTCRtpCodecParameters`](rtcrtpcodecparameters)
* [`RTCRtpContributingSource`](rtcrtpcontributingsource)
* [`RTCRtpEncodingParameters`](rtcrtpencodingparameters)
* [`RTCRtpReceiver`](rtcrtpreceiver)
* [`RTCRtpSender`](rtcrtpsender)
* [`RTCRtpStreamStats`](rtcrtpstreamstats)
* [`RTCRtpTransceiver`](rtcrtptransceiver)
* [`RTCSctpTransport`](rtcsctptransport)
* [`RTCSessionDescription`](rtcsessiondescription)
* [`RTCStats`](rtcstats)
* [`RTCStatsReport`](rtcstatsreport)
* [`RTCTrackEvent`](rtctrackevent)

 ### S


* [`Sanitizer`](sanitizer)  Experimental
* [`Scheduler`](scheduler)
* [`Screen`](screen)
* [`ScreenOrientation`](screenorientation)
* [`ScriptProcessorNode`](scriptprocessornode)  Deprecated
* [`SecurityPolicyViolationEvent`](securitypolicyviolationevent)
* [`Selection`](selection)
* [`Sensor`](sensor)
* [`SensorErrorEvent`](sensorerrorevent)
* [`Serial`](serial)  Experimental
* [`SerialPort`](serialport)  Experimental
* [`ServiceWorker`](serviceworker)
* [`ServiceWorkerContainer`](serviceworkercontainer)
* [`ServiceWorkerGlobalScope`](serviceworkerglobalscope)
* [`ServiceWorkerRegistration`](serviceworkerregistration)
* [`ShadowRoot`](shadowroot)
* [`SharedWorker`](sharedworker)
* [`SharedWorkerGlobalScope`](sharedworkerglobalscope)
* [`SourceBuffer`](sourcebuffer)
* [`SourceBufferList`](sourcebufferlist)
* [`SpeechGrammar`](speechgrammar)  Experimental
* [`SpeechGrammarList`](speechgrammarlist)  Experimental
* [`SpeechRecognition`](speechrecognition)
* [`SpeechRecognitionAlternative`](speechrecognitionalternative)
* [`SpeechRecognitionErrorEvent`](speechrecognitionerrorevent)
* [`SpeechRecognitionEvent`](speechrecognitionevent)
* [`SpeechRecognitionResult`](speechrecognitionresult)
* [`SpeechRecognitionResultList`](speechrecognitionresultlist)
* [`SpeechSynthesis`](speechsynthesis)
* [`SpeechSynthesisErrorEvent`](speechsynthesiserrorevent)
* [`SpeechSynthesisEvent`](speechsynthesisevent)
* [`SpeechSynthesisUtterance`](speechsynthesisutterance)
* [`SpeechSynthesisVoice`](speechsynthesisvoice)
* [`StaticRange`](staticrange)
* [`StereoPannerNode`](stereopannernode)
* [`Storage`](storage)
* [`StorageEvent`](storageevent)
* [`StorageManager`](storagemanager)
* [`StylePropertyMap`](stylepropertymap)
* [`StylePropertyMapReadOnly`](stylepropertymapreadonly)
* [`StyleSheet`](stylesheet)
* [`StyleSheetList`](stylesheetlist)
* [`SubmitEvent`](submitevent)
* [`SubtleCrypto`](subtlecrypto)
* [`SVGAElement`](svgaelement)
* [`SVGAltGlyphDefElement`](svgaltglyphdefelement)  Deprecated
* [`SVGAltGlyphElement`](svgaltglyphelement)  Deprecated
* [`SVGAltGlyphItemElement`](svgaltglyphitemelement)  Deprecated
* [`SVGAngle`](svgangle)
* [`SVGAnimateColorElement`](svganimatecolorelement)  Deprecated
* [`SVGAnimatedAngle`](svganimatedangle)
* [`SVGAnimatedBoolean`](svganimatedboolean)
* [`SVGAnimatedEnumeration`](svganimatedenumeration)
* [`SVGAnimatedInteger`](svganimatedinteger)
* [`SVGAnimatedLength`](svganimatedlength)
* [`SVGAnimatedLengthList`](svganimatedlengthlist)
* [`SVGAnimatedNumber`](svganimatednumber)
* [`SVGAnimatedNumberList`](svganimatednumberlist)
* [`SVGAnimatedPreserveAspectRatio`](svganimatedpreserveaspectratio)
* [`SVGAnimatedRect`](svganimatedrect)
* [`SVGAnimatedString`](svganimatedstring)
* [`SVGAnimatedTransformList`](svganimatedtransformlist)
* [`SVGAnimateElement`](svganimateelement)
* [`SVGAnimateMotionElement`](svganimatemotionelement)
* [`SVGAnimateTransformElement`](svganimatetransformelement)
* [`SVGAnimationElement`](svganimationelement)
* [`SVGCircleElement`](svgcircleelement)
* [`SVGClipPathElement`](svgclippathelement)
* [`SVGComponentTransferFunctionElement`](svgcomponenttransferfunctionelement)
* [`SVGCursorElement`](svgcursorelement)  Deprecated
* [`SVGDefsElement`](svgdefselement)
* [`SVGDescElement`](svgdescelement)
* [`SVGElement`](svgelement)
* [`SVGEllipseElement`](svgellipseelement)
* [`SVGEvent`](svgevent)
* [`SVGFEBlendElement`](svgfeblendelement)
* [`SVGFEColorMatrixElement`](svgfecolormatrixelement)
* [`SVGFEComponentTransferElement`](svgfecomponenttransferelement)
* [`SVGFECompositeElement`](svgfecompositeelement)
* [`SVGFEConvolveMatrixElement`](svgfeconvolvematrixelement)
* [`SVGFEDiffuseLightingElement`](svgfediffuselightingelement)
* [`SVGFEDisplacementMapElement`](svgfedisplacementmapelement)
* [`SVGFEDistantLightElement`](svgfedistantlightelement)
* [`SVGFEDropShadowElement`](svgfedropshadowelement)
* [`SVGFEFloodElement`](svgfefloodelement)
* [`SVGFEFuncAElement`](svgfefuncaelement)
* [`SVGFEFuncBElement`](svgfefuncbelement)
* [`SVGFEFuncGElement`](svgfefuncgelement)
* [`SVGFEFuncRElement`](svgfefuncrelement)
* [`SVGFEGaussianBlurElement`](svgfegaussianblurelement)
* [`SVGFEImageElement`](svgfeimageelement)
* [`SVGFEMergeElement`](svgfemergeelement)
* [`SVGFEMergeNodeElement`](svgfemergenodeelement)
* [`SVGFEMorphologyElement`](svgfemorphologyelement)
* [`SVGFEOffsetElement`](svgfeoffsetelement)
* [`SVGFEPointLightElement`](svgfepointlightelement)
* [`SVGFESpecularLightingElement`](svgfespecularlightingelement)
* [`SVGFESpotLightElement`](svgfespotlightelement)
* [`SVGFETileElement`](svgfetileelement)
* [`SVGFETurbulenceElement`](svgfeturbulenceelement)
* [`SVGFilterElement`](svgfilterelement)
* [`SVGFontElement`](svgfontelement)  Deprecated
* [`SVGFontFaceElement`](svgfontfaceelement)  Deprecated
* [`SVGFontFaceFormatElement`](svgfontfaceformatelement)  Deprecated
* [`SVGFontFaceNameElement`](svgfontfacenameelement)  Deprecated
* [`SVGFontFaceSrcElement`](svgfontfacesrcelement)  Deprecated
* [`SVGFontFaceUriElement`](svgfontfaceurielement)  Deprecated
* [`SVGForeignObjectElement`](svgforeignobjectelement)
* [`SVGGElement`](svggelement)
* [`SVGGeometryElement`](svggeometryelement)
* [`SVGGlyphElement`](svgglyphelement)  Deprecated
* [`SVGGlyphRefElement`](svgglyphrefelement)  Deprecated
* [`SVGGradientElement`](svggradientelement)
* [`SVGGraphicsElement`](svggraphicselement)
* [`SVGHKernElement`](svghkernelement)  Deprecated
* [`SVGImageElement`](svgimageelement)
* [`SVGLength`](svglength)
* [`SVGLengthList`](svglengthlist)
* [`SVGLinearGradientElement`](svglineargradientelement)
* [`SVGLineElement`](svglineelement)
* [`SVGMarkerElement`](svgmarkerelement)
* [`SVGMaskElement`](svgmaskelement)
* [`SVGMetadataElement`](svgmetadataelement)
* [`SVGMissingGlyphElement`](svgmissingglyphelement)  Deprecated
* [`SVGMPathElement`](svgmpathelement)
* [`SVGNumber`](svgnumber)
* [`SVGNumberList`](svgnumberlist)
* [`SVGPathElement`](svgpathelement)
* [`SVGPatternElement`](svgpatternelement)
* [`SVGPoint`](svgpoint)  Deprecated
* [`SVGPointList`](svgpointlist)
* [`SVGPolygonElement`](svgpolygonelement)
* [`SVGPolylineElement`](svgpolylineelement)
* [`SVGPreserveAspectRatio`](svgpreserveaspectratio)
* [`SVGRadialGradientElement`](svgradialgradientelement)
* [`SVGRect`](svgrect)
* [`SVGRectElement`](svgrectelement)
* [`SVGRenderingIntent`](svgrenderingintent)  Deprecated
* [`SVGScriptElement`](svgscriptelement)
* [`SVGSetElement`](svgsetelement)
* [`SVGStopElement`](svgstopelement)
* [`SVGStringList`](svgstringlist)
* [`SVGStyleElement`](svgstyleelement)
* [`SVGSVGElement`](svgsvgelement)
* [`SVGSwitchElement`](svgswitchelement)
* [`SVGSymbolElement`](svgsymbolelement)
* [`SVGTextContentElement`](svgtextcontentelement)
* [`SVGTextElement`](svgtextelement)
* [`SVGTextPathElement`](svgtextpathelement)
* [`SVGTextPositioningElement`](svgtextpositioningelement)
* [`SVGTitleElement`](svgtitleelement)
* [`SVGTransform`](svgtransform)
* [`SVGTransformList`](svgtransformlist)
* [`SVGTRefElement`](svgtrefelement)  Deprecated
* [`SVGTSpanElement`](svgtspanelement)
* [`SVGUnitTypes`](svgunittypes)
* [`SVGUseElement`](svguseelement)
* [`SVGViewElement`](svgviewelement)
* [`SVGVKernElement`](svgvkernelement)  Deprecated
* [`SyncEvent`](syncevent)  Experimental
* [`SyncManager`](syncmanager)  Experimental

 ### T


* [`TaskAttributionTiming`](taskattributiontiming)  Experimental
* [`TaskController`](taskcontroller)
* [`TaskPriorityChangeEvent`](taskprioritychangeevent)
* [`TaskSignal`](tasksignal)
* [`Text`](text)
* [`TextDecoder`](textdecoder)
* [`TextDecoderStream`](textdecoderstream)
* [`TextEncoder`](textencoder)
* [`TextEncoderStream`](textencoderstream)
* [`TextMetrics`](textmetrics)
* [`TextTrack`](texttrack)
* [`TextTrackCue`](texttrackcue)
* [`TextTrackCueList`](texttrackcuelist)
* [`TextTrackList`](texttracklist)
* [`TimeEvent`](timeevent)
* [`TimeRanges`](timeranges)
* [`ToggleEvent`](toggleevent)
* [`Touch`](touch)
* [`TouchEvent`](touchevent)
* [`TouchList`](touchlist)
* [`TrackEvent`](trackevent)
* [`TransformStream`](transformstream)
* [`TransformStreamDefaultController`](transformstreamdefaultcontroller)
* [`TransitionEvent`](transitionevent)
* [`TreeWalker`](treewalker)
* [`TrustedHTML`](trustedhtml)
* [`TrustedScript`](trustedscript)
* [`TrustedScriptURL`](trustedscripturl)
* [`TrustedTypePolicy`](trustedtypepolicy)
* [`TrustedTypePolicyFactory`](trustedtypepolicyfactory)

 ### U


* [`UIEvent`](uievent)
* [`URL`](url)
* [`URLPattern`](urlpattern)  Experimental
* [`URLSearchParams`](urlsearchparams)
* [`USB`](usb)  Experimental
* [`USBAlternateInterface`](usbalternateinterface)  Experimental
* [`USBConfiguration`](usbconfiguration)  Experimental
* [`USBConnectionEvent`](usbconnectionevent)  Experimental
* [`USBDevice`](usbdevice)  Experimental
* [`USBEndpoint`](usbendpoint)  Experimental
* [`USBInterface`](usbinterface)  Experimental
* [`USBInTransferResult`](usbintransferresult)  Experimental
* [`USBIsochronousInTransferPacket`](usbisochronousintransferpacket)  Experimental
* [`USBIsochronousInTransferResult`](usbisochronousintransferresult)  Experimental
* [`USBIsochronousOutTransferPacket`](usbisochronousouttransferpacket)  Experimental
* [`USBIsochronousOutTransferResult`](usbisochronousouttransferresult)  Experimental
* [`USBOutTransferResult`](usbouttransferresult)  Experimental
* [`UserActivation`](useractivation)
* [`UserProximityEvent`](userproximityevent)  Non-standard   Deprecated

 ### V


* [`ValidityState`](validitystate)
* [`VideoColorSpace`](videocolorspace)
* [`VideoDecoder`](videodecoder)
* [`VideoEncoder`](videoencoder)
* [`VideoFrame`](videoframe)
* [`VideoPlaybackQuality`](videoplaybackquality)
* [`VideoTrack`](videotrack)
* [`VideoTrackList`](videotracklist)
* [`ViewTransition`](viewtransition)  Experimental
* [`VirtualKeyboard`](virtualkeyboard)  Experimental
* [`VisualViewport`](visualviewport)
* [`VRDisplay`](vrdisplay)  Non-standard   Deprecated
* [`VRDisplayCapabilities`](vrdisplaycapabilities)  Non-standard   Deprecated
* [`VRDisplayEvent`](vrdisplayevent)  Non-standard   Deprecated
* [`VREyeParameters`](vreyeparameters)  Non-standard   Deprecated
* [`VRFieldOfView`](vrfieldofview)  Non-standard   Deprecated
* [`VRFrameData`](vrframedata)  Non-standard   Deprecated
* [`VRLayerInit`](vrlayerinit)  Deprecated
* [`VRPose`](vrpose)  Non-standard   Deprecated
* [`VRStageParameters`](vrstageparameters)  Non-standard   Deprecated
* [`VTTCue`](vttcue)
* [`VTTRegion`](vttregion)

 ### W


* [`WakeLock`](wakelock)
* [`WakeLockSentinel`](wakelocksentinel)
* [`WaveShaperNode`](waveshapernode)
* [`WebGL2RenderingContext`](webgl2renderingcontext)
* [`WebGLActiveInfo`](webglactiveinfo)
* [`WebGLBuffer`](webglbuffer)
* [`WebGLContextEvent`](webglcontextevent)
* [`WebGLFramebuffer`](webglframebuffer)
* [`WebGLObject`](webglobject)
* [`WebGLProgram`](webglprogram)
* [`WebGLQuery`](webglquery)
* [`WebGLRenderbuffer`](webglrenderbuffer)
* [`WebGLRenderingContext`](webglrenderingcontext)
* [`WebGLSampler`](webglsampler)
* [`WebGLShader`](webglshader)
* [`WebGLShaderPrecisionFormat`](webglshaderprecisionformat)
* [`WebGLSync`](webglsync)
* [`WebGLTexture`](webgltexture)
* [`WebGLTransformFeedback`](webgltransformfeedback)
* [`WebGLUniformLocation`](webgluniformlocation)
* [`WebGLVertexArrayObject`](webglvertexarrayobject)
* [`WebSocket`](websocket)
* [`WebTransport`](webtransport)  Experimental
* [`WebTransportBidirectionalStream`](webtransportbidirectionalstream)  Experimental
* [`WebTransportDatagramDuplexStream`](webtransportdatagramduplexstream)  Experimental
* [`WebTransportError`](webtransporterror)  Experimental
* [`WheelEvent`](wheelevent)
* [`Window`](window)
* [`WindowClient`](windowclient)
* [`WindowControlsOverlay`](windowcontrolsoverlay)  Experimental
* [`WindowControlsOverlayGeometryChangeEvent`](windowcontrolsoverlaygeometrychangeevent)  Experimental
* [`Worker`](worker)
* [`WorkerGlobalScope`](workerglobalscope)
* [`WorkerLocation`](workerlocation)
* [`WorkerNavigator`](workernavigator)
* [`Worklet`](worklet)
* [`WorkletGlobalScope`](workletglobalscope)
* [`WritableStream`](writablestream)
* [`WritableStreamDefaultController`](writablestreamdefaultcontroller)
* [`WritableStreamDefaultWriter`](writablestreamdefaultwriter)

 ### X


* [`XMLDocument`](xmldocument)
* [`XMLHttpRequest`](xmlhttprequest)
* [`XMLHttpRequestEventTarget`](xmlhttprequesteventtarget)
* [`XMLHttpRequestUpload`](xmlhttprequestupload)
* [`XMLSerializer`](xmlserializer)
* [`XPathEvaluator`](xpathevaluator)
* [`XPathException`](xpathexception)
* [`XPathExpression`](xpathexpression)
* [`XPathNSResolver`](xpathnsresolver)
* [`XPathResult`](xpathresult)
* [`XRAnchor`](xranchor)  Experimental
* [`XRAnchorSet`](xranchorset)  Experimental
* [`XRBoundedReferenceSpace`](xrboundedreferencespace)  Experimental
* [`XRCompositionLayer`](xrcompositionlayer)  Experimental
* [`XRCPUDepthInformation`](xrcpudepthinformation)  Experimental
* [`XRCubeLayer`](xrcubelayer)  Experimental
* [`XRCylinderLayer`](xrcylinderlayer)  Experimental
* [`XRDepthInformation`](xrdepthinformation)  Experimental
* [`XREquirectLayer`](xrequirectlayer)  Experimental
* [`XRFrame`](xrframe)  Experimental
* [`XRHand`](xrhand)
* [`XRHitTestResult`](xrhittestresult)  Experimental
* [`XRHitTestSource`](xrhittestsource)  Experimental
* [`XRInputSource`](xrinputsource)
* [`XRInputSourceArray`](xrinputsourcearray)  Experimental
* [`XRInputSourceEvent`](xrinputsourceevent)
* [`XRInputSourcesChangeEvent`](xrinputsourceschangeevent)
* [`XRJointPose`](xrjointpose)
* [`XRJointSpace`](xrjointspace)
* [`XRLayer`](xrlayer)  Experimental
* [`XRLayerEvent`](xrlayerevent)  Experimental
* [`XRLightEstimate`](xrlightestimate)  Experimental
* [`XRLightProbe`](xrlightprobe)  Experimental
* [`XRMediaBinding`](xrmediabinding)  Experimental
* [`XRPose`](xrpose)
* [`XRProjectionLayer`](xrprojectionlayer)  Experimental
* [`XRQuadLayer`](xrquadlayer)  Experimental
* [`XRRay`](xrray)  Experimental
* [`XRReferenceSpace`](xrreferencespace)
* [`XRReferenceSpaceEvent`](xrreferencespaceevent)
* [`XRRenderState`](xrrenderstate)  Experimental
* [`XRRigidTransform`](xrrigidtransform)
* [`XRSession`](xrsession)  Experimental
* [`XRSessionEvent`](xrsessionevent)
* [`XRSpace`](xrspace)
* [`XRSubImage`](xrsubimage)  Experimental
* [`XRSystem`](xrsystem)  Experimental
* [`XRTransientInputHitTestResult`](xrtransientinputhittestresult)  Experimental
* [`XRTransientInputHitTestSource`](xrtransientinputhittestsource)  Experimental
* [`XRView`](xrview)  Experimental
* [`XRViewerPose`](xrviewerpose)
* [`XRViewport`](xrviewport)
* [`XRWebGLBinding`](xrwebglbinding)  Experimental
* [`XRWebGLDepthInformation`](xrwebgldepthinformation)  Experimental
* [`XRWebGLLayer`](xrwebgllayer)  Experimental
* [`XRWebGLSubImage`](xrwebglsubimage)  Experimental
* [`XSLTProcessor`](xsltprocessor)

 
See also
--------


* [Web API event reference](https://developer.mozilla.org/en-US/docs/Web/Events)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API>

Audio Output Devices API
========================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The **Audio Output Devices API** allows web applications to prompt users about what audio output device should be used for playback.



Concepts and usage
------------------



 Operating systems commonly allow users to specify that audio should be played from speakers, a Bluetooth headset, or some other audio output device. This API allows applications to provide this same functionality from within a web page, which may provide a better user experience. 

  Setting a particular audio output device requires explicit user permission, as the user may be in a location where playing audio is not appropriate through some output devices. For more information see [Security requirements](#security-requirements) below. 

  Audio devices may arbitrarily connect and disconnect. Applications that wish to react to this kind of change can listen to the [`devicechange` event](mediadevices/devicechange_event) and use [`enumerateDevices()`](mediadevices/enumeratedevices) to determine if `sinkId` is present in the returned devices. This might trigger, for example, pausing or unpausing playback. 



Interfaces
----------


### Extensions to interfaces



The Audio Output Devices API extends the following APIs, adding the listed features:

  [`MediaDevices.selectAudioOutput()`](mediadevices/selectaudiooutput)  This method prompts the user to select a specific audio output device, for example a speaker or headset.

  [`HTMLMediaElement.setSinkId()`](htmlmediaelement/setsinkid)  This method sets the ID of the audio device to use for output, which will be used if permitted.

  [`HTMLMediaElement.sinkId`](htmlmediaelement/sinkid)  This property returns the unique ID of the audio device being used for output, or an empty string if the default user agent device is being used.

  

Security requirements
---------------------



Access to [`MediaDevices.selectAudioOutput()`](mediadevices/selectaudiooutput) is subject to the following constraints:

 * It may only be used in a [secure context](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts).
* Access may be gated by the [`speaker-selection`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy/midi) HTTP [Permission Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy).
* [Transient user activation](https://developer.mozilla.org/en-US/docs/Web/Security/User_activation) is required. The user has to interact with the page or a UI element for this feature to work.
* The user must explicitly grant permission to use the audio output device through a user-agent specific mechanism, or have previously granted permission. Note that if access is denied by a permission policy it cannot be granted by a user permission.

 User permission to set the output device is also implicitly granted if the user has already granted permission to use a media input device in the same group, using [`MediaDevices.getUserMedia()`](mediadevices/getusermedia).

 Other methods/properties also require a secure context and the [`speaker-selection`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy/midi) permission policy.

 The permission status can be queried using the [Permissions API](permissions_api) method [`navigator.permissions.query()`](permissions/query), passing a permission descriptor with the `speaker-selection` permission.



Specifications
--------------




| Specification |
| --- |
| [Audio Output Devices API # dom-mediadevices-selectaudiooutput](https://w3c.github.io/mediacapture-output/#dom-mediadevices-selectaudiooutput) |
| [Audio Output Devices API # dom-htmlmediaelement-setsinkid](https://w3c.github.io/mediacapture-output/#dom-htmlmediaelement-setsinkid) |
| [Audio Output Devices API # dom-htmlmediaelement-sinkid](https://w3c.github.io/mediacapture-output/#dom-htmlmediaelement-sinkid) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Audio_Output_Devices_API` | 49 | 17 | 64preview | No | 36 | No | NoNot available due to [a limitation in Android](https://crbug.com/648286). | NoNot available due to [a limitation in Android](https://crbug.com/648286). | No | NoNot available due to [a limitation in Android](https://crbug.com/648286). | No | NoNot available due to [a limitation in Android](https://crbug.com/648286). |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Audio_Output_Devices_API` | 49 | 17 | 64preview | No | 36 | No | NoNot available due to [a limitation in Android](https://crbug.com/648286). | NoNot available due to [a limitation in Android](https://crbug.com/648286). | No | NoNot available due to [a limitation in Android](https://crbug.com/648286). | No | NoNot available due to [a limitation in Android](https://crbug.com/648286). |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Audio_Output_Devices_API` | No | No | 88preview | No | No | No | No | No | No | No | No | No |


### api.MediaDevices.selectAudioOutput


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.HTMLMediaElement.setSinkId


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.HTMLMediaElement.sinkId


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Audio_Output_Devices_API>

Console API
===========



The Console API provides functionality to allow developers to perform debugging tasks, such as logging messages or the values of variables at set points in your code, or timing how long an operation takes to complete.


 **Note:** This feature is available in [Web Workers](web_workers_api)

 

Concepts and usage
------------------



The Console API started as a largely proprietary API, with different browsers implementing it, albeit in inconsistent ways. [The Console API spec](https://console.spec.whatwg.org/) was created to define consistent behavior, and all modern browsers eventually settled on implementing this behavior — although some implementations still have their own additional proprietary functions. Find out about these at:

 * [Google Chrome DevTools implementation](https://developer.chrome.com/docs/devtools/console/api/)
* [Safari DevTools implementation](https://developer.apple.com/library/archive/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Console/Console.html)

 Usage is very simple — the [`console`](console) object — available via [`window.console`](window/console), or [`WorkerGlobalScope.console`](workerglobalscope/console) in workers; accessible using just `console` — contains many methods that you can call to perform rudimentary debugging tasks, generally focused around logging various values to the browser's [Web Console](https://firefox-source-docs.mozilla.org/devtools-user/web_console/index.html).

 By far the most commonly-used method is [`console.log`](console/log), which is used to log the current value contained inside a specific variable.



Interfaces
----------


 [`console`](console)  Provides rudimentary debugging functionality, including logging, stack traces, timers, and counters.

  
Examples
--------




```
let myString = "Hello world";

// Output "Hello world" to the console
console.log(myString);

```
 See the [console](console#usage) reference page for more examples.



Specifications
--------------




| Specification |
| --- |
| [Console Standard # console-namespace](https://console.spec.whatwg.org/#console-namespace) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Console_API` | 1 | 12 | 4 | 8In Internet Explorer 8 and 9, the `console` object is `undefined` when the developer tools are not open. This behavior was fixed in Internet Explorer 10. | 10.5 | 3 | ≤37 | 18 | 4 | 11 | 1 | 1.0 |
| `assert` | 2 | 12 | 28 | 8 | 11 | 4 | ≤37 | 18 | 28 | 11 | 3.2 | 1.0 |
| `clear` | 25 | 12 | 39 | 8 | 12 | 7 | 4.4 | 25 | 39 | 12 | 7 | 1.5 |
| `count` | 2 | 12 | 30 | 11 | 11 | 4 | ≤37 | 18 | 30 | 11 | 3.2 | 1.0 |
| `countReset` | 68 | 79 | 62 | No | 55 | 13 | 68 | 68 | 62 | 48 | 13 | 10.0 |
| `debug` | 2 | 12 | 5 | 10 | 11 | 4 | ≤37 | 18 | 5 | 11 | 3.2 | 1.0 |
| `dir` | 2 | 12 | 8 | 9 | 11 | 4 | ≤37 | 18 | 8 | 11 | 3.2 | 1.0 |
| `dirxml` | 2 | 12 | 39 | 11 | 11 | 4 | ≤37 | 18 | 39 | 11 | 3.2 | 1.0 |
| `error` | 1 | 12 | 4 | 8 | 10.5 | 3 | 4.4 | 18 | 4 | 11 | 1 | 1.0 |
| `exception` | No | 13–79 | 28 | No | No | No | No | No | 28 | No | No | No |
| `group` | 2 | 12 | 9 | 11 | 11 | 4 | 37 | 18 | 9 | 11 | 3.2 | 1.0 |
| `groupCollapsed` | 6 | 12 | 9 | 11 | 11 | 5.1 | 3 | 18 | 9 | 11 | 5 | 1.0 |
| `groupEnd` | 2 | 12 | 9 | 11 | 11 | 4 | 37 | 18 | 9 | 11 | 3.2 | 1.0 |
| `info` | 1 | 12 | 4 | 8 | 10.5 | 3 | 4.4 | 18 | 4 | 11 | 1 | 1.0 |
| `log` | 1 | 12 | 4 | 8 | 10.5 | 3 | 4.4 | 18 | 4 | 11 | 1 | 1.0 |
| `profile` | 5 | 12 | 16–102 | 9 | 11 | 4 | ≤37 | 18 | 16–102 | 11 | 3.2 | 1.0 |
| `profileEnd` | 5 | 12 | 16 | 9 | 11 | 4 | ≤37 | 18 | 16 | 11 | 3.2 | 1.0 |
| `table` | 27 | 13 | 34 | No | 11 | 7 | 4.4 | 27 | 34 | 11 | 7 | 1.5 |
| `time` | 2 | 12 | 10 | 11 | 11 | 4 | ≤37 | 18 | 10 | 11 | 3.2 | 1.0 |
| `timeEnd` | 2 | 12 | 10 | 11 | 11 | 4 | ≤37 | 18 | 10 | 11 | 3.2 | 1.0 |
| `timeLog` | 71 | 79 | 62 | No | 60 | 13 | 71 | 71 | 62 | 50 | 13 | 10.0 |
| `timeStamp` | 15 | 12 | 39 | 11 | 15 | 6 | ≤37 | 18 | 39 | 14 | 6 | 1.0 |
| `trace` | 2 | 12 | 6 | 11 | 11 | 4 | ≤37 | 18 | 6 | 11 | 3.2 | 1.0 |
| `warn` | 1 | 12 | 4 | 8 | 10.5 | 3 | 4.4 | 18 | 4 | 11 | 1 | 1.0 |
| `worker_support` | 31 | 12 | 29 | 10 | ≤12.1 | 7 | 4.4.3 | 31 | 29 | ≤12.1 | 7 | 2.0 |


See also
--------


* [Tools](https://firefox-source-docs.mozilla.org/devtools-user/index.html)
* [Web Console](https://firefox-source-docs.mozilla.org/devtools-user/web_console/index.html) — how the Web Console in Firefox handles console API calls
* [about:debugging](https://firefox-source-docs.mozilla.org/devtools-user/about_colon_debugging/index.html) — how to see console output when the debugging target is a mobile device


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Console_API>

Background Fetch API
====================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The **Background Fetch API** provides a method for managing downloads that may take a significant amount of time such as movies, audio files, and software.



Concepts and Usage
------------------



When a web application requires the user to download large files, this often presents a problem in that the user needs to stay connected to the page for the download to complete. If they lose connectivity, close the tab or navigate away from the page the download stops.

 The [`Background Synchronization API`](background_synchronization_api) provides a way for service workers to defer processing until a user is connected; however it can't be used for long running tasks such as downloading a large file. Background Sync requires that the service worker stays alive until the fetch is completed, and to conserve battery life and to prevent unwanted tasks happening in the background the browser will at some point terminate the task.

 The Background Fetch API solves this problem. It creates a way for a web developer to tell the browser to perform some fetches in the background, for example when the user clicks a button to download a video file. The browser then performs the fetches in a user-visible way, displaying progress to the user and giving them a method to cancel the download. Once the download is complete the browser then opens the service worker, at which point your application can do something with the response if required.

 The Background Fetch API will enable the fetch to happen if the user starts the process while offline. Once they are connected it will begin. If the user goes off line, the process pauses until the user is on again.



Interfaces
----------


 [`BackgroundFetchManager`](backgroundfetchmanager)  A map where the keys are background fetch IDs and the values are [`BackgroundFetchRegistration`](backgroundfetchregistration) objects.

  [`BackgroundFetchRegistration`](backgroundfetchregistration)  Represents a Background Fetch.

  [`BackgroundFetchRecord`](backgroundfetchrecord)  Represents an individual fetch request and response.

  [`BackgroundFetchEvent`](backgroundfetchevent)  The event type passed to `onbackgroundfetchabort` and `onbackgroundfetchclick`.

  [`BackgroundFetchUpdateUIEvent`](backgroundfetchupdateuievent)  The event type passed to `onbackgroundfetchsuccess` and `onbackgroundfetchfail`.

  
Examples
--------



Before using Background Fetch, check for browser support.

 
```
if (!("BackgroundFetchManager" in self)) {
  // Provide fallback downloading.
}

```
  Using Background Fetch requires a registered service worker. Then call `backgroundFetch.fetch()` to perform a fetch. This returns a promise that resolves with a [`BackgroundFetchRegistration`](backgroundfetchregistration). 

 A background fetch may fetch a number of files. In our example the fetch requests an MP3 and a JPEG. This enables a package of files that the user sees as one item (for example a podcast and artwork) to be downloaded at once.

 
```
navigator.serviceWorker.ready.then(async (swReg) => {
  const bgFetch = await swReg.backgroundFetch.fetch(
    "my-fetch",
    ["/ep-5.mp3", "ep-5-artwork.jpg"],
    {
      title: "Episode 5: Interesting things.",
      icons: [
        {
          sizes: "300x300",
          src: "/ep-5-icon.png",
          type: "image/png",
        },
      ],
      downloadTotal: 60 \* 1024 \* 1024,
    }
  );
});

```
 You can find a demo application which implements Background Fetch [here](https://glitch.com/edit/#!/bgfetch-http203?path=public%2Fclient.js%3A191%3A45).



Specifications
--------------




| Specification |
| --- |
| [Background Fetch # background-fetch-manager](https://wicg.github.io/background-fetch/#background-fetch-manager) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Background_Fetch_API` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `fetch` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `get` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `getIds` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |


See also
--------


* [Introducing Background Fetch](https://developer.chrome.com/blog/background-fetch/)
* [Background Fetch - HTTP 203](https://www.youtube.com/watch?v=cElAoxhQz6w)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Background_Fetch_API>

Background Synchronization API
==============================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The **Background Synchronization API** enables a web app to defer tasks so that they can be run in a [service worker](service_worker_api) once the user has a stable network connection.



Concepts and usage
------------------



The Background Synchronization API allows web applications to defer server synchronization work to their service worker to handle at a later time, if the device is offline. Uses may include sending requests in the background if they couldn't be sent while the application was being used.

 For example, an email client application could let its users compose and send messages at any time, even when the device has no network connection. The application frontend just registers a sync request and the service worker gets alerted when the network is present again and handles the sync.

 The [`SyncManager`](syncmanager) interface is available through [`ServiceWorkerRegistration.sync`](serviceworkerregistration/sync). A unique tag identifier is set to 'name' the sync event, which can then be listened for within the [`ServiceWorker`](serviceworker) script. Once the event is received you can then run any functionality available, such as sending requests to the server.

 As this API relies on service workers, functionality provided by this API is only available in a secure context.

  **Note:** At the time of writing, the Background Synchronization API is only available through an installed [Progressive Web App](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps).

 

Interfaces
----------


 
[`SyncManager`](syncmanager)  Experimental 
  Registers tasks to be run in a service worker at a later time with network connectivity. These tasks are referred to as *background sync requests*.

  
[`SyncEvent`](syncevent)  Experimental 
  Represents a synchronization event, sent to the [global scope](serviceworkerglobalscope) of a [`ServiceWorker`](serviceworker). It provides a way to run tasks in the service worker once the device has network connectivity.

  
### Extensions to other interfaces



The following additions to the [Service Worker API](service_worker_api) provide an entry point for setting up background synchronization.

  
[`ServiceWorkerRegistration.sync`](serviceworkerregistration/sync) Read only 
  Returns a reference to the [`SyncManager`](syncmanager) interface for registering tasks to run once the device has network connectivity.

  
[`ServiceWorkerGlobalScope: sync`](serviceworkerglobalscope/sync_event) event  An event handler fired whenever a [`sync`](serviceworkerglobalscope/sync_event) event occurs. This happens as soon as the network becomes available.

  

Examples
--------


The following examples show how to use the interface.


### Requesting a background sync



The following asynchronous function registers a background sync from a browsing context:

 
```
async function syncMessagesLater() {
  const registration = await navigator.serviceWorker.ready;
  try {
    await registration.sync.register("sync-messages");
  } catch {
    console.log("Background Sync could not be registered!");
  }
}

```


### Verifying a background sync by Tag



This code checks to see if a background sync task with a given tag is registered.

 
```
navigator.serviceWorker.ready.then((registration) => {
  registration.sync.getTags().then((tags) => {
    if (tags.includes("sync-messages"))
      console.log("Messages sync already requested");
  });
});

```


### Listening for a background sync within a Service Worker



The following example shows how to respond to a background sync event in the service worker.

 
```
self.addEventListener("sync", (event) => {
  if (event.tag === "sync-messages") {
    event.waitUntil(sendOutboxMessages());
  }
});

```


Specifications
--------------




| Specification |
| --- |
| [Web Background Synchronization](https://wicg.github.io/background-sync/spec/)  |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Background_Synchronization_API` | 49 | 79 | No | No | 36 | No | 49 | 49 | No | 36 | No | 5.0 |
| `getTags` | 49 | 79 | No | No | 36 | No | 49 | 49 | No | 36 | No | 5.0 |
| `register` | 49 | 79 | No | No | 36 | No | 49 | 49 | No | 36 | No | 5.0 |
| `worker_support` | 6149Only available in the `Window` and `ServiceWorker` global scopes. | 79 | No | No | No | No | 6149Only available in the `Window` and `ServiceWorker` global scopes. | 6149Only available in the `Window` and `ServiceWorker` global scopes. | No | No | No | 8.05.0Only available in the `Window` and `ServiceWorker` global scopes. |


See also
--------


* [Introducing Background Sync](https://developer.chrome.com/blog/background-sync/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Background_Synchronization_API>

Background Tasks API
====================



The **Cooperative Scheduling of Background Tasks API** (also referred to as the Background Tasks API or the `requestIdleCallback()` API) provides the ability to queue tasks to be executed automatically by the user agent when it determines that there is free time to do so.

  **Note:** This API is *not available* in [Web Workers](web_workers_api).

 

Concepts and usage
------------------



The main thread of a Web browser is centered around its event loop. This code draws any pending updates to the [`Document`](document) currently being displayed, runs any JavaScript code the page needs to run, accepts events from input devices, and dispatches those events to the elements that should receive them. In addition, the event loop handles interactions with the operating system, updates to the browser's own user interface, and so forth. It's an extremely busy chunk of code, and your main JavaScript code may run right inside this thread along with all of this. Certainly most if not all code that is capable of making changes to the DOM is running in the main thread, since it's common for user interface changes to only be available to the main thread.

 Because event handling and screen updates are two of the most obvious ways users notice performance issues, it's important for your code to be a good citizen of the Web and help to prevent stalls in the execution of the event loop. In the past, there's been no way to do this reliably other than by writing code that's as efficient as possible and by offloading as much work as possible to [workers](web_workers_api). [`Window.requestIdleCallback()`](window/requestidlecallback) makes it possible to become actively engaged in helping to ensure that the browser's event loop runs smoothly, by allowing the browser to tell your code how much time it can safely use without causing the system to lag. If you stay within the limit given, you can make the user's experience much better.



### Getting the most out of idle callbacks



Because idle callbacks are intended to give your code a way to cooperate with the event loop to ensure that the system is utilized to its full potential without over-tasking it, resulting in lag or other performance problems, you should be thoughtful about how you go about using them.

 * **Use idle callbacks for tasks which don't have high priority.** Because you don't know how many callbacks have been established, and you don't know how busy the user's system is, you don't know how often your callback will be run (unless you specify a `timeout`). There's no guarantee that every pass through the event loop (or even every screen update cycle) will include any idle callbacks being executed; if the event loop uses all available time, you're out of luck (again, unless you've used a `timeout`).
* **Idle callbacks should do their best not to overrun the time allotted.** While the browser, your code, and the Web in general will continue to run normally if you go over the specified time limit (even if you go *way* over it), the time restriction is intended to ensure that you leave the system enough time to finish the current pass through the event loop and get on to the next one without causing other code to stutter or animation effects to lag. Currently, [`timeRemaining()`](idledeadline/timeremaining) has an upper limit of 50 milliseconds, but in reality you will often have less time than that, since the event loop may already be eating into that time on complex sites, with browser extensions needing processor time, and so forth.
* **Avoid making changes to the DOM within your idle callback.** By the time your callback is run, the current frame has already finished drawing, and all layout updates and computations have been completed. If you make changes that affect layout, you may force a situation in which the browser has to stop and do recalculations that would otherwise be unnecessary. If your callback needs to change the DOM, it should use [`Window.requestAnimationFrame()`](window/requestanimationframe) to schedule that.
* **Avoid tasks whose run time can't be predicted.** Your idle callback should avoid doing anything that could take an unpredictable amount of time. For example, anything which might affect layout should be avoided. You should also avoid resolving or rejecting [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)s, since that would invoke the handler for that promise's resolution or rejection as soon as your callback returns.
* **Use timeouts when you need to, but only when you need to.** Using timeouts can ensure that your code runs in a timely manner, but it can also allow you to cause lag or animation stutters by mandating that the browser call you when there's not enough time left for you to run without disrupting performance.



Interfaces
----------



The Background Tasks API adds only one new interface:

  [`IdleDeadline`](idledeadline)  An object of this type is passed to the idle callback to provide an estimate of how long the idle period is expected to last, as well as whether or not the callback is running because its timeout period has expired.

   The [`Window`](window) interface is also augmented by this API to offer the new [`requestIdleCallback()`](window/requestidlecallback) and [`cancelIdleCallback()`](window/cancelidlecallback) methods.



Example
-------



In this example, we'll take a look at how you can use [`requestIdleCallback()`](window/requestidlecallback) to run time-consuming, low-priority tasks during time the browser would otherwise be idle. In addition, this example demonstrates how to schedule updates to the document content using [`requestAnimationFrame()`](window/requestanimationframe).

 Below you'll find only the HTML and JavaScript for this example. The CSS is not shown, since it's not particularly crucial to understanding this functionality.



### HTML content



In order to be oriented about what we're trying to accomplish, let's have a look at the HTML. This establishes a box (`id="container"`) that's used to present the progress of an operation (because you never know how long decoding "quantum filament tachyon emissions" will take, after all) as well as a second main box (`id="logBox"`), which is used to display textual output.

 
```
<p>
  Demonstration of using cooperatively scheduled background tasks using the
  <code>requestIdleCallback()</code> method.
</p>

<div id="container">
  <div class="label">Decoding quantum filament tachyon emissions…</div>

  <progress id="progress" value="0"></progress>

  <button class="button" id="startButton">Start</button>

  <div class="label counter">
    Task <span id="currentTaskNumber">0</span> of
    <span id="totalTaskCount">0</span>
  </div>
</div>

<div id="logBox">
  <div class="logHeader">Log</div>
  <div id="log"></div>
</div>

```
 The progress box uses a [`<progress>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress) element to show the progress, along with a label with sections that are changed to present numeric information about the progress. In addition, there's a "Start" button (creatively given the ID "startButton"), which the user will use to start the data processing.



### JavaScript content



Now that the document structure is defined, construct the JavaScript code that will do the work. The goal: to be able to add requests to call functions to a queue, with an idle callback that runs those functions whenever the system is idle for long enough a time to make progress.

 #### Variable declarations

 
```
const taskList = [];
let totalTaskCount = 0;
let currentTaskNumber = 0;
let taskHandle = null;

```
 These variables are used to manage the list of tasks that are waiting to be performed, as well as status information about the task queue and its execution:

 * `taskList` is an [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of objects, each representing one task waiting to be run.
* `totalTaskCount` is a counter of the number of tasks that have been added to the queue; it will only go up, never down. We use this to do the math to present progress as a percentage of total work to do.
* `currentTaskNumber` is used to track how many tasks have been processed so far.
* `taskHandle` is a reference to the task currently being processed.

 
```
const totalTaskCountElem = document.getElementById("totalTaskCount");
const currentTaskNumberElem = document.getElementById("currentTaskNumber");
const progressBarElem = document.getElementById("progress");
const startButtonElem = document.getElementById("startButton");
const logElem = document.getElementById("log");

```
 Next we have variables which reference the DOM elements we need to interact with. These elements are:

 * `totalTaskCountElem` is the [`<span>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span) we use to insert the total number of tasks created into the status display in the progress box.
* `currentTaskNumberElem` is the element used to display the number of tasks processed so far.
* `progressBarElem` is the [`<progress>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress) element showing the percentage of the tasks processed so far.
* `startButtonElem` is the start button.
* `logElem` is the [`<div>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div) we'll insert logged text messages into.

 
```
let logFragment = null;
let statusRefreshScheduled = false;

```
 Finally, we set up a couple of variables for other items:

 * `logFragment` will be used to store a [`DocumentFragment`](documentfragment) that's generated by our logging functions to create content to append to the log when the next animation frame is rendered.
* `statusRefreshScheduled` is used to track whether or not we've already scheduled an update of the status display box for the upcoming frame, so that we only do it once per frame

 #### Managing the task queue

 Next, let's look at the way we manage the tasks that need to be performed. We're going to do this by creating a FIFO queue of tasks, which we'll run as time allows during the idle callback period.

 ##### Enqueueing tasks

 First, we need a function that enqueues tasks for future execution. That function, `enqueueTask()`, looks like this:

 
```
function enqueueTask(taskHandler, taskData) {
  taskList.push({
    handler: taskHandler,
    data: taskData,
  });

  totalTaskCount++;

  if (!taskHandle) {
    taskHandle = requestIdleCallback(runTaskQueue, { timeout: 1000 });
  }

  scheduleStatusRefresh();
}

```
 `enqueueTask()` accepts as input two parameters:

 * `taskHandler` is a function which will be called to handle the task.
* `taskData` is an object which is passed into the task handler as an input parameter, to allow the task to receive custom data.

 To enqueue the task, we [push](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) an object onto the `taskList` array; the object contains the `taskHandler` and `taskData` values under the names `handler` and `data`, respectively, then increment `totalTaskCount`, which reflects the total number of tasks which have ever been enqueued (we don't decrement it when tasks are removed from the queue).

 Next, we check to see if we already have an idle callback created; if `taskHandle` is 0, we know there isn't an idle callback yet, so we call [`requestIdleCallback()`](window/requestidlecallback) to create one. It's configured to call a function called `runTaskQueue()`, which we'll look at shortly, and with a `timeout` of 1 second, so that it will be run at least once per second even if there isn't any actual idle time available.

 ##### Running tasks

 Our idle callback handler, `runTaskQueue()`, gets called when the browser determines there's enough idle time available to let us do some work or our timeout of one second expires. This function's job is to run our enqueued tasks.

 
```
function runTaskQueue(deadline) {
  while (
    (deadline.timeRemaining() > 0 || deadline.didTimeout) &&
    taskList.length
  ) {
    const task = taskList.shift();
    currentTaskNumber++;

    task.handler(task.data);
    scheduleStatusRefresh();
  }

  if (taskList.length) {
    taskHandle = requestIdleCallback(runTaskQueue, { timeout: 1000 });
  } else {
    taskHandle = 0;
  }
}

```
 `runTaskQueue()`'s core is a loop which continues as long as there's time left (as determined by checking [`deadline.timeRemaining`](idledeadline/timeremaining)) to be sure it's more than 0 or if the timeout limit was reached ([`deadline.didTimeout`](idledeadline/didtimeout) is true), and as long as there are tasks in the task list.

 For each task in the queue that we have time to execute, we do the following:

 1. We [remove the task object from the queue](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift).
2. We increment `currentTaskNumber` to track how many tasks we've executed.
3. We call the task's handler, `task.handler`, passing into it the task's data object (`task.data`).
4. We call a function, `scheduleStatusRefresh()`, to handle scheduling a screen update to reflect changes to our progress.

 When time runs out, if there are still tasks left in the list, we call [`requestIdleCallback()`](window/requestidlecallback) again so that we can continue to process the tasks the next time there's idle time available. If the queue is empty, we set taskHandle to 0 to indicate that we don't have a callback scheduled. That way, we'll know to request a callback next time `enqueueTask()` is called.

 #### Updating the status display

 One thing we want to be able to do is update our document with log output and progress information. However, you can't safely change the DOM from within an idle callback. Instead, we'll use [`requestAnimationFrame()`](window/requestanimationframe) to ask the browser to call us when it's safe to update the display.

 ##### Scheduling display updates

 DOM changes are scheduled by calling the `scheduleStatusRefresh()` function.

 
```
function scheduleStatusRefresh() {
  if (!statusRefreshScheduled) {
    requestAnimationFrame(updateDisplay);
    statusRefreshScheduled = true;
  }
}

```
 This is a simple function. It checks to see if we've already scheduled a display refresh by checking the value of `statusRefreshScheduled`. If it's `false`, we call [`requestAnimationFrame()`](window/requestanimationframe) to schedule a refresh, providing the `updateDisplay()` function to be called to handle that work.

 ##### Updating the display

 The `updateDisplay()` function is responsible for drawing the contents of the progress box and the log. It's called by the browser when the DOM is in a safe condition for us to apply changes during the process of rendering the next frame.

 
```
function updateDisplay() {
  const scrolledToEnd =
    logElem.scrollHeight - logElem.clientHeight <= logElem.scrollTop + 1;

  if (totalTaskCount) {
    if (progressBarElem.max !== totalTaskCount) {
      totalTaskCountElem.textContent = totalTaskCount;
      progressBarElem.max = totalTaskCount;
    }

    if (progressBarElem.value !== currentTaskNumber) {
      currentTaskNumberElem.textContent = currentTaskNumber;
      progressBarElem.value = currentTaskNumber;
    }
  }

  if (logFragment) {
    logElem.appendChild(logFragment);
    logFragment = null;
  }

  if (scrolledToEnd) {
    logElem.scrollTop = logElem.scrollHeight - logElem.clientHeight;
  }

  statusRefreshScheduled = false;
}

```
 First, `scrolledToEnd` is set to `true` if the text in the log is scrolled to the bottom; otherwise it's set to `false`. We'll use that to determine if we should update the scroll position to ensure that the log stays at the end when we're done adding content to it.

 Next, we update the progress and status information if any tasks have been enqueued.

 1. If the current maximum value of the progress bar is different from the current total number of enqueued tasks (`totalTaskCount`), then we update the contents of the displayed total number of tasks (`totalTaskCountElem`) and the maximum value of the progress bar, so that it scales properly.
2. We do the same thing with the number of tasks processed so far; if `progressBarElem.value` is different from the task number currently being processed (`currentTaskNumber`), then we update the displayed value of the currently-being-processed task and the current value of the progress bar.

 Then, if there's text waiting to be added to the log (that is, if `logFragment` isn't `null`), we append it to the log element using [`Element.appendChild()`](node/appendchild) and set `logFragment` to `null` so we don't add it again.

 If the log was scrolled to the end when we started, we make sure it still is. Then we set `statusRefreshScheduled` to `false` to indicate that we've handled the refresh and that it's safe to request a new one.

 #### Adding text to the log

 The `log()` function adds the specified text to the log. Since we don't know at the time `log()` is called whether or not it's safe to immediately touch the DOM, we will cache the log text until it's safe to update. Above, in the code for `updateDisplay()`, you can find the code that actually adds the logged text to the log element when the animation frame is being updated.

 
```
function log(text) {
  if (!logFragment) {
    logFragment = document.createDocumentFragment();
  }

  const el = document.createElement("div");
  el.textContent = text;
  logFragment.appendChild(el);
}

```
 First, we create a [`DocumentFragment`](documentfragment) object named `logFragment` if one doesn't currently exist. This element is a pseudo-DOM into which we can insert elements without immediately changing the main DOM itself.

 We then create a new [`<div>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div) element and set its contents to match the input `text`. Then we append the new element to the end of the pseudo-DOM in `logFragment`. `logFragment` will accumulate log entries until the next time `updateDisplay()` is called because the DOM for the changes.



### Running tasks



Now that we've got the task management and display maintenance code done, we can actually start setting up code to run tasks that get work done.

 #### The task handler

 The function we'll be using as our task handler—that is, the function that will be used as the value of the task object's `handler` property—is `logTaskHandler()`. It's a simple function that outputs a bunch of stuff to the log for each task. In your own application, you'd replace this code with whatever task it is you wish to perform during idle time. Just remember that anything you want to do that changes the DOM needs to be handled through [`requestAnimationFrame()`](window/requestanimationframe).

 
```
function logTaskHandler(data) {
  log(`Running task #${currentTaskNumber}`);

  for (let i = 0; i < data.count; i += 1) {
    log(`${(i + 1).toString()}. ${data.text}`);
  }
}

```
 #### The main program

 Everything is triggered when the user clicks the Start button, which causes the `decodeTechnoStuff()` function to be called.

 
```
function decodeTechnoStuff() {
  totalTaskCount = 0;
  currentTaskNumber = 0;
  updateDisplay();

  const n = getRandomIntInclusive(100, 200);

  for (let i = 0; i < n; i++) {
    const taskData = {
      count: getRandomIntInclusive(75, 150),
      text: `This text is from task number ${i + 1} of ${n}`,
    };

    enqueueTask(logTaskHandler, taskData);
  }
}

document
  .getElementById("startButton")
  .addEventListener("click", decodeTechnoStuff, false);

```
 `decodeTechnoStuff()` starts by zeroing the values of totalTaskCount (the number of tasks added to the queue so far) and currentTaskNumber (the task currently being run), and then calls `updateDisplay()` to reset the display to its "nothing's happened yet" state.

 This example will create a random number of tasks (between 100 and 200 of them). To do so, we use the [`getRandomIntInclusive()` function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#getting_a_random_integer_between_two_values_inclusive) that's provided as an example in the documentation for [`Math.random()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) to get the number of tasks to create.

 Then we start a loop to create the actual tasks. For each task, we create an object, `taskData`, which includes two properties:

 * `count` is the number of strings to output into the log from the task.
* `text` is the text to output to the log the number of times specified by `count`.

 Each task is then enqueued by calling `enqueueTask()`, passing in `logTaskHandler()` as the handler function and the `taskData` object as the object to pass into the function when it's called.



### Result



Below is the actual functioning result of the code above. Try it out, play with it in your browser's developer tools, and experiment with using it in your own code.




Specifications
--------------




| Specification |
| --- |
| [requestIdleCallback() Cooperative Scheduling of Background Tasks # the-requestidlecallback-method](https://w3c.github.io/requestidlecallback/#the-requestidlecallback-method) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Background_Tasks_API` | 47 | 79 | 55 | No | 34 | No | 47 | 47 | 55 | 34 | No | 5.0 |


See also
--------


* [`Window.requestIdleCallback()`](window/requestidlecallback)
* [`Window.cancelIdleCallback()`](window/cancelidlecallback)
* [`IdleDeadline`](idledeadline)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Background_Tasks_API>

Barcode Detection API
=====================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

  **Note:** This feature is available in [Web Workers](web_workers_api)

  **Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The Barcode Detection API detects linear and two-dimensional barcodes in images.



Concepts and usage
------------------



Support for barcode recognition within web apps unlocks a variety of use cases through supported barcode formats. QR codes can be used for online payments, web navigation or establishing social media connections, Aztec codes can be used to scan boarding passes and shopping apps can use EAN or UPC barcodes to compare prices of physical items.

  Detection is achieved through the [`detect()`](barcodedetector/detect) method, which takes an image object; it can be one of these objects: an [`SVGImageElement`](svgimageelement), an [`HTMLVideoElement`](htmlvideoelement), an [`HTMLCanvasElement`](htmlcanvaselement), an [`ImageBitmap`](imagebitmap), an [`OffscreenCanvas`](offscreencanvas), a [`VideoFrame`](videoframe), a [`Blob`](blob), or an [`ImageData`](imagedata). Optional parameters can be passed to the [`BarcodeDetector`](barcodedetector) constructor to provide hints on which barcode formats to detect. 



### Supported barcode formats



The Barcode Detection API supports the following barcode formats:

 

| Format | Description | Image |
| --- | --- | --- |
| aztec |  A square two-dimensional matrix following iso24778 and with a square bullseye pattern at their center, thus resembling an Aztec pyramid. Does not require a surrounding blank zone.  | A sample image of an Aztec barcode. A square with smaller black and white squares inside |
| code\_128 |  A linear (one-dimensional), bidirectionally-decodable, self-checking barcode following iso15417 and able to encode all 128 characters of ASCII (hence the naming).  | An image of a code-128 barcode. A horizontal distribution of vertical black and white lines |
| code\_39 |  A linear (one-dimensional), self-checking barcode following iso16388. It is a discrete and variable-length barcode type.  | An image of a code-39 barcode. A horizontal distribution of vertical black and white lines |
| code\_93 |  A linear, continuous symbology with a variable length following bc5. It offers a larger information density than Code 128 and the visually similar Code 39. Code 93 is used primarily by Canada Post to encode supplementary delivery information.  | An image of a code 93 format barcode. A horizontal distribution of white and black horizontal lines |
| codabar | A linear barcode representing characters 0-9, A-D and symbols - . $ / + | An image of a codabar format barcode. A horizontal distribution of black and white vertical lines |
| data\_matrix |  An orientation-independent two-dimensional barcode composed of black and white modules arranged in either a square or rectangular pattern following iso16022.  | An example of a data matrix barcode. A square filled with smaller black and white squares |
| ean\_13 | A linear barcode based on the UPC-A standard and defined in iso15420. | An image of an EAN-13 format barcode. A horizontal distribution of white and black lines |
| ean\_8 | A linear barcode defined in iso15420 and derived from EAN-13. | An image of an EAN-8 format barcode. A horizontal distribution of vertical black and white lines |
| itf |  A continuous, self-checking, bidirectionally decodable barcode. It will always encode 14 digits.  | An image of an ITF Barcode. A horizontal distribution of white and black lines |
| pdf417 |  A continuous two-dimensional barcode symbology format with multiple rows and columns. It's bi-directionally decodable and uses the iso15438 standard.  | An example of a pdf417 barcode format. A rectangle of smaller black and white squares |
| qr\_code |  A two-dimensional barcode that uses the iso18004 standard. The information encoded can be text, URL or other data.  | An example of a QR code. A square of smaller black and white squares |
| upc\_a |  One of the most common linear barcode types and is widely applied to retail in the United States. Defined in iso15420, it represents digits by strips of bars and spaces, each digit being associated to a unique pattern of 2 bars and 2 spaces, both of variable width. UPC-A can encode 12 digits that are uniquely assigned to each trade item, and it's technically a subset of EAN-13 (UPC-A codes are represented in EAN-13 with the first character set to 0).  | An image of a upc-a barcode. A rectangle of black and white vertical lines with numbers underneath |
| upc\_e |  A variation of UPC-A defined in iso15420, compressing out unnecessary zeros for a more compact barcode.  | An image of a upc-e barcode. A rectangle of black and white vertical lines |
| unknown |  This value is used by the platform to signify that it does not know or specify which barcode format is being detected or supported.  |  |

 You can check for formats supported by the user agent via the [`getSupportedFormats()`](barcodedetector/getsupportedformats) method.



Interfaces
----------


 
[`BarcodeDetector`](barcodedetector)  Experimental 
  The `BarcodeDetector` interface of the Barcode Detection API allows detection of linear and two dimensional barcodes in images.

  
Examples
--------


### Creating A Detector



This example tests for browser compatibility and creates a new barcode detector object, with specified supported formats.

 
```
// check compatibility
if (!("BarcodeDetector" in window)) {
  console.log("Barcode Detector is not supported by this browser.");
} else {
  console.log("Barcode Detector supported!");

  // create new detector
  const barcodeDetector = new BarcodeDetector({
    formats: ["code\_39", "codabar", "ean\_13"],
  });
}

```


### Getting Supported Formats



The following example calls the `getSupportedFormats()` method and logs the results to the console.

 
```
// check supported types
BarcodeDetector.getSupportedFormats().then((supportedFormats) => {
  supportedFormats.forEach((format) => console.log(format));
});

```


### Detect Barcodes



This example uses the `detect()` method to detect the barcodes within the given image. These are iterated over and the barcode data is logged to the console.

 
```
barcodeDetector
  .detect(imageEl)
  .then((barcodes) => {
    barcodes.forEach((barcode) => console.log(barcode.rawValue));
  })
  .catch((err) => {
    console.log(err);
  });

```


Specifications
--------------




| Specification |
| --- |
| [Accelerated Shape Detection in Images # barcode-detection-api](https://wicg.github.io/shape-detection-api/#barcode-detection-api) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `BarcodeDetector` | 88Supported on Chrome OS and macOS only.83–88Supported on macOS only. | 83Supported on macOS only. | No | No | 69Supported on macOS only. | No | 83 | 83 | No | 59 | No | 13.0 |
| `Barcode_Detection_API` | 88Supported on Chrome OS and macOS only.83–88Supported on macOS only. | 83Supported on macOS only. | No | No | 69Supported on macOS only. | No | 83 | 83 | No | 59 | No | 13.0 |
| `detect` | 88Supported on Chrome OS and macOS only.83–88Supported on macOS only. | 83Supported on macOS only. | No | No | 69Supported on macOS only. | No | 83 | 83 | No | 59 | No | 13.0 |
| `getSupportedFormats` | 88Supported on Chrome OS and macOS only.83–88Supported on macOS only. | 83Supported on macOS only. | No | No | 69Supported on macOS only. | No | 83 | 83 | No | 59 | No | 13.0 |


See also
--------


* [barcodefaq.com: A website with information about different barcodes and examples of the different types.](https://www.barcodefaq.com/)
* [The Shape Detection API: a picture is worth a thousand words, faces, and barcodes](https://web.dev/shape-detection/#barcodedetector)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Barcode_Detection_API>

Battery Status API
==================



The **Battery Status API**, more often referred to as the **Battery API**, provides information about the system's battery charge level and lets you be notified by events that are sent when the battery level or charging status change. This can be used to adjust your app's resource usage to reduce battery drain when the battery is low, or to save changes before the battery runs out in order to prevent data loss.

  **Note:** This API is *not available* in [Web Workers](web_workers_api) (not exposed via [`WorkerNavigator`](workernavigator)).

 

Interfaces
----------


 [`BatteryManager`](batterymanager)  Provides information about the system's battery charge level.

  
[`navigator.getBattery()`](navigator/getbattery) Read only 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with a [`BatteryManager`](batterymanager) object.

  
Example
-------



In this example, we watch for changes both to the charging status (whether or not we're plugged in and charging) and for changes to the battery level and timing. This is done by listening for the [`chargingchange`](batterymanager/chargingchange_event), [`levelchange`](batterymanager/levelchange_event), [`chargingtimechange`](batterymanager/chargingtimechange_event), [`dischargingtimechange`](batterymanager/dischargingtimechange_event) events.

 
```
navigator.getBattery().then((battery) => {
  function updateAllBatteryInfo() {
    updateChargeInfo();
    updateLevelInfo();
    updateChargingInfo();
    updateDischargingInfo();
  }
  updateAllBatteryInfo();

  battery.addEventListener("chargingchange", () => {
    updateChargeInfo();
  });
  function updateChargeInfo() {
    console.log(`Battery charging? ${battery.charging ? "Yes" : "No"}`);
  }

  battery.addEventListener("levelchange", () => {
    updateLevelInfo();
  });
  function updateLevelInfo() {
    console.log(`Battery level: ${battery.level \* 100}%`);
  }

  battery.addEventListener("chargingtimechange", () => {
    updateChargingInfo();
  });
  function updateChargingInfo() {
    console.log(`Battery charging time: ${battery.chargingTime} seconds`);
  }

  battery.addEventListener("dischargingtimechange", () => {
    updateDischargingInfo();
  });
  function updateDischargingInfo() {
    console.log(`Battery discharging time: ${battery.dischargingTime} seconds`);
  }
});

```
 See also [the example in the specification](https://www.w3.org/TR/battery-status/#examples).



Specifications
--------------




| Specification |
| --- |
| [Battery Status API # the-batterymanager-interface](https://w3c.github.io/battery/#the-batterymanager-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Battery_Status_API` | 38 | 79 | 43–52 | No | 25 | No | 38 | 38 | 43–52 | 25 | No | 3.0 |
| `charging` | 38 | 79 | 43–52 | No | 25 | No | 38 | 38 | 43–52 | 25 | No | 3.0 |
| `chargingTime` | 38 | 79 | 43–52 | No | 25 | No | 4238–42Always equal to `0` or `Infinity`. | 4238–42Always equal to `0` or `Infinity`. | 43–52 | 2925–29Always equal to `0` or `Infinity`. | No | 4.03.0–4.0Always equal to `0` or `Infinity`. |
| `chargingchange_event` | 38 | 79 | 43–52 | No | 25 | No | 38 | 38 | 43–52 | 25 | No | 3.0 |
| `chargingtimechange_event` | 38 | 79 | 43–52 | No | 25 | No | 38 | 38 | 43–52 | 25 | No | 3.0 |
| `dischargingTime` | 38 | 79 | 43–52 | No | 25 | No | 4238–42Always equal to `Infinity`. | 4238–42Always equal to `Infinity`. | 43–52 | 2925–29Always equal to `Infinity`. | No | 4.03.0–4.0Always equal to `Infinity`. |
| `dischargingtimechange_event` | 38 | 79 | 43–52 | No | 25 | No | 38 | 38 | 43–52 | 25 | No | 3.0 |
| `level` | 38 | 79 | 43–52 | No | 25 | No | 38 | 38 | 43–52 | 25 | No | 3.0 |
| `levelchange_event` | 38 | 79 | 43–52 | No | 25 | No | 38 | 38 | 43–52 | 25 | No | 3.0 |
| `secure_context_required` | 103 | 103 | No | No | No | No | 103 | 103 | No | 71 | No | 20.0 |


See also
--------


* [Hacks blog post - Using the Battery API](https://hacks.mozilla.org/2012/02/using-the-battery-api-part-of-webapi/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Battery_Status_API>

Beacon API
==========



The `Beacon` API is used to send an asynchronous and non-blocking request to a web server. The request does not expect a response. Unlike requests made using [`XMLHttpRequest`](xmlhttprequest) or the [Fetch API](fetch_api), the browser guarantees to initiate beacon requests before the page is unloaded and to run them to completion.

 The main use case for the Beacon API is to send analytics such as client-side events or session data to the server. Historically, websites have used [`XMLHttpRequest`](xmlhttprequest) for this, but browsers do not guarantee to send these asynchronous requests in some circumstances (for example, if the page is about to be unloaded). To combat this, websites have resorted to various techniques, such as making the request synchronous, that have a bad effect on responsiveness. Because beacon requests are both asynchronous and guaranteed to be sent, they combine good performance characteristics and reliability.

 For more details about the motivation for and usage of this API, see the documentation for the [`navigator.sendBeacon()`](navigator/sendbeacon) method.

  **Note:** This API is *not available* in [Web Workers](web_workers_api) (not exposed via [`WorkerNavigator`](workernavigator)).

 

Interfaces
----------



This API defines a single method: [`navigator.sendBeacon()`](navigator/sendbeacon).

 The method takes two arguments, the URL and the data to send in the request. The data argument is optional and its type may be a [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), a [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView), a [`Blob`](blob), a string literal or object, or a [`FormData`](formdata) object. If the browser successfully queues the request for delivery, the method returns "`true`"; otherwise, it returns "`false`".



Specifications
--------------




| Specification |
| --- |
| [Beacon # sendbeacon-method](https://w3c.github.io/beacon/#sendbeacon-method) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Beacon_API` | 39Starting in Chrome 59, this method cannot send a `Blob` whose type is not CORS safelisted. This is a temporary change until a mitigation can be found for the security issues that this creates. For more information see [Chrome bug 720283](https://crbug.com/720283). | 14 | 31 | No | 26Starting in Opera 46, this method cannot send a `Blob` whose type is not CORS safelisted. This is a temporary change until a mitigation can be found for the security issues that this creates. For more information see [Chrome bug 720283](https://crbug.com/720283). | 11.1 | 40Starting in Chrome 59, this method cannot send a `Blob` whose type is not CORS safelisted. This is a temporary change until a mitigation can be found for the security issues that this creates. For more information see [Chrome bug 720283](https://crbug.com/720283). | 42Starting in Chrome 59, this method cannot send a `Blob` whose type is not CORS safelisted. This is a temporary change until a mitigation can be found for the security issues that this creates. For more information see [Chrome bug 720283](https://crbug.com/720283). | 31 | 26Starting in Opera 46, this method cannot send a `Blob` whose type is not CORS safelisted. This is a temporary change until a mitigation can be found for the security issues that this creates. For more information see [Chrome bug 720283](https://crbug.com/720283). | 11.3 | 4.0Starting in Samsung Internet 7.0, this method cannot send a `Blob` whose type is not CORS safelisted. This is a temporary change until a mitigation can be found for the security issues that this creates. For more information see [Chrome bug 720283](https://crbug.com/720283). |


See also
--------


* [Beacon standard](https://w3c.github.io/beacon/)
* [Beacon CanIUse data](https://caniuse.com/#search=beacon)
* [Intercepting beacons through service workers](https://ehsanakhgari.org/blog/2015-04-08/intercepting-beacons-through-service-workers/); Ehsan Akhgari; 2015-Apr-08
* <https://webkit.org/blog/8821/link-click-analytics-and-privacy/>
* [Beaconing in Practice](https://calendar.perfplanet.com/2020/beaconing-in-practice/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API>

Web Bluetooth API
=================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The Web Bluetooth API provides the ability to connect and interact with Bluetooth Low Energy peripherals.

  **Note:** This API is *not available* in [Web Workers](web_workers_api) (not exposed via [`WorkerNavigator`](workernavigator)).

 

Interfaces
----------


 [`Bluetooth`](bluetooth)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) to a [`BluetoothDevice`](bluetoothdevice) object with the specified options.

  [`BluetoothCharacteristicProperties`](bluetoothcharacteristicproperties)  Provides properties of a particular `BluetoothRemoteGATTCharacteristic`.

  [`BluetoothDevice`](bluetoothdevice)  Represents a Bluetooth device inside a particular script execution environment.

  [`BluetoothRemoteGATTCharacteristic`](bluetoothremotegattcharacteristic)  Represents a GATT Characteristic, which is a basic data element that provides further information about a peripheral's service.

  [`BluetoothRemoteGATTDescriptor`](bluetoothremotegattdescriptor)  Represents a GATT Descriptor, which provides further information about a characteristic's value.

  [`BluetoothRemoteGATTServer`](bluetoothremotegattserver)  Represents a GATT Server on a remote device.

  [`BluetoothRemoteGATTService`](bluetoothremotegattservice)  Represents a service provided by a GATT server, including a device, a list of referenced services, and a list of the characteristics of this service.

  
Specifications
--------------




| Specification |
| --- |
| [Web Bluetooth # bluetooth](https://webbluetoothcg.github.io/web-bluetooth/#bluetooth) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Web_Bluetooth_API` | 56Before Chrome 70, this feature was only supported in macOS. In Chrome 70, support was added for Windows 10. Linux support is not enabled by default.56In Linux and versions of Windows earlier than 10, this flag must be enabled. | 79Supported by default only on macOS and Windows 10. Linux support is not enabled by default.79In Linux and versions of Windows earlier than 10, this flag must be enabled. | No | No | 43Before Opera 57, this feature was only supported in macOS. In Opera 57, support was added for Windows 10. Linux support is not enabled by default.43In Linux and versions of Windows earlier than 10, this flag must be enabled. | No | NoSee [bug 1100993](https://crbug.com/1100993). | 56 | No | 43 | No | 6.0 |
| `availabilitychanged_event` | 56 | 79 | No | No | 43 | No | No | No | No | No | No | No |
| `getAvailability` | 78 | 79 | No | No | 65 | No | No | 78 | No | 56 | No | 12.0 |
| `getDevices` | 85 | 85 | No | No | 71 | No | No | 85 | No | No | No | No |
| `requestDevice` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Web_Bluetooth_API>

Broadcast Channel API
=====================



The **Broadcast Channel API** allows basic communication between [browsing contexts](https://developer.mozilla.org/en-US/docs/Glossary/Browsing_context) (that is, *windows*, *tabs*, *frames*, or *iframes*) and workers on the same [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin).


 **Note:** This feature is available in [Web Workers](web_workers_api)

  By creating a [`BroadcastChannel`](broadcastchannel) object, you can receive any messages that are posted to it. You don't have to maintain a reference to the frames or workers you wish to communicate with: they can "subscribe" to a particular channel by constructing their own [`BroadcastChannel`](broadcastchannel) with the same name, and have bi-directional communication between all of them.

  ![The principle of the Broadcast Channel API] 



Broadcast Channel interface
---------------------------


### Creating or joining a channel



A client joins a broadcast channel by creating a [`BroadcastChannel`](broadcastchannel) object. Its [constructor](broadcastchannel/broadcastchannel) takes one single parameter: the *name* of the channel. If it is the first to connect to that broadcast channel name, the underlying channel is created.

 
```
// Connection to a broadcast channel
const bc = new BroadcastChannel("test\_channel");

```


### Sending a message



It is enough to call the [`postMessage()`](broadcastchannel/postmessage) method on the created `BroadcastChannel` object, which takes any object as an argument. An example string message:

 
```
// Example of sending of a very simple message
bc.postMessage("This is a test message.");

```
 Data sent to the channel is serialized using the [structured clone algorithm](web_workers_api/structured_clone_algorithm). That means you can send a broad variety of data objects safely without having to serialize them yourself.

 The API doesn't associate any semantics to messages, so it is up to the code to know what kind of messages to expect and what to do with them.



### Receiving a message



When a message is posted, a [`message`](broadcastchannel/message_event) event is dispatched to each [`BroadcastChannel`](broadcastchannel) object connected to this channel. A function can be run for this event using the [`onmessage`](broadcastchannel/message_event) event handler:

 
```
// A handler that only logs the event to the console:
bc.onmessage = (event) => {
  console.log(event);
};

```


### Disconnecting a channel



To leave a channel, call the [`close()`](broadcastchannel/close) method on the object. This disconnects the object from the underlying channel, allowing garbage collection.

 
```
// Disconnect the channel
bc.close();

```


Conclusion
----------



The Broadcast Channel API's self-contained interface allows cross-context communication. It can be used to detect user actions in other tabs within a same origin, like when the user logs in or out.

 The messaging protocol is not defined and the different browsing contexts need to implement it themselves; there is no negotiation nor requirement from the specification.



Specifications
--------------




| Specification |
| --- |
| [HTML Standard # broadcasting-to-other-browsing-contexts](https://html.spec.whatwg.org/multipage/web-messaging.html#broadcasting-to-other-browsing-contexts) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `BroadcastChannel` | 54 | 79 | 38 | No | 41 | 15.4 | 54 | 54 | 38 | 41 | 15.4 | 6.0 |
| `Broadcast_Channel_API` | 54 | 79 | 38 | No | 41 | 15.4 | 54 | 54 | 38 | 41 | 15.4 | 6.0 |
| `close` | 54 | 79 | 38 | No | 41 | 15.4 | 54 | 54 | 38 | 41 | 15.4 | 6.0 |
| `message_event` | 54 | 79 | 38 | No | 41 | 15.4 | 54 | 54 | 38 | 41 | 15.4 | 6.0 |
| `messageerror_event` | 60 | 79 | 57 | No | 47 | 15.4 | 60 | 60 | 57 | 47 | 15.4 | 8.0 |
| `name` | 54 | 79 | 38 | No | 41 | 15.4 | 54 | 54 | 38 | 41 | 15.4 | 6.0 |
| `postMessage` | 54 | 79 | 38 | No | 41 | 15.4 | 54 | 54 | 38 | 41 | 15.4 | 6.0 |


See also
--------


* [`BroadcastChannel`](broadcastchannel), the interface implementing it.


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API>

CSS Counter Styles
==================


The CSS Counter Styles module allows to define custom counter styles, which can be used for CSS list-marker and generated-content counters.


Interfaces
----------


 [`CSSCounterStyleRule`](csscounterstylerule)  Represents an [`@counter-style`](https://developer.mozilla.org/en-US/docs/Web/CSS/@counter-style) rule.

  
Specifications
--------------




| Specification |
| --- |
| [CSS Counter Styles Level 3 # the-csscounterstylerule-interface](https://w3c.github.io/csswg-drafts/css-counter-styles/#the-csscounterstylerule-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSS_Counter_Styles` | 91 | 91 | 33 | No | 77 | NoSee [bug 167645](https://webkit.org/b/167645). | 91 | 91 | 33 | 64 | NoSee [bug 167645](https://webkit.org/b/167645). | 16.0 |
| `additiveSymbols` | 91 | 91 | 33 | No | 77 | No | 91 | 91 | 33 | 64 | No | 16.0 |
| `fallback` | 91 | 91 | 33 | No | 77 | No | 91 | 91 | 33 | 64 | No | 16.0 |
| `name` | 91 | 91 | 33 | No | 77 | No | 91 | 91 | 33 | 64 | No | 16.0 |
| `negative` | 91 | 91 | 33 | No | 77 | No | 91 | 91 | 33 | 64 | No | 16.0 |
| `pad` | 91 | 91 | 33 | No | 77 | No | 91 | 91 | 33 | 64 | No | 16.0 |
| `prefix` | 91 | 91 | 33 | No | 77 | No | 91 | 91 | 33 | 64 | No | 16.0 |
| `range` | 91 | 91 | 33 | No | 77 | No | 91 | 91 | 33 | 64 | No | 16.0 |
| `speakAs` | 91 | 91 | 33 | No | 77 | No | 91 | 91 | 33 | 64 | No | 16.0 |
| `suffix` | 91 | 91 | 33 | No | 77 | No | 91 | 91 | 33 | 64 | No | 16.0 |
| `symbols` | 91 | 91 | 33 | No | 77 | No | 91 | 91 | 33 | 64 | No | 16.0 |
| `system` | 91 | 91 | 33 | No | 77 | No | 91 | 91 | 33 | 64 | No | 16.0 |


See also
--------


* [Using CSS counters](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Counter_Styles/Using_CSS_counters)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSS_Counter_Styles>

CSS Custom Highlight API
========================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The CSS Custom Highlight API provides a mechanism for styling arbitrary text ranges on a document by using JavaScript to create the ranges, and CSS to style them.



Concepts and usage
------------------



Styling text ranges on a webpage can be very useful. For example, text editing web apps highlight spelling or grammar errors, and code editors highlight syntax errors.

 The CSS Custom Highlight API extends the concept of other highlight pseudo-elements such as [`::selection`](https://developer.mozilla.org/en-US/docs/Web/CSS/::selection), [`::spelling-error`](https://developer.mozilla.org/en-US/docs/Web/CSS/::spelling-error), [`::grammar-error`](https://developer.mozilla.org/en-US/docs/Web/CSS/::grammar-error), and [`::target-text`](https://developer.mozilla.org/en-US/docs/Web/CSS/::target-text) by providing a way to create and style arbitrary [`Range`](range) objects, rather than being limited to browser-defined ranges.

 Using the CSS Custom Highlight API, you can programmatically create text ranges and highlight them without affecting the DOM structure in the page.

 There are four steps to style text ranges on a webpage using the CSS Custom Highlight API:

 1. Creating [`Range`](range) objects.
2. Creating [`Highlight`](highlight) objects for these ranges.
3. Registering the highlights using the [`HighlightRegistry`](highlightregistry).
4. Styling the highlights using the [`::highlight()`](https://developer.mozilla.org/en-US/docs/Web/CSS/::highlight) pseudo-element.



### Create ranges



The first step is to define the text ranges that you want to style by creating [`Range`](range) objects in JavaScript. For example:

 
```
const parentNode = document.getElementById("foo");

const range1 = new Range();
range1.setStart(parentNode, 10);
range1.setEnd(parentNode, 20);

const range2 = new Range();
range2.setStart(parentNode, 40);
range2.setEnd(parentNode, 60);

```


### Create highlights



The second step is to instantiate [`Highlight`](highlight) objects for your text ranges.

 Multiple ranges can be associated to one highlight. If you want to highlight multiple pieces of text the same way, you need to create a single highlight and initialize it with the corresponding ranges.

 
```
const highlight = new Highlight(range1, range2);

```
 But you can also create as many highlights as you need. For example, if you are building a collaborative text editor where each user gets a different text color, then you can create one highlight per user, as seen in the code snippet below:

 
```
const user1Highlight = new Highlight(user1Range1, user1Range2);
const user2Highlight = new Highlight(user2Range1, user2Range2, user2Range3);

```
 Each highlight can be styled differently.



### Register highlights



Once highlights have been created, register them by using the [`HighlightRegistry`](highlightregistry) available as [`CSS.highlights`](css/highlights).

 The registry is a [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)-like object used to register highlights by names, as seen below:

 
```
CSS.highlights.set("user-1-highlight", user1Highlight);
CSS.highlights.set("user-2-highlight", user2Highlight);

```
 In the above code snippet, the `user-1-highlight` and `user-2-highlight` strings are custom identifiers that can be used in CSS to apply styles to the registered highlights.

 You can register as many highlights as you need in the registry, as well as remove highlights and clear the entire registry.

 
```
// Remove a single highlight from the registry.
CSS.highlights.delete("user-1-highlight");

// Clear the registry.
CSS.highlights.clear();

```


### Style highlights



The final step is to style the registered highlights. This is done by using the [`::highlight()`](https://developer.mozilla.org/en-US/docs/Web/CSS/::highlight) pseudo-element. For example, to style the `user-1-highlight` highlight registered in the previous step:

 
```
::highlight(user-1-highlight) {
  background-color: yellow;
  color: black;
}

```


Interfaces
----------


 
[`Highlight`](highlight)  Experimental 
  This interface is used to represent a collection of ranges to be styled on a document.

  [`HighlightRegistry`](highlightregistry)  Accessible via [`CSS.highlights`](css/highlights), this [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)-like object is used to register highlights with custom identifiers.

  
Examples
--------


### Highlighting search results



This example shows how to use the CSS Custom Highlight API to highlight search results.

 #### HTML

 The HTML code snippet below defines a search field and an article with a few paragraphs of text:

 
```
<label>Search within text <input id="query" type="text" /></label>
<article>
  <p>
    Maxime debitis hic, delectus perspiciatis laborum molestiae labore,
    deleniti, quam consequatur iure veniam alias voluptas nisi quo. Dolorem
    eaque alias, quo vel quas repudiandae architecto deserunt quidem, sapiente
    laudantium nulla.
  </p>
  <p>
    Maiores odit molestias, necessitatibus doloremque dolor illum reprehenderit
    provident nostrum laboriosam iste, tempore perferendis! Ab porro neque esse
    voluptas libero necessitatibus fugiat, ex, minus atque deserunt veniam
    molestiae tempora? Vitae.
  </p>
  <p>
    Dolorum facilis voluptate eaque eius similique ducimus dignissimos assumenda
    quos architecto. Doloremque deleniti non exercitationem rerum quam alias
    harum, nisi obcaecati corporis temporibus vero sapiente voluptatum est
    quibusdam id ipsa.
  </p>
</article>

```
 #### JavaScript

 JavaScript is used to listen to the `input` event on the search field. When the event is fired, the code locates matches for the input text in the article text. It then creates ranges for the matches, and uses the CSS Custom Highlight API to create and register a `search-results` highlight object:

 
```
const query = document.getElementById("query");
const article = document.querySelector("article");

// Find all text nodes in the article. We'll search within
// these text nodes.
const treeWalker = document.createTreeWalker(article, NodeFilter.SHOW\_TEXT);
const allTextNodes = [];
let currentNode = treeWalker.nextNode();
while (currentNode) {
  allTextNodes.push(currentNode);
  currentNode = treeWalker.nextNode();
}

// Listen to the input event to run the search.
query.addEventListener("input", () => {
  // If the CSS Custom Highlight API is not supported,
  // display a message and bail-out.
  if (!CSS.highlights) {
    article.textContent = "CSS Custom Highlight API not supported.";
    return;
  }

  // Clear the HighlightRegistry to remove the
  // previous search results.
  CSS.highlights.clear();

  // Clean-up the search query and bail-out if
  // if it's empty.
  const str = query.value.trim().toLowerCase();
  if (!str) {
    return;
  }

  // Iterate over all text nodes and find matches.
  const ranges = allTextNodes
    .map((el) => {
      return { el, text: el.textContent.toLowerCase() };
    })
    .map(({ text, el }) => {
      const indices = [];
      let startPos = 0;
      while (startPos < text.length) {
        const index = text.indexOf(str, startPos);
        if (index === -1) break;
        indices.push(index);
        startPos = index + str.length;
      }

      // Create a range object for each instance of
      // str we found in the text node.
      return indices.map((index) => {
        const range = new Range();
        range.setStart(el, index);
        range.setEnd(el, index + str.length);
        return range;
      });
    });

  // Create a Highlight object for the ranges.
  const searchResultsHighlight = new Highlight(...ranges.flat());

  // Register the Highlight object in the registry.
  CSS.highlights.set("search-results", searchResultsHighlight);
});

```
 #### CSS

 Finally, the `::highlight()` pseudo-element is used in CSS to style the highlights:

 
```
::highlight(search-results) {
  background-color: #f06;
  color: white;
}

```
 #### Result

 The result is shown below. Type text within the search field to highlight matches in the article:




Specifications
--------------




| Specification |
| --- |
| [CSS Custom Highlight API Module Level 1](https://w3c.github.io/csswg-drafts/css-highlight-api-1/)  |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSS_Custom_Highlight_API` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@iterator` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `CSS_Custom_Highlight_API` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `clear` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `delete` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `entries` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `forEach` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `get` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `has` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `keys` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `set` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `size` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `values` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@iterator` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `Highlight` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `CSS_Custom_Highlight_API` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `add` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `clear` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `delete` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `entries` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `forEach` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `has` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `keys` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `priority` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `size` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `type` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `values` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |


### api.Highlight


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.HighlightRegistry


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### css.selectors.highlight


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


See also
--------


* [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSS_Custom_Highlight_API>

CSS Font Loading API
====================



The CSS Font Loading API provides events and interfaces for dynamically loading font resources.

  **Note:** This feature is available in [Web Workers](web_workers_api) (`self.fonts` provides access to [`FontFaceSet`](fontfaceset)).

 

Concepts and usage
------------------



 CSS stylesheets allow authors to use custom fonts; specifying fonts to download using the [`@font-face`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face) rule, and applying them to elements with the [`font-family`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-family) property. The point at which a font is downloaded is controlled by the user agent. Most agents only fetch and load fonts when they are first needed, which can result in a perceptible delay. 

  The CSS Font Loading API overcomes this problem by letting authors control and track when a font face is fetched and loaded, and when it is added to the font face set owned by the document or worker. Adding a font face to the document or worker font face set allows the user agent to fetch and load the associated font resource automatically if needed. A font face can be loaded either before or after it is added to a font face set, but it *must* be added to the set before it can be used for drawing. 

  Font faces are defined in [`FontFace`](fontface) objects, which specify a binary or URL font source and other properties of font in much the same way as the CSS [`@font-face`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face) rule. `FontFace` objects are added to the document or worker [`FontFaceSet`](fontfaceset) using [`Document.fonts`](document/fonts) and [`WorkerGlobalScope.fonts`](workerglobalscope/fonts), respectively. Authors can trigger download of fonts using either `FontFace` or `FontFaceSet`, and monitor loading completion. `FontFaceSet` can additionally be used to determine when all fonts required by a page have loaded and the document layout is complete. 

  The [`FontFace.status`](fontface/status) property indicates the font face loading status: `unloaded`, `loading`, `loaded` or `failed`. This status is initially `unloaded`. It is set to `loading` when the file is being downloaded or the font data is being processed, and to `failed` if the font definition is invalid or the font data cannot be loaded. The status is set to `loaded` when the font face data has been successfully fetched (if needed) and loaded. 



### Defining a font face



 Font faces are created using the [`FontFace` constructor](fontface/fontface), which takes as parameters: the font family, the font source, and optional descriptors. The format and grammar of these arguments is the same as the equivalent [`@font-face`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face) definition. 

  The font source can either be binary data in an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or a font resource at an URL. A typical font face definition using a URL source might be as shown below. Note that the `url()` function is required for URL font sources. 

 
```
const font = new FontFace("myfont", "url(myfont.woff)", {
  style: "italic",
  weight: "400",
  stretch: "condensed",
});

```
   **Note:** As with `@font-face`, some descriptors represent the expected data in the font data and are used for font matching, while others actually set/define properties of the generated font face. For example, setting the `style` to "italic" indicates that the file contains italic fonts; it is up to the author to specify a file for which this is true. 

   Font faces with a *binary source* are automatically loaded if the font definition is valid and the font data can be loaded — [`FontFace.status`](fontface/status) is set to `loaded` on success and `failed` otherwise. Font faces with a URL source are validated but not automatically loaded — [`FontFace.status`](fontface/status) is set `unloaded` if the font face definition is valid and `failed` otherwise. 



### Adding a font to a document or worker



Font faces are usually added to the document or worker [`FontFaceSet`](fontfaceset) to allow the user agent to automatically load the font when needed, and *must* be added in order for the font to be used for rendering text.

 The code below shows a font face being added to the document.

 
```
// Define a FontFace
const font = new FontFace("myfont", "url(myfont.woff)", {
  style: "italic",
  weight: "400",
  stretch: "condensed",
});

// Add to the document.fonts (FontFaceSet)
document.fonts.add(font);

```


### Loading a font



 A font face can be loaded manually by calling [`FontFace.load()`](fontface/load), or by calling [`FontFaceSet.load()`](fontfaceset/load) if the font face has been added to the `FontFaceSet`. Note that attempting to load an already-loaded font has no effect. 

 The code below shows how to define a font face, add it to the document fonts, and then initiate a font load.

 
```
// Define a FontFace
const font = new FontFace("myfont", "url(myfont.woff)");

// Add to the document.fonts (FontFaceSet)
document.fonts.add(font);

// Load the font
font.load();

// Wait until the fonts are all loaded
document.fonts.ready.then(() => {
  // Use the font to render text (for example, in a canvas)
});

```
  Note that the `font.load()` returns a promise, so we could have handled the completion of font loading by chaining `then` afterwards. Using [`document.fonts.ready`](fontfaceset/ready) can be better in some circumstances, as it is only called when all fonts in the document have been resolved and layout is complete. 



Interfaces
----------


 [`FontFace`](fontface)  Represents a single usable font face.

  [`FontFaceSet`](fontfaceset)  An interface loading font faces and checking their download statuses.

  [`FontFaceSetLoadEvent`](fontfacesetloadevent)  Fired whenever a [`FontFaceSet`](fontfaceset) loads.

  
Examples
--------


### Basic font loading



 This is a very simple example that shows a font being loaded from Google Fonts and used to draw text to a canvas. The example also logs the `status` immediately after creation and after loading. 

 #### HTML

 This code defines a canvas for drawing to and a textarea for logging.

 
```
<canvas id="js-canvas"></canvas>
<textarea id="log" rows="3" cols="100"></textarea>

```
 #### JavaScript

 First we get the element to which we will log, and the canvas that will be used to render text in the downloaded font.

 
```
const log = document.getElementById("log");

const canvas = document.getElementById("js-canvas");
canvas.width = 650;
canvas.height = 75;

```
  Next we define a `FontFace` that has a URL source that is a Google Font and add it to `document.fonts`. We then log the font status, which should be `unloaded`. 

 
```
const bitterFontFace = new FontFace(
  "FontFamily Bitter",
  "url(https://fonts.gstatic.com/s/bitter/v7/HEpP8tJXlWaYHimsnXgfCOvvDin1pK8aKteLpeZ5c0A.woff2)"
);
document.fonts.add(bitterFontFace);
log.textContent += `Bitter font: ${bitterFontFace.status}\n`; // > Bitter font: unloaded

```
  Then we call the [`FontFace.load()`](fontface/load) method to load the font face, and wait on the returned promise. Once the promise resolves we log the loaded status (which should be `loaded`) and draw text in the loaded font to the canvas. 

 
```
bitterFontFace.load().then(
  () => {
    log.textContent += `Bitter font: ${bitterFontFace.status}\n`; // > Bitter font: loaded

    const ctx = canvas.getContext("2d");
    ctx.font = '36px "FontFamily Bitter"';
    ctx.fillText("Bitter font loaded", 20, 50);
  },
  (err) => {
    console.error(err);
  }
);

```
 Note that we could also have waited on the promise returned by the [`FontFace.loaded`](fontface/loaded) property, or on [`FontFaceSet.ready`](fontfaceset/ready).

 #### Result

  The result is shown below. It should show the name of the font drawn on the canvas in the downloaded font, and a log showing the load status before and after loading. 




### Font loading with events



 This example is similar to the previous one, except that it uses [`FontFaceSet.load()`](fontfaceset/load) to load the font. It also demonstrates how to listen for font loading events. 

 #### HTML

 
```
<canvas id="js-canvas"></canvas>
<textarea id="log" rows="25" cols="100"></textarea>

```
 #### JavaScript

 The code below defines a canvas context for drawing text, defines a font face, and adds it to the document font face set.

 
```
const log = document.getElementById("log");

const canvas = document.getElementById("js-canvas");
canvas.width = 650;
canvas.height = 75;
const ctx = canvas.getContext("2d");

const oxygenFontFace = new FontFace(
  "FontFamily Oxygen",
  "url(https://fonts.gstatic.com/s/oxygen/v5/qBSyz106i5ud7wkBU-FrPevvDin1pK8aKteLpeZ5c0A.woff2)"
);
document.fonts.add(oxygenFontFace);
log.textContent += `Oxygen status: ${oxygenFontFace.status}\n`;

```
  Next we use `load()` on the font face set to load the font, specifying which of the fonts to load. The method returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). If the promise is resolved we use the font to draw some text. If it is rejected the error is logged. 

 
```
document.fonts.load("36px FontFamily Oxygen").then(
  (fonts) => {
    log.textContent += `Bitter font: ${fonts}\n`; // > Oxygen font: loaded
    log.textContent += `Bitter font: ${oxygenFontFace.status}\n`; // > Oxygen font: loaded
    ctx.font = '36px "FontFamily Oxygen"';
    ctx.fillText("Oxygen font loaded", 20, 50);
  },
  (err) => {
    console.error(err);
  }
);

```
  Instead of waiting on a promise we might instead use events to track the font loading operation. The code below listens for the `loading` and `loadingerror` events and logs the number of font faces for each case. In the `loadingdone` event listener we additionally iterate through the font faces and log the family names. 

 
```
document.fonts.addEventListener("loading", (event) => {
  log.textContent += `loading\_event: ${event.fontfaces.length}\n`;
});
document.fonts.addEventListener("loadingerror", (event) => {
  log.textContent += `loadingerror\_event: ${event.fontfaces.length}\n`;
});
document.fonts.addEventListener("loadingdone", (event) => {
  log.textContent += `loadingdone\_event: ${event.fontfaces.length}\n`;
  event.fontfaces.forEach((value) => {
    log.textContent += ` fontface: ${value.family}\n`;
  });
});

```
  The last bit of code demonstrates how you can monitor the completion of font loading using the promise returned by [`FontFaceSet.ready`](fontfaceset/ready). Unlike the other mechanisms this returns when all fonts defined in the document have been downloaded and layout is complete. 

 When the promise resolves we iterate the values in the document's font faces.

 
```
document.fonts.ready.then(function () {
  log.textContent += `\nFontFaces in document: ${document.fonts.size}.\n`;

  for (const fontFace of document.fonts.values()) {
    log.textContent += "FontFace:\n";
    for (const property in fontFace) {
      log.textContent += `${property}: ${fontFace[property]}\n`;
    }
  }
});

```
 #### Result

  The output below shows the text drawn in "Oxygen" font. This also shows logging from the events and when the promise returned by `document.fonts.ready` resolves. 




Specifications
--------------




| Specification |
| --- |
| [CSS Font Loading Module Level 3 # fontface-interface](https://w3c.github.io/csswg-drafts/css-font-loading/#fontface-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FontFace` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 4.0 |
| `CSS_Font_Loading_API` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 4.0 |
| `ascentOverride` | 87 | 87 | 89 | No | 73 | No | 87 | 87 | 89 | 62 | No | 14.0 |
| `descentOverride` | 87 | 87 | 89 | No | 73 | No | 87 | 87 | 89 | 62 | No | 14.0 |
| `display` | 60 | 79 | 58 | No | 47 | 11.1 | 60 | 60 | 58 | 44 | 11.3 | 8.0 |
| `family` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 4.0 |
| `featureSettings` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 4.0 |
| `lineGapOverride` | 87 | 87 | 89 | No | 73 | No | 87 | 87 | 89 | 62 | No | 14.0 |
| `load` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 4.0 |
| `loaded` | 37 | 79 | 41 | No | 24 | 10 | 37 | 37 | 41 | 24 | 10 | 4.0 |
| `status` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 4.0 |
| `stretch` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 4.0 |
| `style` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 4.0 |
| `unicodeRange` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 4.0 |
| `variant` | 35 | 79 | 41 | No | 22 | 10–13.1 | 37 | 35 | 41 | 22 | 10–13.4 | 4.0 |
| `variationSettings` | No | No | 62 | No | No | No | No | No | 62 | No | No | No |
| `weight` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 4.0 |
| `worker_support` | 69 | 79 | 105 | No | 56 | No | 69 | 69 | 105 | 48 | No | 10.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSS_Font_Loading_API>

CSS Painting API
================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The CSS Painting API — part of the [CSS Houdini](https://developer.mozilla.org/en-US/docs/Web/Guide/Houdini) umbrella of APIs — allows developers to write JavaScript functions that can draw directly into an element's background, border, or content.



Concepts and usage
------------------



Essentially, the CSS Painting API contains functionality allowing developers to create custom values for [`paint()`](https://developer.mozilla.org/en-US/docs/Web/CSS/image/paint), a CSS [`<image>`](https://developer.mozilla.org/en-US/docs/Web/CSS/image) function. You can then apply these values to properties like [`background-image`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-image) to set complex custom backgrounds on an element.

 For example:

 
```
aside {
  background-image: paint(myPaintedImage);
}

```
 The API defines a [`worklet`](worklet) that can be used to programmatically generate an image that responds to computed style changes. To find out more about how this is used, consult [Using the CSS Painting API](css_painting_api/guide).



Interfaces
----------


 [`PaintWorkletGlobalScope`](paintworkletglobalscope)  The global execution context of the paint worklet.

  `PaintRenderingContext2D`  Implements a subset of the [`CanvasRenderingContext2D`](canvasrenderingcontext2d) API. It has an output bitmap that is the size of the object it is rendering to.

  `PaintSize`  Returns the read-only values of the output bitmap's width and height.

  
Examples
--------



The following example creates a list of items with a background image that rotates between three different colors and three widths. In a supporting browser you will see something like the image below.

  ![The width and color of the background image changes based on the custom properties] 

 To achieve this we'll define two custom CSS properties, `--boxColor` and `--widthSubtractor`.



### The paint worklet



In our worklet, we can reference these custom properties.

 
```
registerPaint(
  "boxbg",
  class {
    static get contextOptions() {
      return { alpha: true };
    }

    /\*
 use this function to retrieve any custom properties (or regular properties, such as 'height')
 defined for the element, return them in the specified array
 \*/
    static get inputProperties() {
      return ["--boxColor", "--widthSubtractor"];
    }

    paint(ctx, size, props) {
      /\*
 ctx -> drawing context
 size -> paintSize: width and height
 props -> properties: get() method
 \*/

      ctx.fillStyle = props.get("--boxColor");
      ctx.fillRect(
        0,
        size.height / 3,
        size.width \* 0.4 - props.get("--widthSubtractor"),
        size.height \* 0.6
      );
    }
  }
);

```
 We used the `inputProperties()` method in the `registerPaint()` class to get the values of two custom properties set on an element that has `boxbg` applied to it and then used those within our `paint()` function. The `inputProperties()` method can return all properties affecting the element, not just custom properties.



### Using the paint worklet



#### HTML

 
```
<ul>
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
  <li>item 4</li>
  <li>item 5</li>
  <li>item 6</li>
  <li>item 7</li>
  <li>item 8</li>
  <li>item 9</li>
  <li>item 10</li>
  <li>item 11</li>
  <li>item 12</li>
  <li>item 13</li>
  <li>item 14</li>
  <li>item 15</li>
  <li>item 16</li>
  <li>item 17</li>
  <li>item</li>
</ul>

```
 #### CSS

 In our CSS, we define the `--boxColor` and `--widthSubtractor` custom properties.

 
```
li {
  background-image: paint(boxbg);
  --boxColor: hsl(55 90% 60% / 1);
}

li:nth-of-type(3n) {
  --boxColor: hsl(155 90% 60% / 1);
  --widthSubtractor: 20;
}

li:nth-of-type(3n + 1) {
  --boxColor: hsl(255 90% 60% / 1);
  --widthSubtractor: 40;
}

```
 #### JavaScript

 In our `<script>` we register the worklet:

 
```
CSS.paintWorklet.addModule("boxbg.js");

```
 #### Result

 While you can't play with the worklet's script, you can alter the custom property values in DevTools to change the colors and width of the background image.




Specifications
--------------




| Specification |
| --- |
| [CSS Painting API Level 1 # paintworkletglobalscope](https://drafts.css-houdini.org/css-paint-api/#paintworkletglobalscope) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSS_Painting_API` | 65 | 79 | No | No | 52 | No | 65 | 65 | No | 47 | No | 9.0 |
| `devicePixelRatio` | 65 | 79 | No | No | 52 | No | 65 | 65 | No | 47 | No | 9.0 |
| `registerPaint` | 65 | 79 | No | No | 52 | No | 65 | 65 | No | 47 | No | 9.0 |


See also
--------


* [Using the CSS Painting API](css_painting_api/guide)
* [CSS Typed Object Model API](css_typed_om_api)
* [CSS Houdini](https://developer.mozilla.org/en-US/docs/Web/Guide/Houdini)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSS_Painting_API>

CSS Properties and Values API
=============================


The **CSS Properties and Values API** — part of the [CSS Houdini](https://developer.mozilla.org/en-US/docs/Web/Guide/Houdini) umbrella of APIs — allows developers to explicitly define their [`CSS custom properties`](https://developer.mozilla.org/en-US/docs/Web/CSS/--*), allowing for property type checking, default values, and properties that do or do not inherit their value.


Interfaces
----------


 [`CSS.registerProperty`](css/registerproperty)  Defines how a browser should parse a [`CSS custom properties`](https://developer.mozilla.org/en-US/docs/Web/CSS/--*). Access this interface through [`CSS.registerProperty`](css/registerproperty) in [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript).

  [`@property`](https://developer.mozilla.org/en-US/docs/Web/CSS/@property)  Defines how a browser should parse a [`CSS custom properties`](https://developer.mozilla.org/en-US/docs/Web/CSS/--*). Access this interface through [`@property`](https://developer.mozilla.org/en-US/docs/Web/CSS/@property) [at-rule](https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule) in [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS).

  
Examples
--------



The following uses [`CSS.registerProperty`](css/registerproperty) in [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript) to type a [`CSS custom properties`](https://developer.mozilla.org/en-US/docs/Web/CSS/--*), `--my-color`, as a color, give it a default value, and not allow it to inherit its value:

 
```
window.CSS.registerProperty({
  name: "--my-color",
  syntax: "<color>",
  inherits: false,
  initialValue: "#c0ffee",
});

```
 The same registration can take place in [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) using the [`@property`](https://developer.mozilla.org/en-US/docs/Web/CSS/@property) [at-rule](https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule):

 
```
@property --my-color {
  syntax: "<color>";
  inherits: false;
  initial-value: #c0ffee;
}

```


Specifications
--------------




| Specification |
| --- |
| [CSS Properties and Values API Level 1 # the-registerproperty-function](https://drafts.css-houdini.org/css-properties-values-api/#the-registerproperty-function) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSS_Properties_and_Values_API` | 78 | 79 | No | No | 65 | 16.4 | 78 | 78 | No | 56 | 16.4 | 12.0 |


See also
--------


* [Using the CSS properties and values API](css_properties_and_values_api/guide)
* [CSS Painting API](css_painting_api)
* [CSS Typed Object Model](css_typed_om_api)
* [CSS Houdini](https://developer.mozilla.org/en-US/docs/Web/Guide/Houdini)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSS_Properties_and_Values_API>

CSS Typed Object Model API
==========================



The CSS Typed Object Model API simplifies CSS property manipulation by exposing CSS values as typed JavaScript objects rather than strings. This not only simplifies CSS manipulation, but also lessens the negative impact on performance as compared to [`HTMLElement.style`](htmlelement/style).

 Generally, CSS values can be read and written in JavaScript as strings, which can be slow and cumbersome. CSS Typed Object Model API provides interfaces to interact with underlying values, by representing them with specialized JS objects that can be manipulated and understood more easily and more reliably than string parsing and concatenation. This is easier for authors (for example, numeric values are reflected with actual JS numbers, and have unit-aware mathematical operations defined for them). It is also generally faster, as values can be directly manipulated and then cheaply translated back into underlying values without having to both build and parse strings of CSS.

 CSS Typed OM both allows for the performant manipulation of values assigned to CSS properties while enabling maintainable code that is both more understandable and easier to write.



Interfaces
----------


### `CSSStyleValue`



The [`CSSStyleValue`](cssstylevalue) interface of the CSS Typed Object Model API is the base class of all CSS values accessible through the Typed OM API. An instance of this class may be used anywhere a string is expected.

  [`CSSStyleValue.parse(property, cssText)`](cssstylevalue/parse)  The parse() method of the CSSStyleValue interface allows a CSSNumericValue to be constructed from a CSS string. It sets a specific CSS property to the specified values and returns the first value as a CSSStyleValue object.

  [`CSSStyleValue.parseAll()`](cssstylevalue/parseall)  The parseAll() method of the CSSStyleValue interface sets all occurrences of a specific CSS property to the specified value and returns an array of CSSStyleValue objects, each containing one of the supplied values.

  

### `StylePropertyMap`



The [`StylePropertyMap`](stylepropertymap) interface of the CSS Typed Object Model API provides a representation of a CSS declaration block that is an alternative to CSSStyleDeclaration.

  [`StylePropertyMap.set()`](stylepropertymap/set)  Method of StylePropertyMap interface that changes the CSS declaration with the given property to the value given.

  [`StylePropertyMap.append()`](stylepropertymap/append)  Method that adds a new CSS declaration to the StylePropertyMap with the given property and value.

  [`StylePropertyMap.delete()`](stylepropertymap/delete)  Method that removes the CSS declaration with the given property from the StylePropertyMap.

  [`StylePropertyMap.clear()`](stylepropertymap/clear)  Method that removes all declarations in the StylePropertyMap.

  

### `CSSUnparsedValue`



The [`CSSUnparsedValue`](cssunparsedvalue) interface of the CSS Typed Object Model API represents property values that reference custom properties. It consists of a list of string fragments and variable references.

  
[`CSSUnparsedValue()`](cssunparsedvalue/cssunparsedvalue) constructor  Creates a new CSSUnparsedValue object which represents property values that reference custom properties.

  [`CSSUnparsedValue.entries()`](cssunparsedvalue/entries)  Method returning an array of a given object's own enumerable property [key, value] pairs in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

  [`CSSUnparsedValue.forEach()`](cssunparsedvalue/foreach)  Method executing a provided function once for each element of the CSSUnparsedValue.

  [`CSSUnparsedValue.keys()`](cssunparsedvalue/keys)  Method returning a new *array iterator* object that contains the keys for each index in the array.

  

### 
`CSSKeywordValue` Serialization



The [`CSSKeywordValue`](csskeywordvalue) interface of the CSS Typed Object Model API creates an object to represent CSS keywords and other identifiers.

  
[`CSSKeywordValue()`](csskeywordvalue/csskeywordvalue) constructor  Constructor creates a new [`CSSKeywordValue()`](csskeywordvalue/csskeywordvalue) object which represents CSS keywords and other identifiers.

  [`CSSKeywordValue.value()`](csskeywordvalue/value)  Property of the CSSKeywordValue interface returning or setting the value of the CSSKeywordValue.

  

CSSStyleValue Interfaces
------------------------



CSSStyleValue is the base class through which all CSS values are expressed. Subclasses include:

  
[`CSSImageValue`](cssimagevalue) objects  An interface representing values for properties that take an image, for example [`background-image`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-image), [`list-style-image`](https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-image), or [`border-image-source`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-image-source).

  [`CSSKeywordValue`](csskeywordvalue)  An interface which creates an object to represent CSS keywords and other identifiers. When used where a string is expected, it will return the value of CSSKeyword.value.

  [`CSSMathValue`](cssmathvalue)  A tree of subclasses representing numeric values that are more complicated than a single value and unit, including:

 * [`CSSMathInvert`](cssmathinvert) - represents a CSS [`calc()`](https://developer.mozilla.org/en-US/docs/Web/CSS/calc) value used as `calc(1 / <value>)`.
* [`CSSMathMax`](cssmathmax) - represents the CSS [`max()`](https://developer.mozilla.org/en-US/docs/Web/CSS/max) function.
* [`CSSMathMin`](cssmathmin) - represents the CSS [`min()`](https://developer.mozilla.org/en-US/docs/Web/CSS/min) function.
* [`CSSMathNegate`](cssmathnegate) - negates the value passed into it.
* [`CSSMathProduct`](cssmathproduct) - represents the result obtained by calling [`add()`](cssnumericvalue/add), [`sub()`](cssnumericvalue/sub), or [`toSum()`](cssnumericvalue/tosum) on [`CSSNumericValue`](cssnumericvalue).
* [`CSSMathSum`](cssmathsum) - represents the result obtained by calling [`add()`](cssnumericvalue/add), [`sub()`](cssnumericvalue/sub), or [`toSum()`](cssnumericvalue/tosum) on [`CSSNumericValue`](cssnumericvalue).

  [`CSSNumericValue`](cssnumericvalue)  An interface representing operations that all numeric values can perform, including:

 * [`CSSNumericValue.add`](cssnumericvalue/add) - Adds supplied numbers to the `CSSNumericValue`.
* [`CSSNumericValue.sub`](cssnumericvalue/sub) - Subtracts supplied numbers to the `CSSNumericValue`.
* [`CSSNumericValue.mul`](cssnumericvalue/mul) - Multiplies supplied numbers to the `CSSNumericValue`.
* [`CSSNumericValue.div`](cssnumericvalue/div) - Divides a supplied number by other numbers, throwing an error if 0.
* [`CSSNumericValue.min`](cssnumericvalue/min) - Returns the minimum value passed
* [`CSSNumericValue.max`](cssnumericvalue/max) - Returns the maximum value passed
* [`CSSNumericValue.equals`](cssnumericvalue/equals) - Returns true if all the values are the exact same type and value, in the same order. Otherwise, false
* [`CSSNumericValue.to`](cssnumericvalue/to) - Converts `value` into another one with the specified *unit.*
* [`CSSNumericValue.toSum`](cssnumericvalue/tosum)
* [`CSSNumericValue.type`](cssnumericvalue/type)
* [`CSSNumericValue.parse`](cssnumericvalue/parse) - Returns a number parsed from a CSS string

  [`CSSPositionValue`](csspositionvalue)  Represents values for properties that take a position, for example object-position.

  [`CSSTransformValue`](csstransformvalue)  An interface representing a list of [`transform`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform) list values. They "contain" one or more [`CSSTransformComponent`](csstransformcomponent)s, which represent individual `transform` function values.

  [`CSSUnitValue`](cssunitvalue)  An interface representing numeric values that can be represented as a single unit, or a named number and percentage.

  [`CSSUnparsedValue`](cssunparsedvalue)  Represents property values that reference [custom properties](https://developer.mozilla.org/en-US/docs/Web/CSS/--*). It consists of a list of string fragments and variable references.

  

Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # stylevalue-objects](https://drafts.css-houdini.org/css-typed-om/#stylevalue-objects) |
| [CSS Typed OM Level 1 # the-stylepropertymap](https://drafts.css-houdini.org/css-typed-om/#the-stylepropertymap) |
| [CSS Typed OM Level 1 # cssunparsedvalue](https://drafts.css-houdini.org/css-typed-om/#cssunparsedvalue) |
| [CSS Typed OM Level 1 # keywordvalue-objects](https://drafts.css-houdini.org/css-typed-om/#keywordvalue-objects) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSKeywordValue` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `CSS_Typed_OM_API` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `value` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@iterator` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `CSSUnparsedValue` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `CSS_Typed_OM_API` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `entries` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `forEach` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `keys` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `length` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `values` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSS_Typed_OM_API` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `append` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `clear` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `delete` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `set` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSS_Typed_OM_API` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `parse` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `parseAll` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `toString` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |


### api.CSSStyleValue


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.StylePropertyMap


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.CSSUnparsedValue


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.CSSKeywordValue


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


See also
--------


* [CSS Painting API](css_painting_api)
* [Using the CSS Typed Object Model](css_typed_om_api/guide)
* [CSS Houdini](https://developer.mozilla.org/en-US/docs/Web/Guide/Houdini)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSS_Typed_OM_API>

CSS Object Model (CSSOM)
========================



The **CSS Object Model** is a set of APIs allowing the manipulation of CSS from JavaScript. It is much like the DOM, but for the CSS rather than the HTML. It allows users to read and modify CSS style dynamically.

 The values of CSS are represented untyped, that is using [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) objects.



Reference
---------



* [`AnimationEvent`](animationevent)
* [`CaretPosition`](caretposition)
* [`CSS`](css)
* `CSSCharsetRule`
* [`CSSConditionRule`](cssconditionrule)
* [`CSSCounterStyleRule`](csscounterstylerule)
* [`CSSFontFaceRule`](cssfontfacerule)
* `CSSFontFeatureValuesMap`
* [`CSSFontFeatureValuesRule`](cssfontfeaturevaluesrule)
* [`CSSGroupingRule`](cssgroupingrule)
* [`CSSImportRule`](cssimportrule)
* [`CSSKeyframeRule`](csskeyframerule)
* [`CSSKeyframesRule`](csskeyframesrule)
* `CSSMarginRule`
* [`CSSMediaRule`](cssmediarule)
* [`CSSNamespaceRule`](cssnamespacerule)
* [`CSSPageRule`](csspagerule)
* [`CSSRule`](cssrule)
* [`CSSRuleList`](cssrulelist)
* [`CSSStyleDeclaration`](cssstyledeclaration)
* [`CSSStyleSheet`](cssstylesheet)
* [`CSSStyleRule`](cssstylerule)
* [`CSSSupportsRule`](csssupportsrule)
* `CSSVariablesMap`
* `CSSViewportRule`
* [`FontFace`](fontface)
* [`FontFaceSet`](fontfaceset)
* [`FontFaceSetLoadEvent`](fontfacesetloadevent)
* `GetStyleUtils`
* [`MediaList`](medialist)
* [`MediaQueryList`](mediaquerylist)
* [`MediaQueryListEvent`](mediaquerylistevent)
* [`Screen`](screen)
* [`StyleSheet`](stylesheet)
* [`StyleSheetList`](stylesheetlist)
* [`TransitionEvent`](transitionevent)

 Several other interfaces are also extended by the CSSOM-related specifications: [`Document`](document), [`Window`](window), [`Element`](element), [`HTMLElement`](htmlelement), [`HTMLImageElement`](htmlimageelement), [`Range`](range), [`MouseEvent`](mouseevent), and [`SVGElement`](svgelement).



### CSS Typed Object Model  Experimental



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 * [`CSSImageValue`](cssimagevalue)  Experimental
* [`CSSKeywordValue`](csskeywordvalue)  Experimental
* [`CSSMathInvert`](cssmathinvert)  Experimental
* [`CSSMathMax`](cssmathmax)  Experimental
* [`CSSMathMin`](cssmathmin)  Experimental
* [`CSSMathNegate`](cssmathnegate)  Experimental
* [`CSSMathProduct`](cssmathproduct)  Experimental
* [`CSSMathSum`](cssmathsum)  Experimental
* [`CSSMathValue`](cssmathvalue)  Experimental
* [`CSSMatrixComponent`](cssmatrixcomponent)  Experimental
* [`CSSNumericArray`](cssnumericarray)  Experimental
* [`CSSNumericValue`](cssnumericvalue)  Experimental
* [`CSSPerspective`](cssperspective)  Experimental
* [`CSSPositionValue`](csspositionvalue)  Experimental
* [`CSSRotate`](cssrotate)  Experimental
* [`CSSScale`](cssscale)  Experimental
* [`CSSSkew`](cssskew)  Experimental
* [`CSSSkewX`](cssskewx)  Experimental
* [`CSSSkewY`](cssskewy)  Experimental
* [`CSSStyleValue`](cssstylevalue)  Experimental
* [`CSSTransformComponent`](csstransformcomponent)  Experimental
* [`CSSTransformValue`](csstransformvalue)  Experimental
* [`CSSTranslate`](csstranslate)  Experimental
* [`CSSUnitValue`](cssunitvalue)  Experimental
* [`CSSUnparsedValue`](cssunparsedvalue)  Experimental
* [`CSSVariableReferenceValue`](cssvariablereferencevalue)  Experimental
* [`StylePropertyMap`](stylepropertymap)  Experimental
* [`StylePropertyMapReadOnly`](stylepropertymapreadonly)  Experimental



### Obsolete CSSOM interfaces  Deprecated



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 * [`CSSPrimitiveValue`](cssprimitivevalue)  Deprecated
* [`CSSValue`](cssvalue)  Deprecated
* [`CSSValueList`](cssvaluelist)  Deprecated



Tutorials
---------


* [Determining the dimensions of elements](css_object_model/determining_the_dimensions_of_elements) (it needs some updating as it was made in the DHTML/Ajax era)
* [Managing screen orientation](css_object_model/managing_screen_orientation)

Specifications
--------------




| Specification |
| --- |
| [CSS Object Model (CSSOM)](https://drafts.csswg.org/cssom/)  |
| [CSSOM View Module](https://drafts.csswg.org/cssom-view/)  |
| [CSS Typed OM Level 1](https://drafts.css-houdini.org/css-typed-om/)  |


Browser compatibility
---------------------


See also
--------


* [Document Object Model (DOM)](document_object_model)
* [Houdini](https://developer.mozilla.org/en-US/docs/Web/Guide/Houdini)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model>

Canvas API
==========



The **Canvas API** provides a means for drawing graphics via [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript) and the [HTML](https://developer.mozilla.org/en-US/docs/Web/HTML) [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element. Among other things, it can be used for animation, game graphics, data visualization, photo manipulation, and real-time video processing.

 The Canvas API largely focuses on 2D graphics. The [WebGL API](webgl_api), which also uses the `<canvas>` element, draws hardware-accelerated 2D and 3D graphics.



Basic example
-------------


This simple example draws a green rectangle onto a canvas.


### HTML



```
<canvas id="canvas"></canvas>

```

### JavaScript



The [`Document.getElementById()`](document/getelementbyid) method gets a reference to the HTML `<canvas>` element. Next, the [`HTMLCanvasElement.getContext()`](htmlcanvaselement/getcontext) method gets that element's context—the thing onto which the drawing will be rendered.

 The actual drawing is done using the [`CanvasRenderingContext2D`](canvasrenderingcontext2d) interface. The [`fillStyle`](canvasrenderingcontext2d/fillstyle) property makes the rectangle green. The [`fillRect()`](canvasrenderingcontext2d/fillrect) method places its top-left corner at (10, 10), and gives it a size of 150 units wide by 100 tall.

 
```
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

ctx.fillStyle = "green";
ctx.fillRect(10, 10, 150, 100);

```


### Result



Reference
---------



* [`HTMLCanvasElement`](htmlcanvaselement)
* [`CanvasRenderingContext2D`](canvasrenderingcontext2d)
* [`CanvasGradient`](canvasgradient)
* [`CanvasPattern`](canvaspattern)
* [`ImageBitmap`](imagebitmap)
* [`ImageData`](imagedata)
* [`TextMetrics`](textmetrics)
* [`OffscreenCanvas`](offscreencanvas)
* [`Path2D`](path2d)  Experimental
* [`ImageBitmapRenderingContext`](imagebitmaprenderingcontext)  Experimental

  **Note:** The interfaces related to the `WebGLRenderingContext` are referenced under [WebGL](webgl_api).

   **Note:** [`OffscreenCanvas`](offscreencanvas) is also available in web workers.

  [`CanvasCaptureMediaStreamTrack`](canvascapturemediastreamtrack) is a related interface.



Guides and tutorials
--------------------


 [Canvas tutorial](canvas_api/tutorial)  A comprehensive tutorial covering both the basic usage of the Canvas API and its advanced features.

  [HTML5 Canvas Deep Dive](https://joshondesign.com/p/books/canvasdeepdive/title.html)  A hands-on, book-length introduction to the Canvas API and WebGL.

  [Canvas Handbook](https://bucephalus.org/text/CanvasHandbook/CanvasHandbook.html)  A handy reference for the Canvas API.

  [Manipulating video using canvas](canvas_api/manipulating_video_using_canvas)  Combining [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) and [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) to manipulate video data in real time.

  
Libraries
---------



The Canvas API is extremely powerful, but not always simple to use. The libraries listed below can make the creation of canvas-based projects faster and easier.

 * [EaselJS](https://www.createjs.com/easeljs) is an open-source canvas library that makes creating games, generative art, and other highly graphical experiences easy.
* [Fabric.js](http://fabricjs.com) is an open-source canvas library with SVG parsing capabilities.
* [heatmap.js](https://www.patrick-wied.at/static/heatmapjs/) is an open-source library for creating canvas-based data heat maps.
* [JavaScript InfoVis Toolkit](https://philogb.github.io/jit/) creates interactive data visualizations.
* [Konva.js](https://konvajs.org/) is a 2D canvas library for desktop and mobile applications.
* [p5.js](https://p5js.org/) has a full set of canvas drawing functionality for artists, designers, educators, and beginners.
* [Paper.js](http://paperjs.org/) is an open-source vector graphics scripting framework that runs on top of the HTML Canvas.
* [Phaser](https://phaser.io/) is a fast, free and fun open source framework for Canvas and WebGL powered browser games.
* [Pts.js](https://ptsjs.org) is a library for creative coding and visualization in canvas and SVG.
* [Rekapi](https://github.com/jeremyckahn/rekapi) is an animation key-framing API for Canvas.
* [Scrawl-canvas](https://scrawl.rikweb.org.uk/) is an open-source JavaScript library for creating and manipulating 2D canvas elements.
* The [ZIM](https://zimjs.com) framework provides conveniences, components, and controls for coding creativity on the canvas — includes accessibility and hundreds of colorful tutorials.
* [Sprig](https://github.com/hackclub/sprig) is a beginner-friendly, open-source, tile-based game development library that uses Canvas.

  **Note:** See the [WebGL API](webgl_api) for 2D and 3D libraries that use WebGL.

 

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-canvas-element](https://html.spec.whatwg.org/multipage/canvas.html#the-canvas-element) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Canvas_API` | 1 | 12 | 1.5["Before Firefox 5, the canvas width and height were signed integers instead of unsigned integers.", "Before Firefox 6, a <canvas> element with a zero width or height would be rendered as if it had default dimensions.", "Before Firefox 12, if JavaScript is disabled, the <canvas> element was being rendered instead of showing the fallback content as per the specification. Since then, the fallback content is rendered instead."] | 9 | 9 | 2Although early versions of Apple's Safari browser don't require the closing tag, the specification indicates that it is required, so you should be sure to include it for broadest compatibility. Before version 2, Safari will render the content of the fallback in addition to the canvas itself unless you use CSS tricks to mask it. | 37 | 18 | 4["Before Firefox 5, the canvas width and height were signed integers instead of unsigned integers.", "Before Firefox 6, a <canvas> element with a zero width or height would be rendered as if it had default dimensions.", "Before Firefox 12, if JavaScript is disabled, the <canvas> element was being rendered instead of showing the fallback content as per the specification. Since then, the fallback content is rendered instead."] | 10.1 | 1 | 1.0 |
| `height` | 1 | 12 | 1.5["Before Firefox 5, the canvas width and height were signed integers instead of unsigned integers.", "Before Firefox 6, a <canvas> element with a zero width or height would be rendered as if it had default dimensions.", "Before Firefox 12, if JavaScript is disabled, the <canvas> element was being rendered instead of showing the fallback content as per the specification. Since then, the fallback content is rendered instead."] | 9 | 9 | 2Although early versions of Apple's Safari browser don't require the closing tag, the specification indicates that it is required, so you should be sure to include it for broadest compatibility. Before version 2, Safari will render the content of the fallback in addition to the canvas itself unless you use CSS tricks to mask it. | 37 | 18 | 4["Before Firefox 5, the canvas width and height were signed integers instead of unsigned integers.", "Before Firefox 6, a <canvas> element with a zero width or height would be rendered as if it had default dimensions.", "Before Firefox 12, if JavaScript is disabled, the <canvas> element was being rendered instead of showing the fallback content as per the specification. Since then, the fallback content is rendered instead."] | 10.1 | 1 | 1.0 |
| `moz-opaque` | No | No | 3.5 | No | No | No | No | No | 4 | No | No | No |
| `width` | 1 | 12 | 1.5["Before Firefox 5, the canvas width and height were signed integers instead of unsigned integers.", "Before Firefox 6, a <canvas> element with a zero width or height would be rendered as if it had default dimensions.", "Before Firefox 12, if JavaScript is disabled, the <canvas> element was being rendered instead of showing the fallback content as per the specification. Since then, the fallback content is rendered instead."] | 9 | 9 | 2Although early versions of Apple's Safari browser don't require the closing tag, the specification indicates that it is required, so you should be sure to include it for broadest compatibility. Before version 2, Safari will render the content of the fallback in addition to the canvas itself unless you use CSS tricks to mask it. | 37 | 18 | 4["Before Firefox 5, the canvas width and height were signed integers instead of unsigned integers.", "Before Firefox 6, a <canvas> element with a zero width or height would be rendered as if it had default dimensions.", "Before Firefox 12, if JavaScript is disabled, the <canvas> element was being rendered instead of showing the fallback content as per the specification. Since then, the fallback content is rendered instead."] | 10.1 | 1 | 1.0 |


See also
--------


* [WebGL](webgl_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API>

Channel Messaging API
=====================



The **Channel Messaging API** allows two separate scripts running in different browsing contexts attached to the same document (e.g., two IFrames, or the main document and an IFrame, two documents via a [`SharedWorker`](sharedworker), or two workers) to communicate directly, passing messages between one another through two-way channels (or pipes) with a port at each end.


 **Note:** This feature is available in [Web Workers](web_workers_api)

 

Channel messaging concepts and usage
------------------------------------



A message channel is created using the [`MessageChannel()`](messagechannel/messagechannel) constructor. Once created, the two ports of the channel can be accessed through the [`MessageChannel.port1`](messagechannel/port1) and [`MessageChannel.port2`](messagechannel/port2) properties (which both return [`MessagePort`](messageport) objects.) The app that created the channel uses `port1`, and the app at the other end of the port uses `port2` — you send a message to `port2`, and transfer the port over to the other browsing context using [`window.postMessage`](window/postmessage) along with two arguments (the message to send, and the object to transfer ownership of, in this case the port itself.)

 When these transferable objects are transferred, they are no longer usable on the context they previously belonged to. A port, after it is sent, can no longer be used by the original context.

 The other browsing context can listen for the message using [`onmessage`](messageport/message_event), and grab the contents of the message using the event's `data` attribute. You could then respond by sending a message back to the original document using [`MessagePort.postMessage`](messageport/postmessage).

 When you want to stop sending messages down the channel, you can invoke [`MessagePort.close`](messageport/close) to close the ports.

 Find out more about how to use this API in [Using channel messaging](channel_messaging_api/using_channel_messaging).



Channel messaging interfaces
----------------------------


 [`MessageChannel`](messagechannel)  Creates a new message channel to send messages across.

  [`MessagePort`](messageport)  Controls the ports on the message channel, allowing sending of messages from one port and listening out for them arriving at the other.

  
Examples
--------


* We have published a [channel messaging basic demo](https://github.com/mdn/dom-examples/tree/main/channel-messaging-basic) on GitHub ([run it live too](https://mdn.github.io/dom-examples/channel-messaging-basic/)), which shows a really simple single message transfer between a page and an embedded [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe).
* You can also see a [multimessaging demo](https://github.com/mdn/dom-examples/tree/main/channel-messaging-multimessage) ([run this live](https://mdn.github.io/dom-examples/channel-messaging-multimessage/)), which shows a slightly more complex setup that can send multiple messages between main page and IFrame.

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # message-channels](https://html.spec.whatwg.org/multipage/web-messaging.html#message-channels) |
| [HTML Standard # message-ports](https://html.spec.whatwg.org/multipage/web-messaging.html#message-ports) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Channel_Messaging_API` | 2 | 12 | 41 | 10 | 10.6 | 5 | 4.4 | 18 | 41 | 11 | 4.2 | 1.0 |
| `close` | 2 | 12 | 41 | 10 | 10.6 | 5 | 4.4 | 18 | 41 | 11 | 4.2 | 1.0 |
| `message_event` | 2 | 12 | 41 | 10 | 10.6 | 5 | ≤37 | 18 | 41 | 11.5 | 4.2 | 1.0 |
| `messageerror_event` | 60 | 18 | 57 | No | 47 | 16.4See [bug 171216](https://webkit.org/b/171216). | 60 | 60 | 57 | 47 | 16.4See [bug 171216](https://webkit.org/b/171216). | 8.0 |
| `postMessage` | 2 | 12 | 41 | 10 | 10.6 | 5 | 4.4 | 18 | 41 | 11 | 4.2 | 1.0 |
| `start` | 2 | 12 | 41 | 10 | 10.6 | 5 | 4.4 | 18 | 41 | 11 | 4.2 | 1.0 |
| `worker_support` | 4 | 12 | 41 | 10 | ≤15 | 5 | ≤37 | 18 | 41 | ≤14 | 5 | 1.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MessageChannel` | 2 | 12 | 41 | 10 | 10.6 | 5 | 4.4 | 18 | 41 | 11 | 4.2 | 1.0 |
| `Channel_Messaging_API` | 2 | 12 | 41 | 10 | 10.6 | 5 | 4.4 | 18 | 41 | 11 | 4.2 | 1.0 |
| `port1` | 2 | 12 | 41 | 10 | 10.6 | 5 | 4.4 | 18 | 41 | 11 | 4.2 | 1.0 |
| `port2` | 2 | 12 | 41 | 10 | 10.6 | 5 | 4.4 | 18 | 41 | 11 | 4.2 | 1.0 |


### api.MessageChannel


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.MessagePort


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


See also
--------


* [Using channel messaging](channel_messaging_api/using_channel_messaging)
* [Web Workers API](web_workers_api)
* [Broadcast Channel API](broadcast_channel_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Channel_Messaging_API>

Clipboard API
=============



The **Clipboard API** provides the ability to respond to clipboard commands (cut, copy, and paste) as well as to asynchronously read from and write to the system clipboard.

  **Note:** This API is *not available* in [Web Workers](web_workers_api) (not exposed via [`WorkerNavigator`](workernavigator)).

  This API is designed to supersede accessing the clipboard using [`document.execCommand()`](document/execcommand).

   **Note:** The **clipboard** is a data buffer that is used for short-term, data storage and/or data transfers, this can be between documents or applications. It is usually implemented as an anonymous, temporary [data buffer](https://en.wikipedia.org/wiki/Data_buffer), sometimes called the paste buffer, that can be accessed from most or all programs within the environment via defined [programming interfaces](https://en.wikipedia.org/wiki/Application_programming_interface). 

 A typical application accesses clipboard functionality by mapping [user input](https://en.wikipedia.org/wiki/User_input) such as [keybindings](https://en.wikipedia.org/wiki/Keybinding), [menu selections](https://en.wikipedia.org/wiki/Menu_(computing)), etc. to these interfaces.

 

Accessing the clipboard
-----------------------



Instead of creating a `Clipboard` object through instantiation, you access the system clipboard through the [`Navigator.clipboard`](navigator/clipboard) global:

 
```
navigator.clipboard
  .readText()
  .then(
    (clipText) => (document.querySelector(".editor").innerText += clipText)
  );

```
 This snippet fetches the text from the clipboard and appends it to the first element found with the class `editor`. Since [`readText()`](clipboard/readtext) (and [`read()`](clipboard/read), for that matter) returns an empty string if the clipboard isn't text, this code is safe.



Interfaces
----------


 
[`Clipboard`](clipboard) Secure context
  Provides an interface for reading and writing text and data to or from the system clipboard. The specification refers to this as the 'Async Clipboard API'.

  
[`ClipboardEvent`](clipboardevent) Secure context
  Represents events providing information related to modification of the clipboard, that is [`cut`](element/cut_event), [`copy`](element/copy_event), and [`paste`](element/paste_event) events. The specification refers to this as the 'Clipboard Event API'.

  
[`ClipboardItem`](clipboarditem) Secure context
  Represents a single item format, used when reading or writing data.

  
Specifications
--------------




| Specification |
| --- |
| [Clipboard API and events # clipboard-interface](https://w3c.github.io/clipboard-apis/#clipboard-interface) |
| [Clipboard API and events # clipboard-event-interfaces](https://w3c.github.io/clipboard-apis/#clipboard-event-interfaces) |
| [Clipboard API and events # clipboarditem](https://w3c.github.io/clipboard-apis/#clipboarditem) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ClipboardItem` | 9876–98The `ClipboardItem` constructor only accepts a blob as the item data, but not strings or Promises that resolve to strings or blobs. See [bug 1014310](https://crbug.com/1014310). | 9879–98The `ClipboardItem` constructor only accepts a blob as the item data, but not strings or Promises that resolve to strings or blobs. See [bug 1014310](https://crbug.com/1014310). | 87 | No | 8463–84The `ClipboardItem` constructor only accepts a blob as the item data, but not strings or Promises that resolve to strings or blobs. See [bug 1014310](https://crbug.com/1014310). | 13.1 | 9884–98The `ClipboardItem` constructor only accepts a blob as the item data, but not strings or Promises that resolve to strings or blobs. See [bug 1014310](https://crbug.com/1014310). | 9884–98The `ClipboardItem` constructor only accepts a blob as the item data, but not strings or Promises that resolve to strings or blobs. See [bug 1014310](https://crbug.com/1014310). | No | 6860–68The `ClipboardItem` constructor only accepts a blob as the item data, but not strings or Promises that resolve to strings or blobs. See [bug 1014310](https://crbug.com/1014310). | 13.4 | 18.014.0–18.0The `ClipboardItem` constructor only accepts a blob as the item data, but not strings or Promises that resolve to strings or blobs. See [bug 1014310](https://crbug.com/1014310). |
| `Clipboard_API` | 76 | 79 | 87 | No | 63 | 13.1 | 84 | 84 | No | 60 | 13.4 | 14.0 |
| `getType` | 76 | 79 | 87 | No | 63 | 13.1 | 84 | 84 | No | 60 | 13.4 | 14.0 |
| `presentationStyle` | No | No | 87 | No | No | 13.1 | 84 | 84 | No | 60 | 13.4 | 14.0 |
| `types` | 76 | 79 | 87 | No | 63 | 13.1 | 84 | 84 | No | 60 | 13.4 | 14.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ClipboardEvent` | 58 | 17 | 22 | No | 45 | 10.1 | 58 | 58 | 22 | 43 | 10.3 | 7.0 |
| `Clipboard_API` | 41 | 12 | 22 | 4 | 28 | 10.1 | 41 | 41 | 22 | 28 | 10.3 | 4.0 |
| `clipboardData` | 41 | 12 | 22 | 5 | 28 | 10.1 | 41 | 41 | 22 | 28 | 10.3 | 4.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Clipboard_API` | 66 | 79 | 63 | No | 53 | 13.1 | 66 | 66 | 63 | 47 | 13.4 | 9.0 |
| `read` | 86From version 86, the `text/html` MIME type is supported.76From version 76, the `image/png` MIME type is supported.66Images are not supported. | 79 | 90Firefox only supports reading the clipboard in browser extensions, using the `"clipboardRead"` extension permission. | No | 63 | 13.1 | 84From version 84, the `image/png` MIME type is supported.66Images are not supported. | 86From version 86, the `text/html` MIME type is supported.84From version 84, the `image/png` MIME type is supported.66Images are not supported. | No | 54 | 13.4 | 12.0 |
| `readText` | 66 | 79 | NoFirefox only supports reading the clipboard in browser extensions, using the `"clipboardRead"` extension permission. | No | 53 | 13.1 | 66 | 66 | NoFirefox only supports reading the clipboard in browser extensions, using the `"clipboardRead"` extension permission. | 47 | 13.4 | 9.0 |
| `write` | 66From version 76, the `image/png` MIME type is supported. | 79 | 87Writing to the clipboard is available without permission in secure contexts and browser extensions, but only from user-initiated event callbacks. Browser extensions with the `"clipboardWrite"` permission can write to the clipboard at any time.63["This method accepts a `DataTransfer` object instead of an array of `ClipboardItem` objects.", "Writing to the clipboard is available without permission in secure contexts and browser extensions, but only from user-initiated event callbacks. Browser extensions with the `\"clipboardWrite\"` permission can write to the clipboard at any time."] | No | 63 | 13.1 | 66From version 84, the `image/png` MIME type is supported. | 66From version 84, the `image/png` MIME type is supported. | No | 54 | 13.4 | 12.0 |
| `writeText` | 66 | 79 | 63Writing to the clipboard is available without permission in secure contexts and browser extensions, but only from user-initiated event callbacks. Browser extensions with the `"clipboardWrite"` permission can write to the clipboard at any time. | No | 53 | 13.1Must be called within user gesture event handlers such as `pointerdown` or `pointerup`. | 66 | 66 | 63Writing to the clipboard is available without permission in secure contexts and browser extensions, but only from user-initiated event callbacks. Browser extensions with the `"clipboardWrite"` permission can write to the clipboard at any time. | 47 | 13.4Must be called within user gesture event handlers such as `pointerdown` or `pointerup`. | 9.0 |


### api.Clipboard


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.ClipboardEvent


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.ClipboardItem


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


See also
--------


* [Async Clipboard API demo on Glitch](https://async-clipboard-api.glitch.me/)
* [Image support for Async Clipboard article](https://web.dev/async-clipboard/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API>

Compression Streams API
=======================



The **Compression Streams API** provides a JavaScript API for compressing and decompressing streams of data using the gzip or deflate formats.

 Built in compression means that JavaScript applications will not need to include a compression library, which makes the download size of the application smaller.



Interfaces
----------


 [`CompressionStream`](compressionstream)  Compresses a stream of data.

  [`DecompressionStream`](decompressionstream)  Decompresses a stream of data.

  
Examples
--------



In this example a stream is compressed using gzip compression.

 
```
const compressedReadableStream = inputReadableStream.pipeThrough(
  new CompressionStream("gzip")
);

```
 In the following example a function decompresses a blob using gzip.

 
```
async function DecompressBlob(blob) {
  const ds = new DecompressionStream("gzip");
  const decompressedStream = blob.stream().pipeThrough(ds);
  return await new Response(decompressedStream).blob();
}

```


Specifications
--------------




| Specification |
| --- |
| [Compression Streams # compression-stream](https://wicg.github.io/compression/#compression-stream) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CompressionStream` | 80 | 80 | No | No | 67 | 16.4 | 80 | 80 | No | 57 | 16.4 | 13.0 |
| `Compression_Streams_API` | 80 | 80 | No | No | 67 | 16.4 | 80 | 80 | No | 57 | 16.4 | 13.0 |
| `readable` | 80 | 80 | No | No | 67 | 16.4 | 80 | 80 | No | 57 | 16.4 | 13.0 |
| `writable` | 80 | 80 | No | No | 67 | 16.4 | 80 | 80 | No | 57 | 16.4 | 13.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Compression_Streams_API>

Contact Picker API
==================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The Contact Picker API allows users to select entries from their contact list and share limited details of the selected entries with a website or application.

  **Note:** This API is *not available* in [Web Workers](web_workers_api) (not exposed via [`WorkerNavigator`](workernavigator)).

 

Contact Picker API Concepts and Usage
-------------------------------------



Access to contacts has long been a feature available within native applications. The Contacts Picker API brings that functionality to web applications.

 Use cases include selecting contacts to message via an email or chat application, selecting a contacts phone number for use with voice over IP (VOIP), or for discovering contacts who have already joined a social platform. User agents can also offer a consistent experience with other applications on a users device.

 When calling the [`select`](contactsmanager/select) method of the [`ContactsManager`](contactsmanager) interface, the user is presented with a contact picker, whereby they can then select contact information to share with the web application. User interaction is required before permission to display the contact picker is granted and access to contacts is not persistent; the user must grant access every time a request is made by the application.

 This API is only available from a secure top-level browsing context and very carefully considers the sensitivity and privacy of contact data. The onus is on the user for choosing data to share and only allows specific data for selected contacts, with no access to any data for other contacts.



Interfaces
----------


 [`ContactAddress`](contactaddress)  Represents a physical address.

  [`ContactsManager`](contactsmanager)  Provides a way for users to select and share limited details of contacts with a web application.

  [`Navigator.contacts`](navigator/contacts)  Returns a [`ContactsManager`](contactsmanager) object instance, from which all other functionality can be accessed.

  
Examples
--------


### Feature Detection



The following code checks whether the Contact Picker API is supported.

 
```
const supported = "contacts" in navigator;

```


### Checking for Supported Properties



The following asynchronous function uses the `getProperties()` method to check for supported properties.

 
```
async function checkProperties() {
  const supportedProperties = await navigator.contacts.getProperties();
  if (supportedProperties.includes("name")) {
    // run code for name support
  }
  if (supportedProperties.includes("email")) {
    // run code for email support
  }
  if (supportedProperties.includes("tel")) {
    // run code for telephone number support
  }
  if (supportedProperties.includes("address")) {
    // run code for address support
  }
  if (supportedProperties.includes("icon")) {
    // run code for avatar support
  }
}

```


### Selecting Contacts



The following example sets an array of properties to be retrieved for each contact, as well as setting an options object to allow for multiple contacts to be selected.

 An asynchronous function is then defined which uses the `select()` method to present the user with a contact picker interface and handle the chosen results.

 
```
const props = ["name", "email", "tel", "address", "icon"];
const opts = { multiple: true };

async function getContacts() {
  try {
    const contacts = await navigator.contacts.select(props, opts);
    handleResults(contacts);
  } catch (ex) {
    // Handle any errors here.
  }
}

```
 `handleResults()` is a developer defined function.



Specifications
--------------




| Specification |
| --- |
| [Contact Picker API # contacts-manager](https://w3c.github.io/contact-picker/#contacts-manager) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Contact_Picker_API` | No | No | No | No | No | No | 80 | 80 | No | 57 | 14.5 | 13.0 |
| `getProperties` | No | No | No | No | No | No | 80 | 80 | No | 57 | 14.5 | 13.0 |
| `select` | No | No | No | No | No | No | 80 | 80 | No | 57 | 14.5 | 13.0 |


See also
--------


* [A Contact Picker for the Web](https://web.dev/contact-picker/)
* [A Contact Picker demo on glitch](https://contact-picker.glitch.me/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Contact_Picker_API>

Content Index API
=================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The **Content Index API** allows developers to register their offline enabled content with the browser.



Concepts and usage
------------------



As it stands, offline web content is not easily discoverable by users. Content indexing allows developers to tell the browser about their specific offline content. This allows users to discover and view what is available, whilst giving developers the ability to add and manage this content. Examples could be a news website prefetching the latest articles in the background, or a content streaming app registering downloaded content.

 The Content Index API is an extension to [service workers](service_worker_api), which allows developers to add URLs and metadata of already cached pages, under the scope of the current service worker. The browser can then use these entries to display offline reading to a user. As a developer you can also display these entries within your application.

 Indexed entries do not automatically expire. It's good practice to present an interface for clearing out entries, or periodically remove older entries.

  **Note:** The API supports indexing URLs corresponding to HTML documents. A URL for a cached media file, for example, can't be indexed directly. Instead, you need to provide a URL for a page that displays media, and which works offline.

 

Interfaces
----------


 [`ContentIndex`](contentindex)  The `ContentIndex` interface provides functionality to register content available offline.

  [`ContentIndexEvent`](contentindexevent)  The `ContentIndexEvent` interface of the [`Content Index API`](content_index_api) defines the object used to represent the [`contentdelete`](serviceworkerglobalscope/contentdelete_event) event.

  
Service worker additions
------------------------



The following additions to the [`ServiceWorker`](serviceworker) have been specified in the Content Index API spec to provide an entry point for using content indexing.

  
[`ServiceWorkerRegistration.index`](serviceworkerregistration/index) Read only 
  Returns a reference to the [`ContentIndex`](contentindex) interface for indexing cached pages.

  
[`contentdelete`](serviceworkerglobalscope/contentdelete_event) event  Experimental 
  An event fired when content is removed by the user agent.

  

Examples
--------


All the following examples assume a service worker has been registered. For more information see the [Service Worker API](service_worker_api).


### Feature detection and interface access



Here we get a reference to the [`ServiceWorkerRegistration`](serviceworkerregistration), then check for the `index` property, which gives us access to the content index interface.

 
```
// reference registration
const registration = await navigator.serviceWorker.ready;

// feature detection
if ("index" in registration) {
  // Content Index API functionality
  const contentIndex = registration.index;
}

```


### Adding to the content index



Here we're declaring an item in the correct format and creating an asynchronous function which uses the [`add()`](contentindex/add) method to register it with the [`content index`](content_index_api).

 
```
// our content
const item = {
  id: "post-1",
  url: "/posts/amet.html",
  title: "Amet consectetur adipisicing",
  description:
    "Repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.",
  icons: [
    {
      src: "/media/dark.png",
      sizes: "128x128",
      type: "image/png",
    },
  ],
  category: "article",
};

// our asynchronous function to add indexed content
async function registerContent(data) {
  const registration = await navigator.serviceWorker.ready;

  // feature detect Content Index
  if (!registration.index) {
    return;
  }

  // register content
  try {
    await registration.index.add(data);
  } catch (e) {
    console.log("Failed to register content: ", e.message);
  }
}

```


### Retrieving items within the current index



The below example shows an asynchronous function that retrieves items within the content index and iterates over each entry, building a list for the interface.

 
```
async function createReadingList() {
  // access our service worker registration
  const registration = await navigator.serviceWorker.ready;

  // get our index entries
  const entries = await registration.index.getAll();

  // create a containing element
  const readingListElem = document.createElement("div");

  // test for entries
  if (!Array.length) {
    // if there are no entries, display a message
    const message = document.createElement("p");
    message.innerText =
      "You currently have no articles saved for offline reading.";

    readingListElem.append(message);
  } else {
    // if entries are present, display in a list of links to the content
    const listElem = document.createElement("ul");

    for (const entry of entries) {
      const listItem = document.createElement("li");

      const anchorElem = document.createElement("a");
      anchorElem.innerText = entry.title;
      anchorElem.setAttribute("href", entry.url);

      listElem.append(listItem);
    }

    readingListElem.append(listElem);
  }
}

```


### Unregistering indexed content



Below is an asynchronous function, that removes an item from the content index.

 
```
async function unregisterContent(article) {
  // reference registration
  const registration = await navigator.serviceWorker.ready;

  // feature detect Content Index
  if (!registration.index) return;

  // unregister content from index
  await registration.index.delete(article.id);
}

```
 All the above methods are available within the scope of the [service worker](serviceworker). They are accessible from the [`WorkerGlobalScope.self`](workerglobalscope/self) property:

 
```
// service worker script

self.registration.index.add(item);

self.registration.index.delete(item.id);

const contentIndexItems = self.registration.index.getAll();

```


### The contentdelete event



When an item is removed from the user agent interface, a `contentdelete` event is received by the service worker.

 
```
self.addEventListener("contentdelete", (event) => {
  console.log(event.id);

  // logs content index id, which can then be used to determine what content to delete from your cache
});

```
 The [`contentdelete`](serviceworkerglobalscope/contentdelete_event) event is only fired when the deletion happens due to interaction with the browser's built-in user interface. It is not fired when the [`ContentIndex.delete()`](contentindex/delete) method is called.



Specifications
--------------




| Specification |
| --- |
| [Content Index # content-index](https://wicg.github.io/content-index/spec/#content-index) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Content_Index_API` | No | No | No | No | No | No | 84 | 84 | No | 60 | No | 14.0 |
| `add` | No | No | No | No | No | No | 84 | 84 | No | 60 | No | 14.0 |
| `delete` | No | No | No | No | No | No | 84 | 84 | No | 60 | No | 14.0 |
| `getAll` | No | No | No | No | No | No | 84 | 84 | No | 60 | No | 14.0 |


See also
--------


* [An introductory article on the Content Index API](https://web.dev/content-indexing-api/)
* [An app which uses the Content Index API to list and remove 'save for later' content](https://contentindex.dev/)
* [Service Worker API, along with information about Cache and CacheStorage](service_worker_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Content_Index_API>

Cookie Store API
================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The ***Cookie Store API*** provides an asynchronous API for managing cookies, while also exposing cookies to [Service Worker API](service_worker_api),



Concepts and Usage
------------------



The existing method of getting and setting cookies involves working with [`document.cookie`](document/cookie) as a string of key/value pairs. In addition to this being cumbersome and error prone, it also has a host of issues in the context of modern web development.

 The `document.cookie` interface is [synchronous](https://developer.mozilla.org/en-US/docs/Glossary/Synchronous), single-threaded, and blocking. When writing a cookie you must wait for the browser to update the string of all cookies. In addition, the reliance on [`document`](document) means that cookies cannot be accessed by service workers which cannot access the `document` object.

 The *Cookie Store API* provides an updated method of managing cookies. It is [asynchronous](https://developer.mozilla.org/en-US/docs/Glossary/Asynchronous) and promise-based, therefore does not block the event loop. It does not rely on [`document`](document) and so is available to service workers. The methods for getting and setting cookies also provide more feedback by way of error messages. This means that web developers do not have to set then immediately read back a cookie to check that setting was successful.



Interfaces
----------


 [`CookieStore`](cookiestore)  The `CookieStore` interface enables getting and setting cookies.

  [`CookieStoreManager`](cookiestoremanager)  The `CookieStoreManager` interface provides a service worker registration to enable service workers to subscribe to cookie change events.

  [`CookieChangeEvent`](cookiechangeevent)  A `CookieChangeEvent` named `change` is dispatched against `CookieStore` objects in [`Window`](window) contexts when any script-visible cookies changes occur.

  [`ExtendableCookieChangeEvent`](extendablecookiechangeevent)  An `ExtendableCookieChangeEvent` named `change` is dispatched against [`ServiceWorkerGlobalScope`](serviceworkerglobalscope) events when any script-visible cookie changes occur that match the service worker's cookie change subscription list.

  
Specifications
--------------




| Specification |
| --- |
| [Cookie Store API # CookieStore](https://wicg.github.io/cookie-store/#CookieStore) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Cookie_Store_API` | 87 | 87 | NoSee [bug 1475599](https://bugzil.la/1475599). | No | 73 | NoSee [bug 231750](https://webkit.org/b/231750). | 87 | 87 | NoSee [bug 1475599](https://bugzil.la/1475599). | 62 | NoSee [bug 231750](https://webkit.org/b/231750). | 14.0 |
| `change_event` | 87 | 87 | No | No | 73 | No | 87 | 87 | No | 62 | No | 14.0 |
| `delete` | 87 | 87 | No | No | 73 | No | 87 | 87 | No | 62 | No | 14.0 |
| `get` | 87 | 87 | No | No | 73 | No | 87 | 87 | No | 62 | No | 14.0 |
| `getAll` | 87 | 87 | No | No | 73 | No | 87 | 87 | No | 62 | No | 14.0 |
| `set` | 87 | 87 | No | No | 73 | No | 87 | 87 | No | 62 | No | 14.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Cookie_Store_API>

Document Object Model (DOM)
===========================



The **Document Object Model** (**DOM**) connects web pages to scripts or programming languages by representing the structure of a document—such as the HTML representing a web page—in memory. Usually it refers to JavaScript, even though modeling HTML, SVG, or XML documents as objects are not part of the core JavaScript language.

 The DOM represents a document with a logical tree. Each branch of the tree ends in a node, and each node contains objects. DOM methods allow programmatic access to the tree. With them, you can change the document's structure, style, or content.

 Nodes can also have event handlers attached to them. Once an event is triggered, the event handlers get executed.

 To learn more about what the DOM is and how it represents documents, see our article [Introduction to the DOM](document_object_model/introduction).



DOM interfaces
--------------


* [`AbortController`](abortcontroller)
* [`AbortSignal`](abortsignal)
* [`AbstractRange`](abstractrange)
* [`Attr`](attr)
* [`CDATASection`](cdatasection)
* [`CharacterData`](characterdata)
* [`Comment`](comment)
* [`CustomEvent`](customevent)
* [`Document`](document)
* [`DocumentFragment`](documentfragment)
* [`DocumentType`](documenttype)
* [`DOMError`](domerror)  Deprecated
* [`DOMException`](domexception)
* [`DOMImplementation`](domimplementation)
* [`DOMParser`](domparser)
* [`DOMPoint`](dompoint)
* [`DOMPointReadOnly`](dompointreadonly)
* [`DOMRect`](domrect)
* [`DOMTokenList`](domtokenlist)
* [`Element`](element)
* [`Event`](event)
* [`EventTarget`](eventtarget)
* [`HTMLCollection`](htmlcollection)
* [`MutationObserver`](mutationobserver)
* [`MutationRecord`](mutationrecord)
* [`NamedNodeMap`](namednodemap)
* [`Node`](node)
* [`NodeFilter`](document/createnodeiterator)
* [`NodeIterator`](nodeiterator)
* [`NodeList`](nodelist)
* [`ProcessingInstruction`](processinginstruction)
* [`Range`](range)
* [`StaticRange`](staticrange)
* [`Text`](text)
* [`TextDecoder`](textdecoder)
* [`TextEncoder`](textencoder)
* [`TimeRanges`](timeranges)
* [`TreeWalker`](treewalker)
* [`XMLDocument`](xmldocument)

### Obsolete DOM interfaces



The Document Object Model has been highly simplified. To achieve this, the following interfaces present in the different DOM level 3 or earlier specifications have been removed. It is uncertain whether some may be reintroduced in the future or not, but for the time being they should be considered obsolete and should be avoided:

 * `DOMConfiguration`
* `DOMErrorHandler`
* `DOMImplementationList`
* `DOMImplementationRegistry`
* `DOMImplementationSource`
* `DOMLocator`
* `DOMObject`
* `DOMSettableTokenList`
* `DOMUserData`
* `ElementTraversal`
* `Entity`
* `EntityReference`
* `NameList`
* `Notation`
* `TypeInfo`
* `UserDataHandler`



HTML DOM
--------



A document containing HTML is described using the [`Document`](document) interface, which is extended by the HTML specification to include various HTML-specific features. In particular, the [`Element`](element) interface is enhanced to become [`HTMLElement`](htmlelement) and various subclasses, each representing one of (or a family of closely related) elements.

 The HTML DOM API provides access to various browser features such as tabs and windows, CSS styles and stylesheets, browser history, and so forth. These interfaces are discussed further in [the HTML DOM API](html_dom_api) documentation.



SVG interfaces
--------------


### SVG element interfaces


* [`SVGAElement`](svgaelement)
* [`SVGAltGlyphElement`](svgaltglyphelement)  Deprecated
* [`SVGAltGlyphDefElement`](svgaltglyphdefelement)  Deprecated
* [`SVGAltGlyphItemElement`](svgaltglyphitemelement)  Deprecated
* [`SVGAnimationElement`](svganimationelement)
* [`SVGAnimateElement`](svganimateelement)
* [`SVGAnimateColorElement`](svganimatecolorelement)  Deprecated
* [`SVGAnimateMotionElement`](svganimatemotionelement)
* [`SVGAnimateTransformElement`](svganimatetransformelement)
* [`SVGCircleElement`](svgcircleelement)
* [`SVGClipPathElement`](svgclippathelement)
* [`SVGComponentTransferFunctionElement`](svgcomponenttransferfunctionelement)
* [`SVGCursorElement`](svgcursorelement)
* [`SVGDefsElement`](svgdefselement)
* [`SVGDescElement`](svgdescelement)
* [`SVGElement`](svgelement)
* [`SVGEllipseElement`](svgellipseelement)
* [`SVGFEBlendElement`](svgfeblendelement)
* [`SVGFEColorMatrixElement`](svgfecolormatrixelement)
* [`SVGFEComponentTransferElement`](svgfecomponenttransferelement)
* [`SVGFECompositeElement`](svgfecompositeelement)
* [`SVGFEConvolveMatrixElement`](svgfeconvolvematrixelement)
* [`SVGFEDiffuseLightingElement`](svgfediffuselightingelement)
* [`SVGFEDisplacementMapElement`](svgfedisplacementmapelement)
* [`SVGFEDistantLightElement`](svgfedistantlightelement)
* [`SVGFEDropShadowElement`](svgfedropshadowelement)
* [`SVGFEFloodElement`](svgfefloodelement)
* [`SVGFEFuncAElement`](svgfefuncaelement)
* [`SVGFEFuncBElement`](svgfefuncbelement)
* [`SVGFEFuncGElement`](svgfefuncgelement)
* [`SVGFEFuncRElement`](svgfefuncrelement)
* [`SVGFEGaussianBlurElement`](svgfegaussianblurelement)
* [`SVGFEImageElement`](svgfeimageelement)
* [`SVGFEMergeElement`](svgfemergeelement)
* [`SVGFEMergeNodeElement`](svgfemergenodeelement)
* [`SVGFEMorphologyElement`](svgfemorphologyelement)
* [`SVGFEOffsetElement`](svgfeoffsetelement)
* [`SVGFEPointLightElement`](svgfepointlightelement)
* [`SVGFESpecularLightingElement`](svgfespecularlightingelement)
* [`SVGFESpotLightElement`](svgfespotlightelement)
* [`SVGFETileElement`](svgfetileelement)
* [`SVGFETurbulenceElement`](svgfeturbulenceelement)
* [`SVGFilterElement`](svgfilterelement)
* `SVGFilterPrimitiveStandardAttributes`
* [`SVGFontElement`](svgfontelement)  Deprecated
* [`SVGFontFaceElement`](svgfontfaceelement)  Deprecated
* [`SVGFontFaceFormatElement`](svgfontfaceformatelement)  Deprecated
* [`SVGFontFaceNameElement`](svgfontfacenameelement)  Deprecated
* [`SVGFontFaceSrcElement`](svgfontfacesrcelement)  Deprecated
* [`SVGFontFaceUriElement`](svgfontfaceurielement)  Deprecated
* [`SVGForeignObjectElement`](svgforeignobjectelement)
* [`SVGGElement`](svggelement)
* [`SVGGeometryElement`](svggeometryelement)
* [`SVGGlyphElement`](svgglyphelement)  Deprecated
* [`SVGGlyphRefElement`](svgglyphrefelement)  Deprecated
* [`SVGGradientElement`](svggradientelement)
* [`SVGGraphicsElement`](svggraphicselement)
* `SVGHatchElement`  Experimental
* `SVGHatchpathElement`  Experimental
* [`SVGHKernElement`](svghkernelement)  Deprecated
* [`SVGImageElement`](svgimageelement)
* [`SVGLinearGradientElement`](svglineargradientelement)
* [`SVGLineElement`](svglineelement)
* [`SVGMarkerElement`](svgmarkerelement)  Experimental
* [`SVGMaskElement`](svgmaskelement)
* [`SVGMetadataElement`](svgmetadataelement)
* [`SVGMissingGlyphElement`](svgmissingglyphelement)  Deprecated
* [`SVGMPathElement`](svgmpathelement)
* [`SVGPathElement`](svgpathelement)
* [`SVGPatternElement`](svgpatternelement)
* [`SVGPolylineElement`](svgpolylineelement)
* [`SVGPolygonElement`](svgpolygonelement)
* [`SVGRadialGradientElement`](svgradialgradientelement)
* [`SVGRectElement`](svgrectelement)
* [`SVGScriptElement`](svgscriptelement)
* [`SVGSetElement`](svgsetelement)
* [`SVGStopElement`](svgstopelement)
* [`SVGStyleElement`](svgstyleelement)
* [`SVGSVGElement`](svgsvgelement)
* [`SVGSwitchElement`](svgswitchelement)
* [`SVGSymbolElement`](svgsymbolelement)
* [`SVGTextContentElement`](svgtextcontentelement)
* [`SVGTextElement`](svgtextelement)
* [`SVGTextPathElement`](svgtextpathelement)
* [`SVGTextPositioningElement`](svgtextpositioningelement)
* [`SVGTitleElement`](svgtitleelement)
* [`SVGTRefElement`](svgtrefelement)  Deprecated
* [`SVGTSpanElement`](svgtspanelement)
* [`SVGUseElement`](svguseelement)
* [`SVGViewElement`](svgviewelement)
* [`SVGVKernElement`](svgvkernelement)  Deprecated

### SVG data type interfaces



Here are the DOM APIs for data types used in the definitions of SVG properties and attributes.

 #### Static type

 * [`SVGAngle`](svgangle)
* `SVGColor`  Deprecated
* `SVGICCColor`  Deprecated
* `SVGElementInstance`
* `SVGElementInstanceList`
* [`SVGLength`](svglength)
* [`SVGLengthList`](svglengthlist)
* `SVGNameList`
* [`SVGNumber`](svgnumber)
* [`SVGNumberList`](svgnumberlist)
* `SVGPaint`
* `SVGPathSeg`  Deprecated
* `SVGPathSegClosePath`  Deprecated
* `SVGPathSegMovetoAbs`  Deprecated
* `SVGPathSegMovetoRel`  Deprecated
* `SVGPathSegLinetoAbs`  Deprecated
* `SVGPathSegLinetoRel`  Deprecated
* `SVGPathSegCurvetoCubicAbs`  Deprecated
* `SVGPathSegCurvetoCubicRel`  Deprecated
* `SVGPathSegCurvetoQuadraticAbs`  Deprecated
* `SVGPathSegCurvetoQuadraticRel`  Deprecated
* `SVGPathSegArcAbs`  Deprecated
* `SVGPathSegArcRel`  Deprecated
* `SVGPathSegLinetoHorizontalAbs`  Deprecated
* `SVGPathSegLinetoHorizontalRel`  Deprecated
* `SVGPathSegLinetoVerticalAbs`  Deprecated
* `SVGPathSegLinetoVerticalRel`  Deprecated
* `SVGPathSegCurvetoCubicSmoothAbs`  Deprecated
* `SVGPathSegCurvetoCubicSmoothRel`  Deprecated
* `SVGPathSegCurvetoQuadraticSmoothAbs`  Deprecated
* `SVGPathSegCurvetoQuadraticSmoothRel`  Deprecated
* `SVGPathSegList`  Deprecated
* [`SVGPoint`](svgpoint)  Deprecated
* [`SVGPointList`](svgpointlist)  Deprecated
* [`SVGPreserveAspectRatio`](svgpreserveaspectratio)
* [`SVGRect`](svgrect)  Deprecated
* [`SVGStringList`](svgstringlist)
* [`SVGTransform`](svgtransform)
* [`SVGTransformList`](svgtransformlist)

 #### Animated type

 * [`SVGAnimatedAngle`](svganimatedangle)
* [`SVGAnimatedBoolean`](svganimatedboolean)
* [`SVGAnimatedEnumeration`](svganimatedenumeration)
* [`SVGAnimatedInteger`](svganimatedinteger)
* [`SVGAnimatedLength`](svganimatedlength)
* [`SVGAnimatedLengthList`](svganimatedlengthlist)
* [`SVGAnimatedNumber`](svganimatednumber)
* [`SVGAnimatedNumberList`](svganimatednumberlist)
* `SVGAnimatedPathData`  Deprecated
* [`SVGAnimatedPoints`](svgpolygonelement)
* [`SVGAnimatedPreserveAspectRatio`](svganimatedpreserveaspectratio)
* [`SVGAnimatedRect`](svganimatedrect)
* [`SVGAnimatedString`](svganimatedstring)
* [`SVGAnimatedTransformList`](svganimatedtransformlist)



### SMIL-related interfaces


* `ElementTimeControl`
* [`TimeEvent`](timeevent)

### Other SVG interfaces


* `GetSVGDocument`
* `ShadowAnimation`
* `SVGColorProfileRule`  Deprecated
* `SVGCSSRule`  Deprecated
* `SVGDocument`
* `SVGException`  Deprecated
* `SVGFitToViewBox`
* `SVGLocatable`  Deprecated
* [`SVGRenderingIntent`](svgrenderingintent)  Deprecated
* [`SVGUnitTypes`](svgunittypes)
* `SVGUseElementShadowRoot`
* `SVGViewSpec`  Deprecated
* `SVGZoomEvent`  Deprecated

Specifications
--------------




| Specification |
| --- |
| [DOM Standard](https://dom.spec.whatwg.org/)  |


See also
--------


* [DOM Examples](document_object_model/examples)
* [CSS Object Model (CSSOM)](css_object_model)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model>

Device orientation events
=========================


Device orientation events are events that allow you to [detect a device's physical orientation](device_orientation_events/detecting_device_orientation#processing_motion_events), as well as allowing you to [detect the device's motion](device_orientation_events/detecting_device_orientation#processing_motion_events).


Concepts and usage
------------------



Mobile devices commonly have sensors such as gyroscopes, compasses, and accelerometers that can enable applications running on the device to detect the device's orientation and motion.

 The device orientation events enable you to write web applications that can change their behavior based on the orientation of the user's device, and that can react when the user moves their device.

 Some typical features for which you might want to use the device orientation events include:

 * in web-based games, to enable the user to control the motion of characters or objects in the game by tilting and moving the device
* in mapping applications, to re-orient a map based on the device's position, or to provide turn-by-turn directions that update with the user's movements
* for gesture recognition — for example, recognizing a "shake" gesture and using it to perform some action such as clearing an input area when the user shakes the device



Interfaces
----------


 [`DeviceOrientationEvent`](deviceorientationevent)  Represents changes in the physical orientation of a device.

  [`DeviceMotionEvent`](devicemotionevent)  Represents changes in the acceleration of a device, as well as the rotation rate.

  [`DeviceMotionEventAcceleration`](devicemotioneventacceleration)  Represents the amount of acceleration the device is experiencing along all three axes

  [`DeviceMotionEventRotationRate`](devicemotioneventrotationrate)  Represents the rate at which the device is rotating around all three axes.

  
Events
------


 [`deviceorientation`](window/deviceorientation_event)  Fired when fresh data is available from the device about the current orientation of the device as compared to the Earth coordinate frame.

  [`devicemotion`](window/devicemotion_event)  Fired at a regular interval to indicate the amount of physical force of acceleration the device is receiving at that time, and the rate of rotation of the device.

  [`deviceorientationabsolute`](window/deviceorientationabsolute_event)  Fired when absolute device orientation changes.

  
Specifications
--------------




| Specification |
| --- |
| [DeviceOrientation Event Specification # deviceorientation](https://w3c.github.io/deviceorientation/#deviceorientation) |
| [DeviceOrientation Event Specification # ref-for-dom-window-ondeviceorientation](https://w3c.github.io/deviceorientation/#ref-for-dom-window-ondeviceorientation) |
| [DeviceOrientation Event Specification # devicemotion](https://w3c.github.io/deviceorientation/#devicemotion) |
| [DeviceOrientation Event Specification # ref-for-dom-window-ondevicemotion](https://w3c.github.io/deviceorientation/#ref-for-dom-window-ondevicemotion) |
| [DeviceOrientation Event Specification # dom-window-ondeviceorientationabsolute](https://w3c.github.io/deviceorientation/#dom-window-ondeviceorientationabsolute) |
| [DeviceOrientation Event Specification # devicemotioneventacceleration](https://w3c.github.io/deviceorientation/#devicemotioneventacceleration) |
| [DeviceOrientation Event Specification # devicemotioneventrotationrate](https://w3c.github.io/deviceorientation/#devicemotioneventrotationrate) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Device_orientation_events` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |
| `alpha` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |
| `beta` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |
| `gamma` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Device_orientation_events` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |
| `x` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |
| `y` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |
| `z` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DeviceMotionEvent` | 59 | 14 | 29 | No | 46 | No | 59 | 59 | 29 | 43 | No | 7.0 |
| `Device_orientation_events` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |
| `acceleration` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |
| `accelerationIncludingGravity` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |
| `interval` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |
| `requestPermission` | No | No | No | No | No | No | No | No | No | No | 14.5 | No |
| `rotationRate` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DeviceOrientationEvent` | 59 | 14 | 17 | No | 46 | No | 59 | 59 | 17 | 43 | No | 7.0 |
| `Device_orientation_events` | 7Before version 50, Chrome provided absolute values instead of relative values for this event. Developers still needing absolute values may use the `deviceorientationabsolute` event. | 12 | 6Firefox 3.6, 4, and 5 supported `mozOrientation` instead of the standard DeviceOrientationEvent interface. | 11 | 15 | No | 3Before version 50, Chrome provided absolute values instead of relative values for this event. Developers still needing absolute values may use the `deviceorientationabsolute` event. | 18Before version 50, Chrome provided absolute values instead of relative values for this event. Developers still needing absolute values may use the `deviceorientationabsolute` event. | 6Firefox 3.6, 4, and 5 supported `mozOrientation` instead of the standard DeviceOrientationEvent interface. | 14 | 4.2 | 1.0Before Samsung Internet 5.0, Samsung Internet provided absolute values instead of relative values for this event. Developers still needing absolute values may use the `deviceorientationabsolute` event. |
| `absolute` | 7 | 12 | 6 | 11 | 15 | No | 4.4 | 18 | 6 | 14 | No | 1.0 |
| `alpha` | 7 | 12 | 6 | 11 | 15 | No | 3 | 18 | 6 | 14 | 4.2 | 1.0 |
| `beta` | 7 | 12 | 6 | 11 | 15 | No | 3 | 18 | 6 | 14 | 4.2 | 1.0 |
| `gamma` | 7 | 12 | 6 | 11 | 15 | No | 3 | 18 | 6 | 14 | 4.2 | 1.0 |
| `requestPermission` | No | No | No | No | No | No | No | No | No | No | 14.5 | No |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Device_orientation_events` | 50 | 79 | No | No | 37 | No | 50 | 50 | No | 37 | No | 5.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Device_orientation_events` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Device_orientation_events` | 7 | 12 | 63.6–6 | 11 | 12 | No | 3 | 18 | 64–6 | 12 | 4.2 | 1.0 |


### api.Window.deviceorientation\_event


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.Window.devicemotion\_event


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.Window.deviceorientationabsolute\_event


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.DeviceOrientationEvent


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.DeviceMotionEvent


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.DeviceMotionEventAcceleration


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.DeviceMotionEventRotationRate


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


See also
--------


* [Device Orientation & Motion](https://web.dev/native-hardware-device-orientation/) at web.dev


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Device_orientation_events>

Encoding API
============



The **Encoding API** provides a mechanism for handling text in various [character encodings](https://developer.mozilla.org/en-US/docs/Glossary/Character_encoding), including legacy non-[UTF-8](https://developer.mozilla.org/en-US/docs/Glossary/UTF-8) encodings.

 The API provides four interfaces: [`TextDecoder`](textdecoder), [`TextEncoder`](textencoder), [`TextDecoderStream`](textdecoderstream) and [`TextEncoderStream`](textencoderstream).


 **Note:** This feature is available in [Web Workers](web_workers_api)

 

Interfaces
----------


* [`TextDecoder`](textdecoder)
* [`TextEncoder`](textencoder)
* [`TextDecoderStream`](textdecoderstream)
* [`TextEncoderStream`](textencoderstream)

Specifications
--------------




| Specification |
| --- |
| [Encoding Standard # interface-textdecoder](https://encoding.spec.whatwg.org/#interface-textdecoder) |
| [Encoding Standard # interface-textencoder](https://encoding.spec.whatwg.org/#interface-textencoder) |
| [Encoding Standard # interface-textencoderstream](https://encoding.spec.whatwg.org/#interface-textencoderstream) |
| [Encoding Standard # interface-textdecoderstream](https://encoding.spec.whatwg.org/#interface-textdecoderstream) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `TextDecoderStream` | 71 | 79 | 105 | No | 58 | 14.1 | 71 | 71 | 105 | 50 | 14.5 | 10.0 |
| `Encoding_API` | 71 | 79 | 105 | No | 58 | 14.1 | 71 | 71 | 105 | 50 | 14.5 | 10.0 |
| `encoding` | 71 | 79 | 105 | No | 58 | 14.1 | 71 | 71 | 105 | 50 | 14.5 | 10.0 |
| `fatal` | 71 | 79 | 105 | No | 58 | 14.1 | 71 | 71 | 105 | 50 | 14.5 | 10.0 |
| `ignoreBOM` | 71 | 79 | 105 | No | 58 | 14.1 | 71 | 71 | 105 | 50 | 14.5 | 10.0 |
| `readable` | 71 | 79 | 105 | No | 58 | 14.1 | 71 | 71 | 105 | 50 | 14.5 | 10.0 |
| `writable` | 71 | 79 | 105 | No | 58 | 14.1 | 71 | 71 | 105 | 50 | 14.5 | 10.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `TextEncoderStream` | 71 | 79 | 105 | No | 58 | 14.1 | 71 | 71 | 105 | 50 | 14.5 | 10.0 |
| `Encoding_API` | 71 | 79 | 105 | No | 58 | 14.1 | 71 | 71 | 105 | 50 | 14.5 | 10.0 |
| `encoding` | 71 | 79 | 105 | No | 58 | 14.1 | 71 | 71 | 105 | 50 | 14.5 | 10.0 |
| `readable` | 71 | 79 | 105 | No | 58 | 14.1 | 71 | 71 | 105 | 50 | 14.5 | 10.0 |
| `writable` | 71 | 79 | 105 | No | 58 | 14.1 | 71 | 71 | 105 | 50 | 14.5 | 10.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `TextEncoder` | 38 | 79 | 18 | No | 25 | 10.1 | 38 | 38 | 18 | 25 | 10.3 | 3.0 |
| `Encoding_API` | 38 | 79 | 18 | No | 25 | 10.1 | 38 | 38 | 18 | 25 | 10.3 | 3.0 |
| `encode` | 38 | 79 | 18 | No | 25 | 10.1 | 38 | 38 | 18 | 25 | 10.3 | 3.0 |
| `encodeInto` | 74 | 79 | 66 | No | 62 | 14.1 | 74 | 74 | 66 | 50 | 14.5 | 11.0 |
| `encoding` | 38 | 79 | 18 | No | 25 | 10.1 | 38 | 38 | 18 | 25 | 10.3 | 3.0 |
| `worker_support` | 38 | 79 | 20 | No | 25 | 10.1 | 38 | 38 | 20 | 25 | 10.3 | 3.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `TextDecoder` | 38 | 79 | 1918Implemented a slightly different version of the spec. | No | 25 | 10.1 | 38 | 38 | 1918Implemented a slightly different version of the spec. | 25 | 10.3 | 3.0 |
| `Encoding_API` | 38 | 79 | 1918Implemented a slightly different version of the spec. | No | 25 | 10.1 | 38 | 38 | 1918Implemented a slightly different version of the spec. | 25 | 10.3 | 3.0 |
| `decode` | 38 | 79 | 1918Implemented a slightly different version of the spec. | No | 25 | 10.1 | 38 | 38 | 1918Implemented a slightly different version of the spec. | 25 | 10.3 | 3.0 |
| `encoding` | 38 | 79 | 1918Implemented a slightly different version of the spec. | No | 25 | 10.1 | 38 | 38 | 1918Implemented a slightly different version of the spec. | 25 | 10.3 | 3.0 |
| `fatal` | 38 | 79 | 36 | No | 25 | 10.1 | 38 | 38 | 36 | 25 | 10.3 | 3.0 |
| `ignoreBOM` | 38 | 79 | 63 | No | 25 | 10.1 | 38 | 38 | 63 | 25 | 10.3 | 3.0 |
| `worker_support` | 38 | 79 | 20 | No | 25 | 10.1 | 38 | 38 | 20 | 25 | 10.3 | 3.0 |


### api.TextDecoder


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.TextEncoder


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.TextEncoderStream


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.TextDecoderStream


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


See also
--------


* [Encoding API Encodings](encoding_api/encodings) - Encodings that must be supported for decoding text.
* A [polyfill](https://github.com/inexorabletash/text-encoding) allowing to use this interface in browsers that don't support it


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Encoding_API>

Encrypted Media Extensions API
==============================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The Encrypted Media Extensions API provides interfaces for controlling the playback of content which is subject to a digital restrictions management scheme.

 Access to this API is provided through [`Navigator.requestMediaKeySystemAccess()`](navigator/requestmediakeysystemaccess).



Interfaces
----------


 [`MediaEncryptedEvent`](mediaencryptedevent)  Represents a specific [`encrypted`](htmlmediaelement/encrypted_event) event thrown when a [`HTMLMediaElement`](htmlmediaelement) encounters some initialization data.

  [`MediaKeyMessageEvent`](mediakeymessageevent)  Contains the content and related data when the content decryption module (CDM) generates a message for the session.

  [`MediaKeys`](mediakeys)  Represents a set of keys that an associated [`HTMLMediaElement`](htmlmediaelement) can use for decryption of media data during playback.

  [`MediaKeySession`](mediakeysession)  Represents a context for message exchange with a content decryption module (CDM).

  [`MediaKeyStatusMap`](mediakeystatusmap)  A read-only map of media key statuses by key IDs.

  [`MediaKeySystemAccess`](mediakeysystemaccess)  Provides access to a key system for decryption and/or a content protection provider.

  
Specifications
--------------




| Specification |
| --- |
| [Encrypted Media Extensions # navigator-extension-requestmediakeysystemaccess](https://w3c.github.io/encrypted-media/#navigator-extension-requestmediakeysystemaccess) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Encrypted_Media_Extensions_API` | 42["The spec requires that the passed `supportedConfigurations` option contain at least one of `audioCapabilities` or `videoCapabilities`, and that said parameters include a codec string.", "The function does not exist in insecure contexts. This was not enforced until Chrome 58."] | 13 | 38["Starting in Firefox 55, if neither `audioCapabilities` nor `videoCapabilities` is specified in `supportedConfigurations`, a warning is output to the web console.", "In addition, starting in Firefox 55, if in `supportedConfigurations`, either `audioCapabilities`'s or `videoCapabilities`'s `contentType` value doesn't specify a `\"codecs\"` substring to define allowed codecs within the media wrapper, a warning is output to the web console. See note below table for example and correction.", "In the future, if neither `audioCapabilities` nor `videoCapabilities` is specified in the `supportedConfigurations`, a `NotSupported` exception will be thrown."] | No | 29["The spec requires that the passed `supportedConfigurations` option contain at least one of `audioCapabilities` or `videoCapabilities`, and that said parameters include a codec string.", "The function does not exist in insecure contexts. This was not enforced until Opera 45."] | 12.1 | 43["The spec requires that the passed `supportedConfigurations` option contain at least one of `audioCapabilities` or `videoCapabilities`, and that said parameters include a codec string.", "The function does not exist in insecure contexts. This was not enforced until version 58."] | 42["The spec requires that the passed `supportedConfigurations` option contain at least one of `audioCapabilities` or `videoCapabilities`, and that said parameters include a codec string.", "The function does not exist in insecure contexts. This was not enforced until Chrome 58."] | 38["Starting in Firefox 55, if neither `audioCapabilities` nor `videoCapabilities` is specified in `supportedConfigurations`, a warning is output to the web console.", "In addition, starting in Firefox 55, if in `supportedConfigurations`, either `audioCapabilities`'s or `videoCapabilities`'s `contentType` value doesn't specify a `\"codecs\"` substring to define allowed codecs within the media wrapper, a warning is output to the web console. See note below table for example and correction.", "In the future, if neither `audioCapabilities` nor `videoCapabilities` is specified in the `supportedConfigurations`, a `NotSupported` exception will be thrown."] | 29["The spec requires that the passed `supportedConfigurations` option contain at least one of `audioCapabilities` or `videoCapabilities`, and that said parameters include a codec string.", "The function does not exist in insecure contexts. This was not enforced until Opera 45."] | 12.2 | 4.0["The spec requires that the passed `supportedConfigurations` option contain at least one of `audioCapabilities` or `videoCapabilities`, and that said parameters include a codec string.", "The function does not exist in insecure contexts. This was not enforced until Samsung Internet 7.0."] |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API>

Federated Credential Management API (FedCM)
===========================================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The **Federated Credential Management API** (or *FedCM API*) provides a standard mechanism for identity providers to enable identity federation services in a privacy-preserving way without relying on third-party cookies and redirects, and a JavaScript API for sites that depend on those services for sign-in functionality to make use of them.



FedCM concepts
--------------



Identity federation is the delegation of user authentication from a website that requires user sign-in such as an e-commerce or social networking site (also known as a relying party or RP) to a trusted third party identity provider (IdP). Users will sign up an account with the IdP, which can then be used to sign-in to one or more RPs. Identity federation via a small set of dedicated identity providers has improved web authentication in terms of security, consumer confidence, and user experience, versus having every site handling their own sign-in needs with a separate username and password.

 The problem is that traditional identity federation relies on [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe)s, redirects, and third-party cookies, which are also used for third-party tracking. Browsers are limiting the usage of these features in an effort to preserve user privacy, but a side effect is that this makes valid, non-tracking uses more difficult to implement, and this includes identity federation.

 Affected identity federation use cases that rely on third-party cookies:

 * [OIDC front-channel logout](https://openid.net/specs/openid-connect-frontchannel-1_0.html): This flow requires the IDP to embed several RP `<iframe>`s, which rely on RP cookies.
* Social Widgets: In order to provide social widgets, the IdP third-party cookie must be provided from the RP top-level origin.
* Personalized buttons: The display of personalized sign in information on a [`<button>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button) in the RP origin is implemented as an IdP `<iframe>` that requires third party cookies.
* Session Refresh without top-level navigation or popups.

 FedCM aims to work around this problem, providing a dedicated mechanism for federated identity flows on the web, and enabling supporting browsers to provide special UI elements on RPs, allowing users to choose an IdP account to use for sign-in.

 There are two sides to using the FedCM API — IdP integration with FedCM, and RP sign-in using the JavaScript API.



IdP integration with FedCM
--------------------------



To integrate with FedCM, an identity provider needs to do the following:

 1. Provide a well-known file to identify the IdP.
2. Provide a config file and endpoints for accounts list and assertion issuance (and optionally, client metadata).



### Provide a well-known file



There is a potential privacy issue whereby an [IdP is able to discern whether a user visited an RP without explicit consent](https://github.com/fedidcg/FedCM/issues/230). This has tracking implications, so an IdP is required to provide a well-known file to verify its identity and mitigate this issue.

 The well-known file must be served from the [eTLD+1](https://web.dev/same-site-same-origin/#site) of the IdP at `/.well-known/web-identity`.

 For example, if the IdP endpoints are served under `https://accounts.idp.example/`, they must serve a well-known file at `https://idp.example/.well-known/web-identity`. The well-known file's content should have the following JSON structure:

 
```
{
  "provider\_urls": ["https://accounts.idp.example/config.json"]
}

```
 The `provider_urls` member should contain an array of URLs pointing to valid IdP config files that can be used by RPs to interact with the IdP. The array length is current limited to one.



### Provide a config file



The IdP config file provides a list of the endpoints required by the browser to process the identity federation flow and sign the user in. IdPs will host this config file and the required endpoints.

 The config file (hosted at `https://accounts.idp.example/config.json` in our example) should have the following JSON structure:

 
```
{
  "accounts\_endpoint": "/accounts.php",
  "client\_metadata\_endpoint": "/client\_metadata.php",
  "id\_assertion\_endpoint": "/assertion.php",
  "branding": {
    "background\_color": "green",
    "color": "0xFFEEAA",
    "icons": [
      {
        "url": "https://idp.example/icon.ico",
        "size": 25
      }
    ]
  }
}

```
 The properties are as follows:

  `accounts_endpoint`  The URL for the accounts list endpoint, which returns a list of accounts that the user is currently signed in to on the IdP. The browser uses these to create a list of sign-in choices to show to the user in the sign-in UI.

  
`client_metadata_endpoint` Optional
  The URL for the client metadata endpoint, which provides URLs pointing to the RP's metadata and terms of service pages, to be used in the browser-supplied sign-in UI.

  `id_assertion_endpoint`  The URL for the ID assertion endpoint, which when sent valid user credentials should respond with a validation token that the RP can use to validate the authentication.

  
`branding` Optional
  Contains branding information that will be used in the browser-supplied sign-in UI to customize its appearance as desired by the IdP.

   #### The accounts list endpoint

 This endpoint returns a list of all the IdP accounts that the user is currently signed in with, with a JSON structure that matches the following:

 
```
{
 "accounts": [{
   "id": "1234",
   "given\_name": "John",
   "name": "John Doe",
   "email": "john\_doe@idp.example",
   "picture": "https://idp.example/profile/123",
   "approved\_clients": ["123", "456", "789"],
  }, {
   "id": "5678",
   "given\_name": "Johnny",
   "name": "Johnny",
   "email": "johnny@idp.example",
   "picture": "https://idp.example/profile/456"
   "approved\_clients": ["abc", "def", "ghi"],
  }]
}

```
 This includes the following information:

  `id`  The unique ID of the user.

  `name`  The family name of the user.

  `email`  The email address of the user.

  
`given_name` Optional
  The given name of the user.

  
`picture` Optional
  The URL of the user's avatar image.

  
`approved_clients` Optional
  An array of RP clients that the user has registered with.

    **Note:**: If the user is not signed in to any IdP accounts, the endpoint should respond with [HTTP 401 (Unauthorized)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401).

  #### The client metadata endpoint

 Provides URLs pointing to the RP's metadata and terms of service pages, to be used in the browser-supplied sign-in UI. This should follow the JSON structure seen below:

 
```
{
  "privacy\_policy\_url": "https://rp.example/privacy\_policy.html",
  "terms\_of\_service\_url": "https://rp.example/terms\_of\_service.html"
}

```
 #### The ID assertion endpoint

 When sent valid user credentials, this endpoint should respond with a validation token that the RP can use to validate the authentication:

 
```
{
  "token": "\*\*\*\*\*\*\*\*\*\*\*"
}

```


RP sign-in using the JavaScript API
-----------------------------------



RPs can call [`navigator.credentials.get()`](credentialscontainer/get) with an `identity` option to make a request for users to sign in to the RP with the IdP, using the available IdP config and endpoints (as described above). A typical request would look like this:

 
```
async function signIn() {
  const identityCredential = await navigator.credentials.get({
    identity: {
      providers: [
        {
          configURL: "https://accounts.idp.example/config.json",
          clientId: "\*\*\*\*\*\*\*\*",
          nonce: "\*\*\*\*\*\*",
        },
      ],
    },
  });
}

```
 The `identity.providers` property takes an array of objects containing the path to an IdP config file, the RP's client identifier issued by the IdP, and an optional random nonce that ensures the response is issued for this specific request, preventing [replay attacks](https://developer.mozilla.org/en-US/docs/Glossary/Replay_attack).

 The browser requests the IdP config file and carries out the sign-in flow detailed below. For more information on the kind of interaction a user might expect from the browser-supplied UI, see [Sign in to the relying party with the identity provider](https://developer.chrome.com/docs/privacy-sandbox/fedcm/#sign-into-rp).



### FedCM sign-in flow



1. The RP invokes [`navigator.credentials.get()`](credentialscontainer/get) to start off the sign-in flow.
2. From the `configURL` provided in the `get()` call, the browser requests two files:
	1. The well-known file (`/.well-known/web-identity`), available from `/.well-known/web-identity` at the [eTLD+1](https://web.dev/same-site-same-origin/#site) of the `configURL`.
	2. The config file (`/config.json`), available at the `configURL`.These are both a [`GET`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET) requests, which don't have cookies and don't follow redirects. This effectively prevents the IdP from learning who made the request and which RP is attempting to connect. For example, the config file request would look like so: 
```
GET /config.json HTTP/1.1
Host: accounts.idp.example
Accept: application/json
Sec-Fetch-Dest: webidentity

```
  **Note:** All requests sent from the browser via FedCM include a `Sec-Fetch-Dest: webidentity` header to prevent [CSRF](https://developer.mozilla.org/en-US/docs/Glossary/CSRF) attacks. All IdP endpoints must confirm this header is included.
3. The IdP responds with the requested files. The config file URL is validated against the list of valid config URLs inside the well-known file.
4. The browser makes a request to the `accounts_endpoint` inside the config file for the list of accounts that the user is currently signed in to on the IdP. This is a `GET` request with cookies, but without a `client_id` parameter or the [`Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin) header. This effectively prevents the IdP from learning which RP the user is trying to sign in to. For example: 
```
GET /accounts.php HTTP/1.1
Host: accounts.idp.example
Accept: application/json
Cookie: 0x23223
Sec-Fetch-Dest: webidentity

```
5. The IdP responds with the account information.
6. Optional If included in the config file, the browser makes a request to the `client_metadata_endpoint` for the location of the RP's terms of service and privacy policy pages. This is a `GET` request sent with the `clientId` passed into the `get()` call included as a parameter, and without cookies. For example: 
```
GET /client\_metadata.php?client\_id=1234 HTTP/1.1
Host: accounts.idp.example
Origin: https://rp.example/
Accept: application/json
Sec-Fetch-Dest: webidentity

```
7. Optional The IdP responds with the requested URLs.
8. The browser uses the information obtained by the previous two requests to create the UI asking the user for permission to sign in to the RP using their federated IdP account.
9. If the user grants permission to do so, the browser sends some credentials to the `id_assertion_endpoint` and requests a validation token from the IdP. The credentials are sent in an HTTP [`POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) request with cookies and a content type of `application/x-www-form-urlencoded`. It should look something like this: 
```
POST /assertion.php HTTP/1.1
Host: accounts.idp.example
Origin: https://rp.example/
Content-Type: application/x-www-form-urlencoded
Cookie: 0x23223
Sec-Fetch-Dest: webidentity
account_id=123&client_id=client1234&nonce=Ct60bD&disclosure_text_shown=true

```
The payload should contain the following:  `client_id`  The RP's client identifier.

  `account_id`  The unique ID of the user to be signed in.

  
`nonce` Optional
  The request nonce, provided by the RP.

  `disclosure_text_shown`  A string of "true" or "false" indicating whether the disclosure text was shown or not. The disclosure text is the information shown to the user (which can include the terms of service and privacy policy links, if provided) if the user is signed in to the IdP but doesn't have an account specifically on the current RP (in which case they'd need to choose to "Continue as..." their IdP identity and then create a corresponding account on the RP).
10. The IdP checks that the account ID sent by the RP matches the ID for the account that is already signed in, and that the `Origin` matches the origin of the RP, which will have been registered in advance with the IdP. If everything looks good, it responds with the validation token.

  **Note:** The origin of the RP will be registered with the IdP in a completely separate process when the RP first integrates with the IdP. This process will be specific to each IdP.

  When the flow is complete, the RP validates the validation token. If validation is successful, the `get()` promise resolves with an [`IdentityCredential`](identitycredential) object, which provides further RP functionality. Additionally, at this point the RP may register the user or let them sign in and start a new session.



### Features available via IdentityCredential


The [`IdentityCredential`](identitycredential) object obtained from a successful FedCM sign-in provides access to the token used to validate the sign-in (see [`IdentityCredential.token`](identitycredential/token)).


Permissions Policy integration and IFrame support
-------------------------------------------------



The [`identity-credentials-get`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy/identity-credentials-get) [Permissions-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy) can be used to control permission to use FedCM, more specifically usage of the [`navigator.credentials.get()`](credentialscontainer/get) method.

 Developers can explicitly grant permission for an [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe) to use FedCM via the `allow` attribute:

 
```
<iframe src="3rd-party.example" allow="identity-credentials-get"></iframe>

```
 The availability of FedCM within `<iframe>`s enables a couple of use cases:

 * Larger sites won't want a third-party sign-in script to gain control over the top-level frame; instead they will want to add that script and invoke FedCM from within an [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe).
* Some `<iframes>` may themselves require federated sign-in.



Interfaces
----------


 [`IdentityCredential`](identitycredential)  Represents a user identity credential arising from a successful federated sign-in. A successful [`navigator.credentials.get()`](credentialscontainer/get) call that includes an `identity` option fulfills with an [`IdentityCredential`](identitycredential) instance.

  
Extensions to other interfaces
------------------------------


 
[`CredentialsContainer.get()`](credentialscontainer/get), the `identity` option.  `identity` is an object containing details of federated identity providers (IdPs) that a relying party (RP) website can use to sign users in. Causes a `get()` call to initiate a request for a user to sign in to a RP with an IdP.

  
Examples
--------


* [FedCM sign-in example](https://fedcm-rp-demo.glitch.me/)
	+ [RP source code](https://glitch.com/edit/#!/fedcm-rp-demo?path=server.js%3A1%3A0)
	+ [IdP source code](https://glitch.com/edit/#!/fedcm-idp-demo?path=server.js%3A1%3A0)
* [FedCM `<iframe>` sign-in](https://fedcm-main-frame.glitch.me/)
	+ [RP `<iframe>` page source code](https://glitch.com/edit/#!/fedcm-main-frame?path=index.html%3A1%3A0)
	+ [IdP source code](https://glitch.com/edit/#!/webid-fcm-idp-single?path=server.js%3A1%3A0)

Specifications
--------------




| Specification |
| --- |
| [Federated Credential Management API # browser-api-identity-credential-interface](https://fedidcg.github.io/FedCM/#browser-api-identity-credential-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FedCM_API` | 108 | 108 | No | No | 94 | No | 108 | 108 | No | 73 | No | No |
| `token` | 108 | 108 | No | No | 94 | No | 108 | 108 | No | 73 | No | No |


See also
--------


* [Federated Credential Management API](https://developer.chrome.com/docs/privacy-sandbox/fedcm/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FedCM_API>

Fetch API
=========



The Fetch API provides an interface for fetching resources (including across the network). It is a more powerful and flexible replacement for [`XMLHttpRequest`](xmlhttprequest).


 **Note:** This feature is available in [Web Workers](web_workers_api)

 

Concepts and usage
------------------



The Fetch API uses [`Request`](request) and [`Response`](response) objects (and other things involved with network requests), as well as related concepts such as CORS and the HTTP Origin header semantics.

 For making a request and fetching a resource, use the [`fetch()`](fetch) method. It is a global method in both [`Window`](window) and [`Worker`](workerglobalscope) contexts. This makes it available in pretty much any context you might want to fetch resources in.

 The `fetch()` method takes one mandatory argument, the path to the resource you want to fetch. It returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to the [`Response`](response) to that request — as soon as the server responds with headers — **even if the server response is an HTTP error status**. You can also optionally pass in an `init` options object as the second argument (see [`Request`](request)).

 Once a [`Response`](response) is retrieved, there are a number of methods available to define what the body content is and how it should be handled.

 You can create a request and response directly using the [`Request()`](request/request) and [`Response()`](response/response) constructors, but it's uncommon to do this directly. Instead, these are more likely to be created as results of other API actions (for example, [`FetchEvent.respondWith()`](fetchevent/respondwith) from service workers).

 Find out more about using the Fetch API features in [Using Fetch](fetch_api/using_fetch), and study concepts in [Fetch basic concepts](fetch_api/basic_concepts).



Fetch Interfaces
----------------


 [`fetch()`](fetch)  The `fetch()` method used to fetch a resource.

  [`Headers`](headers)  Represents response/request headers, allowing you to query them and take different actions depending on the results.

  [`Request`](request)  Represents a resource request.

  [`Response`](response)  Represents the response to a request.

  
Specifications
--------------




| Specification |
| --- |
| [Fetch Standard # fetch-method](https://fetch.spec.whatwg.org/#fetch-method) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Fetch_API` | 42 | 14 | 39 | No | 29 | 10.1 | 42 | 42 | 39 | 29 | 10.3 | 4.0 |
| `authorization_removed_cross_origin` | No | No | 111 | No | No | 16.1 | No | No | 111 | No | 16.1 | No |
| `blob_data_support` | 48 | 79 | 39 | No | 35 | 10.1 | 43 | 48 | 39 | 35 | 10.3 | 5.0 |
| `init_keepalive_parameter` | 66 | 15 | No | No | 43 | 13 | 66 | 66 | No | 43 | 13 | 9.0 |
| `init_referrerPolicy_parameter` | 52 | 79 | 52 | No | 39 | 11.1 | 52 | 52 | 52 | 41 | No | 6.0 |
| `init_signal_parameter` | 66 | 16 | 57 | No | 53 | 11.1 | 66 | 66 | 57 | 47 | 11.3 | 9.0 |
| `worker_support` | 42 | 14 | 39 | No | 29 | 10.1 | 42 | 42 | 39 | 29 | 10.3 | 4.0 |


See also
--------


* [Using Fetch](fetch_api/using_fetch)
* [Service Worker API](service_worker_api)
* [HTTP access control (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)
* [HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP)
* [Fetch polyfill](https://github.com/github/fetch)
* [Fetch basic concepts](fetch_api/basic_concepts)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API>

File API
========


Concepts and Usage
------------------



The File API enables web applications to access files and their contents.

 Web applications can access files when the user makes them available, either using a [file `<input>` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file) or [via drag and drop](datatransfer/files).

 Sets of files made available in this way are represented as [`FileList`](filelist) objects, which enable a web application to retrieve individual [`File`](file) objects. In turn [`File`](file) objects provide access to metadata such as the file's name, size, type, and last modified date.

 [`File`](file) objects can be passed to [`FileReader`](filereader) objects to access the contents of the file. The [`FileReader`](filereader) interface is asynchronous, but a synchronous version, available only in [web workers](web_workers_api), is provided by the [`FileReaderSync`](filereadersync) interface.



Interfaces
----------


 [`Blob`](blob)  Represents a "Binary Large Object", meaning a file-like object of immutable, raw data; a [`Blob`](blob) can be read as text or binary data, or converted into a [`ReadableStream`](readablestream) so its methods can be used for processing the data.

  [`File`](file)  Provides information about a file and allows JavaScript in a web page to access its content.

  [`FileList`](filelist)  Returned by the `files` property of the HTML [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) element; this lets you access the list of files selected with the `<input type="file">` element. It's also used for a list of files dropped into web content when using the drag and drop API; see the [`DataTransfer`](datatransfer) object for details on this usage.

  [`FileReader`](filereader)  Enables web applications to asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using [`File`](file) or [`Blob`](blob) objects to specify the file or data to read.

  [`FileReaderSync`](filereadersync)  Enables web applications to synchronously read the contents of files (or raw data buffers) stored on the user's computer, using [`File`](file) or [`Blob`](blob) objects to specify the file or data to read.

  
### Extensions to other interfaces


 [`URL.createObjectURL()`](url/createobjecturl)  Creates a URL that can be used to fetch a [`File`](file) or [`Blob`](blob) object.

  [`URL.revokeObjectURL()`](url/revokeobjecturl)  Releases an existing object URL which was previously created by calling [`URL.createObjectURL()`](url/createobjecturl).

  
Examples
--------


### Reading a file



In this example, we provide a [file `<input>` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file), and when the user selects a file, we read the contents of the first file selected as text, and display the result in a [`<div>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div).

 #### HTML

 
```
<input type="file" />
<div class="output"></div>

```
 #### CSS

 
```
.output {
  overflow: scroll;
  margin: 1rem 0;
  height: 200px;
}

```
 #### JavaScript

 
```
const fileInput = document.querySelector("input[type=file]");
const output = document.querySelector(".output");

fileInput.addEventListener("change", () => {
  const [file] = fileInput.files;
  if (file) {
    const reader = new FileReader();
    reader.addEventListener("load", () => {
      output.innerText = reader.result;
    });
    reader.readAsText(file);
  }
});

```


### Result



Specifications
--------------




| Specification |
| --- |
| [File API](https://w3c.github.io/FileAPI/)  |


See also
--------


* [`<input type="file">`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file): the file input element
* The [`DataTransfer`](datatransfer) interface


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/File_API>

File System Access API
======================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The File System Access API allows read, write and file management capabilities.



Concepts and Usage
------------------



This API allows interaction with files on a user's local device, or on a user-accessible network file system. Core functionality of this API includes reading files, writing or saving files, and access to directory structure.

 Most of the interaction with files and directories is accomplished through handles. A parent [`FileSystemHandle`](filesystemhandle) class helps define two child classes: [`FileSystemFileHandle`](filesystemfilehandle) and [`FileSystemDirectoryHandle`](filesystemdirectoryhandle), for files and directories respectively.

 The handles represent a file or directory on the user's system. You can first gain access to them by showing the user a file or directory picker using methods such as [`window.showOpenFilePicker()`](window/showopenfilepicker) and [`window.showDirectoryPicker()`](window/showdirectorypicker). Once these are called, the file picker presents itself and the user selects either a file or directory. Once this happens successfully, a handle is returned.

 You can also gain access to file handles via:

 * The [`DataTransferItem.getAsFileSystemHandle()`](datatransferitem/getasfilesystemhandle) method of the [HTML Drag and Drop API](html_drag_and_drop_api).
* The [File Handling API](https://developer.chrome.com/en/articles/file-handling/).

 Each handle provides its own functionality and there are a few differences depending on which one you are using (see the [interfaces](#interfaces) section for specific details). You then can access file data, or information (including children) of the directory selected. This API opens up potential functionality the web has been lacking. Still, security has been of utmost concern when designing the API, and access to file/directory data is disallowed unless the user specifically permits it.

  **Note:** The different exceptions that can be thrown when using the features of this API are listed on relevant pages as defined in the spec. However, the situation is made more complex by the interaction of the API and the underlying operating system. A proposal has been made to [list the error mappings in the spec](https://github.com/whatwg/fs/issues/57), which includes useful related information.

   **Note:** Objects based on [`FileSystemHandle`](filesystemhandle) can also be serialized into an [IndexedDB](indexeddb_api) database instance, or transferred via [`postMessage()`](window/postmessage).

 

### Origin private file system



The [origin private file system (OPFS)](https://fs.spec.whatwg.org/#origin-private-file-system) is a storage endpoint private to the origin of the page, providing optional access to a special kind of file that is highly optimized for performance, for example, by offering in-place and exclusive write access to a file's content.

 Storing data in the OPFS is similar to storing data in any other browser-provided storage mechanism that's private to the origin of the page (for example the [IndexedDB API](indexeddb_api)). This means that files in the OPFS differ from files selected using a picker in the following ways:

 * Permission prompts are not required to access files in the OPFS.
* Clearing data for the site deletes the OPFS.
* The OPFS is subject to browser quota restrictions.

 Files can be manipulated inside the OPFS via a three-step process:

 1. The [`StorageManager.getDirectory()`](storagemanager/getdirectory) method, which is obtained using [`navigator.storage.getDirectory()`](navigator/storage) in a worker or the main thread, returns a reference to a [`FileSystemDirectoryHandle`](filesystemdirectoryhandle) object allowing access to a directory and its contents — this represents the root of the OPFS.
2. The [`FileSystemDirectoryHandle.getFileHandle()`](filesystemdirectoryhandle/getfilehandle) method is invoked to return a [`FileSystemFileHandle`](filesystemfilehandle) object representing a handle to a specific file in the directory.
3. The [`createSyncAccessHandle()`](filesystemfilehandle/createsyncaccesshandle) method is invoked on that file handle, and returns a [`FileSystemSyncAccessHandle`](filesystemsyncaccesshandle) object that can be used to read and write to the file. This is a high-performance handle for *synchronous* read/write operations (the other handle types are asynchronous). The synchronous nature of this class brings performance advantages intended for use in contexts where asynchronous operations come with high overhead (for example, [WebAssembly](https://developer.mozilla.org/en-US/docs/WebAssembly)). Note that it is only usable inside dedicated [Web Workers](web_workers_api).

 While browsers typically implement this by persisting the contents of the OPFS to disk somewhere, it is not intended that the contents be easily user-accessible. While the browser might make it seem that there are files, they might be stored in a database or any other data structure. You cannot expect to find the created files matched one-to-one somewhere on the hard disk.

  **Note:** Writes performed using [`FileSystemSyncAccessHandle.write()`](filesystemsyncaccesshandle/write) are in-place, meaning that changes are written to the actual underlying file at the same time as they are written to the writer. This is not the case with other writing mechanisms available in this API (e.g. [`FileSystemFileHandle.createWritable()`](filesystemfilehandle/createwritable)), where changes are not committed to disk until the writing stream is closed.

 

### Saving files



There is also "save" functionality:

 * In the case of the asynchronous handles, use the [`FileSystemWritableFileStream`](filesystemwritablefilestream) interface. Once the data you'd like to save is in a format of [`Blob`](blob), [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) object, string literal or [`buffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), you can open a stream and save the data to a file. This can be the existing file or a new file.
* In the case of the synchronous [`FileSystemSyncAccessHandle`](filesystemsyncaccesshandle), you write changes to a file using the [`write()`](filesystemsyncaccesshandle/write) method. You can optionally also call [`flush()`](filesystemsyncaccesshandle/flush) if you need the changes committed to disk at a specific time (otherwise you can leave the underlying operating system to handle this when it sees fit, which should be OK in most cases).



Interfaces
----------


 [`FileSystemHandle`](filesystemhandle)  The `FileSystemHandle` interface is an object which represents an entry. Multiple handles can represent the same entry. For the most part you do not work with `FileSystemHandle` directly but rather its child interfaces [`FileSystemFileHandle`](filesystemfilehandle) and [`FileSystemDirectoryHandle`](filesystemdirectoryhandle).

  [`FileSystemFileHandle`](filesystemfilehandle)  Provides a handle to a file system entry.

  [`FileSystemDirectoryHandle`](filesystemdirectoryhandle)  provides a handle to a file system directory.

  [`FileSystemSyncAccessHandle`](filesystemsyncaccesshandle)  Provides a synchronous handle to a file system entry, which operates in-place on a single file on disk. The synchronous nature of the file reads and writes allows for higher performance for critical methods in contexts where asynchronous operations come with high overhead, e.g., [WebAssembly](https://developer.mozilla.org/en-US/docs/WebAssembly). This class is only accessible inside dedicated [Web Workers](web_workers_api) for files within the [origin private file system](#origin_private_file_system).

  [`FileSystemWritableFileStream`](filesystemwritablefilestream)  is a [`WritableStream`](writablestream) object with additional convenience methods, which operates on a single file on disk.

  
Examples
--------


### Accessing files



The below code allows the user to choose a file from the file picker.

 
```
async function getFile() {
  // Open file picker and destructure the result the first handle
  const [fileHandle] = await window.showOpenFilePicker();
  const file = await fileHandle.getFile();
  return file;
}

```
 The following asynchronous function presents a file picker and once a file is chosen, uses the `getFile()` method to retrieve the contents.

 
```
const pickerOpts = {
  types: [
    {
      description: "Images",
      accept: {
        "image/\*": [".png", ".gif", ".jpeg", ".jpg"],
      },
    },
  ],
  excludeAcceptAllOption: true,
  multiple: false,
};

async function getTheFile() {
  // Open file picker and destructure the result the first handle
  const [fileHandle] = await window.showOpenFilePicker(pickerOpts);

  // get file contents
  const fileData = await fileHandle.getFile();
}

```


### Accessing directories



The following example returns a directory handle with the specified name. If the directory does not exist, it is created.

 
```
const dirName = "directoryToGetName";

// assuming we have a directory handle: 'currentDirHandle'
const subDir = currentDirHandle.getDirectoryHandle(dirName, { create: true });

```
 The following asynchronous function uses `resolve()` to find the path to a chosen file, relative to a specified directory handle.

 
```
async function returnPathDirectories(directoryHandle) {
  // Get a file handle by showing a file picker:
  const [handle] = await self.showOpenFilePicker();
  if (!handle) {
    // User cancelled, or otherwise failed to open a file.
    return;
  }

  // Check if handle exists inside directory our directory handle
  const relativePaths = await directoryHandle.resolve(handle);

  if (relativePaths === null) {
    // Not inside directory handle
  } else {
    // relativePaths is an array of names, giving the relative path

    for (const name of relativePaths) {
      // log each entry
      console.log(name);
    }
  }
}

```


### Writing to files



The following asynchronous function opens the save file picker, which returns a [`FileSystemFileHandle`](filesystemfilehandle) once a file is selected. A writable stream is then created using the [`FileSystemFileHandle.createWritable()`](filesystemfilehandle/createwritable) method.

 A user defined [`Blob`](blob) is then written to the stream which is subsequently closed.

 
```
async function saveFile() {
  // create a new handle
  const newHandle = await window.showSaveFilePicker();

  // create a FileSystemWritableFileStream to write to
  const writableStream = await newHandle.createWritable();

  // write our file
  await writableStream.write(imgBlob);

  // close the file and write the contents to disk.
  await writableStream.close();
}

```
 The following show different examples of options that can be passed into the `write()` method.

 
```
// just pass in the data (no options)
writableStream.write(data);

// writes the data to the stream from the determined position
writableStream.write({ type: "write", position, data });

// updates the current file cursor offset to the position specified
writableStream.write({ type: "seek", position });

// resizes the file to be size bytes long
writableStream.write({ type: "truncate", size });

```


### Synchronously reading and writing files in OPFS



This example synchronously reads and writes a file to the [origin private file system](#origin_private_file_system).

 The following asynchronous event handler function is contained inside a Web Worker. On receiving a message from the main thread it:

 * Creates a synchronous file access handle.
* Gets the size of the file and creates an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) to contain it.
* Reads the file contents into the buffer.
* Encodes the message and writes it to the end of the file.
* Persists the changes to disk and closes the access handle.

 
```
onmessage = async (e) => {
  // retrieve message sent to work from main script
  const message = e.data;

  // Get handle to draft file in OPFS
  const root = await navigator.storage.getDirectory();
  const draftHandle = await root.getFileHandle("draft.txt", { create: true });
  // Get sync access handle
  const accessHandle = await draftHandle.createSyncAccessHandle();

  // Get size of the file.
  const fileSize = accessHandle.getSize();
  // Read file content to a buffer.
  const buffer = new DataView(new ArrayBuffer(fileSize));
  const readBuffer = accessHandle.read(buffer, { at: 0 });

  // Write the message to the end of the file.
  const encoder = new TextEncoder();
  const encodedMessage = encoder.encode(message);
  const writeBuffer = accessHandle.write(encodedMessage, { at: readBuffer });

  // Persist changes to disk.
  accessHandle.flush();

  // Always close FileSystemSyncAccessHandle if done.
  accessHandle.close();
};

```
  **Note:** In earlier versions of the spec, [`close()`](filesystemsyncaccesshandle/close), [`flush()`](filesystemsyncaccesshandle/flush), [`getSize()`](filesystemsyncaccesshandle/getsize), and [`truncate()`](filesystemsyncaccesshandle/truncate) were unergonomically specified as asynchronous methods. This has now been [amended](https://github.com/whatwg/fs/issues/7), but some browsers still support the asynchronous versions.

 

Specifications
--------------




| Specification |
| --- |
| [File System Standard # api-filesystemhandle](https://fs.spec.whatwg.org/#api-filesystemhandle) |
| [File System Standard # api-filesystemfilehandle](https://fs.spec.whatwg.org/#api-filesystemfilehandle) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `File_System_Access_API` | 86 | 86 | 111 | No | 72 | 15.2 | 86 | 86 | 111 | 61 | 15.2 | 14.0 |
| `createSyncAccessHandle` | 102 | 102 | 111 | No | 88 | 15.2 | 109 | 109 | 111 | 74 | 15.2 | No |
| `createWritable` | 86 | 86 | 111 | No | 72 | No | No | 86 | 111 | 61 | No | 14.0 |
| `getFile` | 86 | 86 | 111 | No | 72 | 15.2 | No | 86 | 111 | 61 | 15.2 | 14.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `File_System_Access_API` | 86 | 86 | 111 | No | 72 | 15.2 | No | 86 | 111 | 61 | 15.2 | 14.0 |
| `isSameEntry` | 86 | 86 | 111 | No | 72 | 15.2 | No | 86 | 111 | 61 | 15.2 | 14.0 |
| `kind` | 86 | 86 | 111 | No | 72 | 15.2 | No | 86 | 111 | 61 | 15.2 | 14.0 |
| `move` | No | No | 111 | No | No | No | No | No | 111 | No | No | No |
| `name` | 86 | 86 | 111 | No | 72 | 15.2 | No | 86 | 111 | 61 | 15.2 | 14.0 |
| `queryPermission` | 86 | 86 | No | No | 72 | No | No | 86 | No | 61 | No | 14.0 |
| `remove` | 110 | 110 | No | No | 96 | No | No | 110 | No | 74 | No | No |
| `requestPermission` | 86 | 86 | No | No | 72 | No | No | 86 | No | 61 | No | 14.0 |


### api.FileSystemHandle


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.FileSystemFileHandle


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


See also
--------


* [The File System Access API: simplifying access to local files](https://web.dev/file-system-access/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API>

File and Directory Entries API
==============================


The File and Directory Entries API simulates a local file system that web apps can navigate within and access files in. You can develop apps which read, write, and create files and/or directories in a virtual, sandboxed file system.


Getting access to a file system
-------------------------------



There are two ways to get access to file systems defined in the current specification draft:

 * When handling a [`drop`](htmlelement/drop_event) event for drag and drop, you can call [`DataTransferItem.webkitGetAsEntry()`](datatransferitem/webkitgetasentry) to get the [`FileSystemEntry`](filesystementry) for a dropped item. If the result isn't `null`, then it's a dropped file or directory, and you can use file system calls to work with it.
* The [`HTMLInputElement.webkitEntries`](htmlinputelement/webkitentries) property lets you access the [`FileSystemFileEntry`](filesystemfileentry) objects for the currently selected files, but only if they are dragged-and-dropped onto the file chooser ([Firefox bug 1326031](https://bugzil.la/1326031)). If [`HTMLInputElement.webkitdirectory`](htmlinputelement/webkitdirectory) is `true`, the [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) element is instead a directory picker, and you get [`FileSystemDirectoryEntry`](filesystemdirectoryentry) objects for each selected directory.



Interfaces
----------



The File and Directory Entries API includes the following interfaces:

  [`FileSystem`](filesystem)  Represents a file system.

  [`FileSystemEntry`](filesystementry)  The basic interface representing a single entry in a file system. This is implemented by other interfaces which represent files or directories.

  [`FileSystemFileEntry`](filesystemfileentry)  Represents a single file in a file system.

  [`FileSystemDirectoryEntry`](filesystemdirectoryentry)  Represents a single directory in a file system.

  [`FileSystemDirectoryReader`](filesystemdirectoryreader)  Created by calling [`FileSystemDirectoryEntry.createReader()`](filesystemdirectoryentry/createreader), this interface provides the functionality which lets you read the contents of a directory.

  

Specifications
--------------




| Specification |
| --- |
| [File and Directory Entries API # api-domfilesystem](https://wicg.github.io/entries-api/#api-domfilesystem) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `File_and_Directory_Entries_API` | 7 | ≤18Edge only supports this API in drag-and-drop scenarios using the `[DataTransferItem.webkitGetAsEntry()](https://developer.mozilla.org/docs/Web/API/DataTransferItem/webkitGetAsEntry)` method. It's not available for use in file or folder picker panels (such as when you use an `[<input>](https://developer.mozilla.org/docs/Web/HTML/Element/input)` element with the `[HTMLInputElement.webkitdirectory](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/webkitdirectory)` attribute. | 50 | No | 15 | 11.1 | ≤37 | 18 | 50 | 14 | 11.3 | 1.0 |
| `name` | 7 | ≤18 | 50 | No | 15 | 11.1 | ≤37 | 18 | 50 | 14 | 11.3 | 1.0 |
| `root` | 7 | ≤18 | 50 | No | 15 | 11.1 | ≤37 | 18 | 50 | 14 | 11.3 | 1.0 |


See also
--------


* [Introduction to the File and Directory Entries API](file_and_directory_entries_api/introduction)
* [File and Directory Entries API support in Firefox](file_and_directory_entries_api/firefox_support)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/File_and_Directory_Entries_API>

Fullscreen API
==============



The **Fullscreen API** adds methods to present a specific [`Element`](element) (and its descendants) in fullscreen mode, and to exit fullscreen mode once it is no longer needed. This makes it possible to present desired content—such as an online game—using the user's entire screen, removing all browser user interface elements and other applications from the screen until fullscreen mode is shut off.

 See the article [Guide to the Fullscreen API](fullscreen_api/guide) for details on how to use the API.

  **Note:** Support for this API varies somewhat across browsers, with many requiring vendor prefixes and/or not implementing the latest specification. See the [Browser compatibility](#browser_compatibility) section below for details on support for this API. You may wish to consider using a library such as [Fscreen](https://github.com/rafgraph/fscreen) for vendor agnostic access to the Fullscreen API.

 

Interfaces
----------


*The Fullscreen API has no interfaces of its own. Instead, it augments several other interfaces to add the methods, properties, and event handlers needed to provide fullscreen functionality. These are listed in the following sections.*


Instance methods
----------------


The Fullscreen API adds methods to the [`Document`](document) and [`Element`](element) interfaces to allow turning off and on fullscreen mode.


### Instance methods on the Document interface


 [`Document.exitFullscreen()`](document/exitfullscreen)  Requests that the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) switch from fullscreen mode back to windowed mode. Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which is resolved once fullscreen mode has been completely shut off.

  
### Instance methods on the Element interface


 [`Element.requestFullscreen()`](element/requestfullscreen)  Asks the user agent to place the specified element (and, by extension, its descendants) into fullscreen mode, removing all of the browser's UI elements as well as all other applications from the screen. Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which is resolved once fullscreen mode has been activated.

  
Instance properties
-------------------



*The [`Document`](document) interface provides properties that can be used to determine if fullscreen mode is supported and available, and if fullscreen mode is currently active, which element is using the screen.*

  
[`Document.fullscreenElement`](document/fullscreenelement) / [`ShadowRoot.fullscreenElement`](shadowroot/fullscreenelement)
  The `fullscreenElement` property tells you the [`Element`](element) that's currently being displayed in fullscreen mode on the DOM (or shadow DOM). If this is `null`, the document (or shadow DOM) is not in fullscreen mode.

  [`document.fullscreenEnabled`](document/fullscreenenabled)  The `fullscreenEnabled` property tells you whether or not it is possible to engage fullscreen mode. This is `false` if fullscreen mode is not available for any reason (such as the `"fullscreen"` feature not being allowed, or fullscreen mode not being supported).

  

### Obsolete properties


 
[`Document.fullscreen`](document/fullscreen)  Deprecated 
  A Boolean value which is `true` if the document has an element currently being displayed in fullscreen mode; otherwise, this returns `false`.

  **Note:** Use the [`fullscreenElement`](document/fullscreenelement) property on the [`Document`](document) or [`ShadowRoot`](shadowroot) instead; if it's not `null`, then it's an [`Element`](element) currently being displayed in fullscreen mode.

   
Events
------



*The Fullscreen API defines two events which can be used to detect when fullscreen mode is turned on and off, as well as when errors occur during the process of changing between fullscreen and windowed modes.*

  [`fullscreenchange`](element/fullscreenchange_event)  Sent to an [`Element`](element) when it transitions into or out of fullscreen mode.

  [`fullscreenerror`](element/fullscreenerror_event)  Sent to an `Element` if an error occurs while attempting to switch it into or out of fullscreen mode.

  

Controlling access
------------------


The availability of fullscreen mode can be controlled using a [Permissions Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy). The fullscreen mode feature is identified by the string `"fullscreen"`, with a default allowlist value of `"self"`, meaning that fullscreen mode is permitted in top-level document contexts, as well as to nested browsing contexts loaded from the same origin as the top-most document.


Usage notes
-----------



Users can choose to exit fullscreen mode by pressing the `ESC` (or `F11`) key, rather than waiting for the site or app to programmatically do so. Make sure you provide, somewhere in your user interface, appropriate user interface elements that inform the user that this option is available to them.

  **Note:** Navigating to another page, changing tabs, or switching to another application using any application switcher (or `Alt`-`Tab`) will likewise exit fullscreen mode.

 

Examples
--------


### Simple fullscreen usage



In this example, a video is presented in a web page. Pressing the `Enter` key lets the user toggle between windowed and fullscreen presentation of the video.

 [View Live Example](https://mdn.github.io/dom-examples/fullscreen-api/index.html)

 #### Watching for the Enter key

 When the page is loaded, this code is run to set up an event listener to watch for the `Enter` key.

 
```
document.addEventListener(
  "keydown",
  (e) => {
    if (e.key === "Enter") {
      toggleFullScreen();
    }
  },
  false
);

```
 #### Toggling fullscreen mode

 This code is called by the event handler above when the user hits the `Enter` key.

 
```
function toggleFullScreen() {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen();
  } else if (document.exitFullscreen) {
    document.exitFullscreen();
  }
}

```
 This starts by looking at the value of the [`document`](document)'s `fullscreenElement` attribute. In a real-world deployment, at this time, you'll want to check for prefixed versions of this (`mozFullScreenElement`, `msFullscreenElement`, or `webkitFullscreenElement`, for example). If the value is `null`, the document is currently in windowed mode, so we need to switch to fullscreen mode; otherwise, it's the element that's currently in fullscreen mode. Switching to fullscreen mode is done by calling [`Element.requestFullscreen()`](element/requestfullscreen) on the [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) element.

 If fullscreen mode is already active (`fullscreenElement` is not `null`), we call [`exitFullscreen()`](document/exitfullscreen) on the `document` to shut off fullscreen mode.



Specifications
--------------




| Specification |
| --- |
| [Fullscreen API Standard # ref-for-dom-document-fullscreenelement①](#) |
| [Fullscreen API Standard # ref-for-dom-document-fullscreenenabled①](#) |
| [Fullscreen API Standard # ref-for-dom-document-exitfullscreen①](#) |
| [Fullscreen API Standard # ref-for-dom-element-requestfullscreen①](#) |
| [Fullscreen API Standard # dom-document-fullscreen](https://fullscreen.spec.whatwg.org/#dom-document-fullscreen) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Fullscreen_API` | 7115 | 7912 | 649 | No | 5815 | 16.46 | 71≤37 | 7118 | 649 | 5014 | 12Only available on iPad, not on iPhone. | 10.01.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Fullscreen_API` | 7115 | 791212–14 | 649Before Firefox 44, Firefox incorrectly allowed elements inside a `<frame>` or `<object>` element to request, and to be granted, fullscreen. In Firefox 44 and onwards this has been fixed: only elements in the top-level document or in an `<iframe>` element with the `allowfullscreen` attribute can be displayed fullscreen. | 11 | 581512.1–15 | 16.45.1 | 71≤37 | 7118 | 649Before Firefox 44, Firefox incorrectly allowed elements inside a `<frame>` or an `<object>` to request, and to be granted, fullscreen. In Firefox 44 and onwards this has been fixed: only elements in the top-level document or in an ``<iframe>`` with the `allowfullscreen` attribute can be displayed fullscreen. | 501412.1–14 | 12Only available on iPad, not on iPhone. Shows an overlay button which can not be disabled. | 10.01.0 |
| `options_navigationUI_parameter` | 71 | 79 | No | No | 58 | 16.4 | 71 | 71 | No | 50 | 16.4 | 10.0 |
| `returns_promise` | 71 | 79 | 64 | No | 58 | 16.4 | 71 | 71 | 64 | 50 | 16.4 | 10.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Fullscreen_API` | 7115 | 791212–14 | 649 | 11 | 581512.1–15 | 16.45.1 | 71≤37 | 7118 | 649 | 501412.1–14 | 12Only available on iPad, not on iPhone. | 10.01.0 |
| `returns_promise` | 69 | 79 | 64 | No | 56 | No | 69 | 69 | 64 | 48 | No | 10.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Fullscreen_API` | 7120 | 12 | 6410 | 11 | 581512.1–15 | 16.46 | 714.4 | 7125 | 6410 | 501412.1–14 | 12Only available on iPad, not on iPhone. | 10.01.5 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Fullscreen_API` | 7120 | 791212–14 | 649 | 11 | 581512.1–15 | 16.46 | 714.4 | 7125 | 649 | 501412.1–14 | 16.4Only available on iPad, not on iPhone.12Only available on iPad, not on iPhone. | 10.01.5 |


### api.Document.fullscreenElement


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.Document.fullscreenEnabled


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.Document.exitFullscreen


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.Element.requestFullscreen


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.Document.fullscreen


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


See also
--------


* [`Element.requestFullscreen()`](element/requestfullscreen)
* [`Document.exitFullscreen()`](document/exitfullscreen)
* [`Document.fullscreen`](document/fullscreen)
* [`Document.fullscreenElement`](document/fullscreenelement)
* [`:fullscreen`](https://developer.mozilla.org/en-US/docs/Web/CSS/:fullscreen), [`::backdrop`](https://developer.mozilla.org/en-US/docs/Web/CSS/::backdrop)
* [`allowfullscreen`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#allowfullscreen)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API>

Gamepad API
===========



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The **Gamepad API** is a way for developers to access and respond to signals from gamepads and other game controllers in a simple, consistent way. It contains three interfaces, two events and one specialist function, to respond to gamepads being connected and disconnected, and to access other information about the gamepads themselves, and what buttons and other controls are currently being pressed.



Interfaces
----------


 [`Gamepad`](gamepad)  Represents a gamepad/controller connected to the computer.

  [`GamepadButton`](gamepadbutton)  Represents a button on one of the connected controllers.

  [`GamepadEvent`](gamepadevent)  The event object representing events fired that are related to gamepads.

  
### Experimental Gamepad extensions



 [`GamepadHapticActuator`](gamepadhapticactuator)  Represents hardware in the controller designed to provide haptic feedback to the user (if available), most commonly vibration hardware.

  [`GamepadPose`](gamepadpose)  Represents the pose of a controller (e.g. position and orientation in 3D space) in the case of a [WebVR](webvr_api) controller. This is *not* used by the newer [WebXR](webxr_device_api) standard.

   See also the [extensions to the Gamepad interface](gamepad#experimental_extensions_to_gamepad), for features that allow you to access the above information.



### Extensions to other interfaces



#### Navigator

  [`Navigator.getGamepads()`](navigator/getgamepads)  An extension to the [`Navigator`](navigator) object that returns an array of [`Gamepad`](gamepad) objects, one for each connected gamepad.

   #### Window events

  [`gamepadconnected`](window/gamepadconnected_event)  An event that will fire when a gamepad is connected.

  [`gamepaddisconnected`](window/gamepaddisconnected_event)  An event that will fire when a gamepad is disconnected.

  

Tutorials and guides
--------------------


* [Using the Gamepad API](gamepad_api/using_the_gamepad_api)
* [Implementing controls using the Gamepad API](https://developer.mozilla.org/en-US/docs/Games/Techniques/Controls_Gamepad_API)

Specifications
--------------




| Specification |
| --- |
| [Gamepad # gamepad-interface](https://w3c.github.io/gamepad/#gamepad-interface) |
| [Gamepad Extensions # partial-gamepad-interface](https://w3c.github.io/gamepad/extensions.html#partial-gamepad-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Gamepad_API` | 21 | 12 | 29 | No | 15 | 10.1 | 4.4 | 25 | 32 | 14 | 10.3 | 1.5 |
| `axes` | 21 | 12 | 29 | No | 15 | 10.1 | 4.4 | 25 | 32 | 14 | 10.3 | 1.5 |
| `buttons` | 21 | 12 | 29 | No | 15 | 10.1 | 4.4 | 25 | 32 | 14 | 10.3 | 1.5 |
| `connected` | 25 | 12 | 29 | No | 15 | 10.1 | 4.4 | 25 | 32 | 14 | 10.3 | 1.5 |
| `displayId` | No | 79–8015–79 | 9864–98macOS support was enabled in Firefox 64.55–98Windows support was enabled in Firefox 55. | No | No | No | No | 55–80Currently supported only by Google Daydream. | 55 | 42–57Currently supported only by Google Daydream. | No | 6.0–13.0Currently supported only by Google Daydream. |
| `hand` | No | 15–79 | 55 | No | No | No | No | No | 55 | No | No | No |
| `hapticActuators` | No | 15–79 | 55 | No | No | No | No | No | 55 | No | No | No |
| `id` | 21 | 12 | 29 | No | 15 | 10.1 | 4.4 | 25 | 32 | 14 | 10.3 | 1.5 |
| `index` | 21 | 12 | 29 | No | 15 | 10.1 | 4.4 | 25 | 32 | 14 | 10.3 | 1.5 |
| `mapping` | 21 | 12 | 29 | No | 15 | 10.1 | 4.4 | 25 | 32 | 14 | 10.3 | 1.5 |
| `pose` | No | 15–79 | 55 | No | No | No | No | No | 55 | No | No | No |
| `secure_context_required` | 86 | 86 | 91 | No | 72 | No | No | 86 | 91 | No | No | No |
| `timestamp` | 21 | 12 | 29 | No | 15 | 10.1 | 4.4 | 25 | 32 | 14 | 10.3 | 1.5 |
| `vibrationActuator` | 68 | 79 | No | No | 55 | 16.4 | No | 68 | No | 48 | 16.4 | 10.0 |


See also
--------


* [The Gamepad API](https://hacks.mozilla.org/2013/12/the-gamepad-api/) by Ted Mielczarek and Robert Nyman
* [Simple API demo page](https://luser.github.io/gamepadtest/) ([source](https://github.com/luser/gamepadtest))


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API>

Geolocation API
===============



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The **Geolocation API** allows the user to provide their location to web applications if they so desire. For privacy reasons, the user is asked for permission to report location information.

 WebExtensions that wish to use the `Geolocation` object must add the `"geolocation"` permission to their manifest. The user's operating system will prompt the user to allow location access the first time it is requested.



Concepts and usage
------------------



You will often want to retrieve a user's location information in your web app, for example to plot their location on a map, or display personalized information relevant to their location.

 The Geolocation API is accessed via a call to [`navigator.geolocation`](navigator/geolocation); this will cause the user's browser to ask them for permission to access their location data. If they accept, then the browser will use the best available functionality on the device to access this information (for example, GPS).

 The developer can now access this location information in a couple of different ways:

 * [`Geolocation.getCurrentPosition()`](geolocation/getcurrentposition): Retrieves the device's current location.
* [`Geolocation.watchPosition()`](geolocation/watchposition): Registers a handler function that will be called automatically each time the position of the device changes, returning the updated location.

 In both cases, the method call takes up to three arguments:

 * A mandatory success callback: If the location retrieval is successful, the callback executes with a [`GeolocationPosition`](geolocationposition) object as its only parameter, providing access to the location data.
* An optional error callback: If the location retrieval is unsuccessful, the callback executes with a [`GeolocationPositionError`](geolocationpositionerror) object as its only parameter, providing access information on what went wrong.
* An optional object which provides options for retrieval of the position data.

 For further information on Geolocation usage, read [Using the Geolocation API](geolocation_api/using_the_geolocation_api).



Interfaces
----------


 [`Geolocation`](geolocation)  The main class of this API — contains methods to retrieve the user's current position, watch for changes in their position, and clear a previously-set watch.

  [`GeolocationPosition`](geolocationposition)  Represents the position of a user. A `GeolocationPosition` instance is returned by a successful call to one of the methods contained inside [`Geolocation`](geolocation), inside a success callback, and contains a timestamp plus a [`GeolocationCoordinates`](geolocationcoordinates) object instance.

  [`GeolocationCoordinates`](geolocationcoordinates)  Represents the coordinates of a user's position; a `GeolocationCoordinates` instance contains latitude, longitude, and other important related information.

  [`GeolocationPositionError`](geolocationpositionerror)  A `GeolocationPositionError` is returned by an unsuccessful call to one of the methods contained inside [`Geolocation`](geolocation), inside an error callback, and contains an error code and message.

  [`Navigator.geolocation`](navigator/geolocation)  The entry point into the API. Returns a [`Geolocation`](geolocation) object instance, from which all other functionality can be accessed.

  
Examples
--------


See [Using the Geolocation API](geolocation_api/using_the_geolocation_api#examples) for example code.


Specifications
--------------




| Specification |
| --- |
| [Geolocation API # geolocation\_interface](https://w3c.github.io/geolocation-api/#geolocation_interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Geolocation_API` | 5 | 12 | 3.5[GPSD](https://gpsd.gitlab.io/gpsd/index.html) (GPS daemon) support added in Firefox 3.6. WiFi-based location is provided by Google ([privacy](https://support.mozilla.org/en-US/kb/does-firefox-share-my-location-websites)) or a custom provider ([MLS instructions](https://wiki.mozilla.org/CloudServices/Location/Software)). | 9 | 10.6 | 5 | ≤37 | 18 | 4 | 11 | ≤3 | 1.0 |
| `clearWatch` | 5 | 12 | 3.5 | 9 | 10.6 | 5 | ≤37 | 18 | 4 | 11 | ≤3 | 1.0 |
| `getCurrentPosition` | 5 | 12 | 3.5 | 9 | 10.6 | 5 | ≤37 | 18 | 4 | 11 | ≤3 | 1.0 |
| `secure_context_required` | 50 | 79 | 55 | No | 37 | 10 | 51Secure context is only required for applications targeting Android Nougat (7) and higher. See [bug 603574](https://crbug.com/603574). | 50 | 55 | 37 | 10 | 5.0 |
| `watchPosition` | 5 | 12 | 3.5 | 9 | 10.6 | 5 | ≤37 | 18 | 4 | 11 | ≤3 | 1.0 |


### Availability


As Wi-Fi-based locating is often provided by Google, the vanilla Geolocation API may be unavailable in China. You may use local third-party providers such as [Baidu](https://lbsyun.baidu.com/index.php?title=jspopular/guide/geolocation), [Autonavi](https://lbs.amap.com/api/javascript-api/guide/services/geolocation#geolocation), or [Tencent](https://lbs.qq.com/tool/component-geolocation.html). These services use the user's IP address and/or a local app to provide enhanced positioning.


See also
--------


* [Using the Geolocation API](geolocation_api/using_the_geolocation_api)
* [Geolocation API on w3.org](https://www.w3.org/TR/geolocation/)
* [Who moved my geolocation?](https://hacks.mozilla.org/2013/10/who-moved-my-geolocation/) (Hacks blog)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API>

Geometry interfaces
===================



**Geometry interfaces** is a CSS module that provides interfaces for working with 3D and 2D graphics — in particular, for working with points, rectangles, quadrilaterals and [transformation matrices](webgl_api/matrix_math_for_the_web#transformation_matrices) (for operations that translate/move, scale, rotate, skew/shear/slant, and flip graphics, as well as for multiplying/chaining and inverting/undoing those operations).

 As a web developer, you don't always use the geometry interfaces directly, but instead use other features that rely on them behind the scenes: parts of [CSS Transforms](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transforms), the [Canvas API](canvas_api), the [WebXR Device API](webxr_device_api), and (more directly) [`VideoFrame.visibleRect`](videoframe/visiblerect), [`Element.getClientRects()`](element/getclientrects), and [`Element.getBoundingClientRect()`](element/getboundingclientrect).



Interfaces
----------


 [`DOMMatrix`](dommatrix)  Represents a [transformation matrix](webgl_api/matrix_math_for_the_web#transformation_matrices), for operations that translate/move, scale, rotate, skew/shear/slant, and flip graphics, as well as for multiplying/chaining and inverting/undoing those operations.

  [`DOMMatrixReadOnly`](dommatrixreadonly)  Read-only version of [`DOMMatrix`](dommatrix).

  [`DOMPoint`](dompoint)  Represents a 2D or 3D point in a coordinate system; it includes values for the coordinates in up to three dimensions, as well as an optional perspective value.

  [`DOMQuad`](domquad)  Represents a collection of four [`DOMPoint`](dompoint) objects defining the corners of a [quadrilateral](https://en.wikipedia.org/wiki/Quadrilateral).

  [`DOMRect`](domrect)  Represents the size and position of a rectangle.

  [`DOMRectReadOnly`](domrectreadonly)  Read-only version of [`DOMRect`](domrect).

  
Examples
--------


The [`Path2D.addPath()`](path2d/addpath) and [`CanvasPattern.setTransform()`](canvaspattern/settransform) articles have examples that use some of the geometry interfaces.


Specifications
--------------




| Specification |
| --- |
| [Geometry Interfaces Module Level 1 # DOMMatrix](https://drafts.fxtf.org/geometry/#DOMMatrix) |
| [Geometry Interfaces Module Level 1 # DOMPoint](https://drafts.fxtf.org/geometry/#DOMPoint) |
| [Geometry Interfaces Module Level 1 # DOMQuad](https://drafts.fxtf.org/geometry/#DOMQuad) |
| [Geometry Interfaces Module Level 1 # DOMRect](https://drafts.fxtf.org/geometry/#DOMRect) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DOMRectReadOnly` | 61 | 79 | 62 | No | 48 | 10.1 | 61 | 61 | 62 | 45 | 10.3 | 8.0 |
| `Geometry_interfaces` | 612–61 | 7912–79 | 3127–313–27 | 4 | 489.5–48 | 10.14–11 | 612–61 | 6118–61 | 3127–314–27 | 4510.1–45 | 10.33.2–11 | 8.01.0–8.0 |
| `bottom` | 2 | 12 | 3 | 4 | 9.5 | 4 | 2 | 18 | 4 | 10.1 | 3.2 | 1.0 |
| `fromRect` | 61 | 79 | 69 | No | 48 | 10.1 | 61 | 61 | 79 | 45 | 10.3 | 8.0 |
| `height` | 2 | 12 | 3 | 4 | 9.5 | 4 | 2 | 18 | 4 | 10.1 | 3.2 | 1.0 |
| `left` | 2 | 12 | 3 | 4 | 9.5 | 4 | 2 | 18 | 4 | 10.1 | 3.2 | 1.0 |
| `right` | 2 | 12 | 3 | 4 | 9.5 | 4 | 2 | 18 | 4 | 10.1 | 3.2 | 1.0 |
| `toJSON` | 61 | 79 | 62 | No | 48 | 10.1 | 61 | 61 | 62 | 45 | 10.3 | 8.0 |
| `top` | 2 | 12 | 3 | 4 | 9.5 | 4 | 2 | 18 | 4 | 10.1 | 3.2 | 1.0 |
| `width` | 2 | 12 | 3 | 4 | 9.5 | 4 | 2 | 18 | 4 | 10.1 | 3.2 | 1.0 |
| `worker_support` | 61 | 79 | 69 | No | 48 | 10.1 | 61 | 61 | No | 45 | 10.3 | 8.0 |
| `x` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |
| `y` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DOMRect` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |
| `Geometry_interfaces` | 612–61 | 7912–79 | 273–27 | 4 | 489.5–48 | 10.14–11 | 612–61 | 6118–61 | 274–27 | 4510.1–45 | 10.33.2–11 | 8.01.0–8.0 |
| `fromRect` | 61 | 79 | 69 | No | 48 | 10.1 | 61 | 61 | 79 | 45 | 10.3 | 8.0 |
| `height` | 2 | 12 | 3 | 4 | 9.5 | 4 | 2 | 18 | 4 | 10.1 | 3.2 | 1.0 |
| `width` | 2 | 12 | 3 | 4 | 9.5 | 4 | 2 | 18 | 4 | 10.1 | 3.2 | 1.0 |
| `worker_support` | 61 | 79 | 69 | No | 48 | 10.1 | 61 | 61 | No | 45 | 10.3 | 8.0 |
| `x` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |
| `y` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DOMQuad` | 61 | 79 | 31 | No | 48 | 11 | 61 | 61 | 31 | 45 | 11 | 8.0 |
| `Geometry_interfaces` | 61 | 79 | 31 | No | 48 | 11 | 61 | 61 | 31 | 45 | 11 | 8.0 |
| `fromQuad` | 61 | 79 | 69 | No | 48 | 11 | 61 | 61 | 79 | 45 | 11 | 8.0 |
| `fromRect` | 61 | 79 | 69 | No | 48 | 11 | 61 | 61 | 79 | 45 | 11 | 8.0 |
| `getBounds` | 61 | 79 | 62 | No | 48 | 11 | 61 | 61 | 62 | 45 | 11 | 8.0 |
| `p1` | 61 | 79 | 31Before Firefox 69, the default value of `p1` through `p4` was undefined; now `DOMQuadInit` defines these as `false`. | No | 48 | 11 | 61 | 61 | 31Before Firefox for Android 79, the default value of `p1` through `p4` was undefined; now `DOMQuadInit` defines these as `false`. | 45 | 11 | 8.0 |
| `p2` | 61 | 79 | 31Before Firefox 69, the default value of `p1` through `p4` was undefined; now `DOMQuadInit` defines these as `false`. | No | 48 | 11 | 61 | 61 | 31Before Firefox for Android 79, the default value of `p1` through `p4` was undefined; now `DOMQuadInit` defines these as `false`. | 45 | 11 | 8.0 |
| `p3` | 61 | 79 | 31Before Firefox 69, the default value of `p1` through `p4` was undefined; now `DOMQuadInit` defines these as `false`. | No | 48 | 11 | 61 | 61 | 31Before Firefox for Android 79, the default value of `p1` through `p4` was undefined; now `DOMQuadInit` defines these as `false`. | 45 | 11 | 8.0 |
| `p4` | 61 | 79 | 31Before Firefox 69, the default value of `p1` through `p4` was undefined; now `DOMQuadInit` defines these as `false`. | No | 48 | 11 | 61 | 61 | 31Before Firefox for Android 79, the default value of `p1` through `p4` was undefined; now `DOMQuadInit` defines these as `false`. | 45 | 11 | 8.0 |
| `toJSON` | 61 | 79 | 62 | No | 48 | 11 | 61 | 61 | 62 | 45 | 11 | 8.0 |
| `worker_support` | 61 | 79 | 69 | No | 48 | 11 | 61 | 61 | 79 | 45 | 11 | 8.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DOMPoint` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |
| `Geometry_interfaces` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |
| `fromPoint` | 61 | 79 | 62 | No | 48 | 10.1 | 61 | 61 | 62 | 45 | 10.3 | 8.0 |
| `w` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |
| `worker_support` | 61 | 79 | 69 | No | 48 | 10.1 | 61 | 61 | No | 45 | 10.3 | 8.0 |
| `x` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |
| `y` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |
| `z` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DOMMatrixReadOnly` | 61 | 79 | 62 | No | 48 | 11 | 61 | 61 | 62 | 45 | 11 | 8.0 |
| `Geometry_interfaces` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `a` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `b` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `c` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `d` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `e` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `f` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `flipX` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `flipY` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `fromFloat32Array` | 61 | 79 | 69 | No | 48 | 11 | 61 | 61 | 79 | 45 | 11 | 8.0 |
| `fromFloat64Array` | 61 | 79 | 69 | No | 48 | 11 | 61 | 61 | 79 | 45 | 11 | 8.0 |
| `fromMatrix` | 61 | 79 | 69 | No | 48 | 11 | 61 | 61 | 79 | 45 | 11 | 8.0 |
| `inverse` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `is2D` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `isIdentity` | 61 | 79 | 59 | No | 48 | 11 | 61 | 61 | 59 | 45 | 11 | 8.0 |
| `m11` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m12` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m13` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m14` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m21` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m22` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m23` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m24` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m31` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m32` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m33` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m34` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m41` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m42` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m43` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m44` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `multiply` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `rotate` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `rotateAxisAngle` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `rotateFromVector` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `scale` | 61 | 79 | 33Firefox 69 introduced support for the modern six-parameter syntax for `scale()`. Previously, it only supported the older three-parameter syntax: `scale(*scaleX*[, *originX*][, *originY*]]])`. | No | 48 | 11 | 61 | 61 | 33Firefox for Android 79 introduced support for the modern six-parameter syntax for `scale()`. Previously, it only supported the older three-parameter syntax: `scale(*scaleX*[, *originX*][, *originY*]]])`. | 45 | 11 | 8.0 |
| `scale3d` | 61 | 79 | 33Starting in Firefox 69, the first parameter (`scale`) is now optional with a default value of 1, per the specification. Previously it was required. | No | 48 | 11 | 61 | 61 | 33Starting in Firefox for Android 79, the first parameter (`scale`) is now optional with a default value of 1, per the specification. Previously it was required. | 45 | 11 | 8.0 |
| `scaleNonUniform` | 73 | 79 | 33 | No | 60 | No | 73 | 73 | 33 | 52 | No | 11.0 |
| `skewX` | 61 | 79 | 33Before Firefox 69, the `sx` parameter was required; you may now call `skewX()` with no inputs. A value of 0 is correctly assumed. | No | 48 | 11 | 61 | 61 | 33Before Firefox for Android 79, the `sx` parameter was required; you may now call `skewX()` with no inputs. A value of 0 is correctly assumed. | 45 | 11 | 8.0 |
| `skewY` | 61 | 79 | 33Before Firefox 69, the `sy` parameter was required; you may now call `skewY()` with no inputs. A value of 0 is correctly assumed. | No | 48 | 11 | 61 | 61 | 33Before Firefox for Android 79, the `sy` parameter was required; you may now call `skewY()` with no inputs. A value of 0 is correctly assumed. | 45 | 11 | 8.0 |
| `toFloat32Array` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `toFloat64Array` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `toJSON` | 61 | 79 | 62 | No | 48 | 11 | 61 | 61 | 62 | 45 | 11 | 8.0 |
| `toString` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `transformPoint` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `translate` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `worker_support` | 61 | 79 | 69 | No | 48 | 11 | 61 | 61 | 79 | 45 | 11 | 8.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DOMMatrix` | 6152 | 79121212–79 | 49331.5 | 11109 | 4815≤12.1 | 1154 | 614.44.4 | 611818 | 49334 | 4814≤12.1 | 1143 | 8.01.01.0 |
| `Geometry_interfaces` | 6152 | 79121212–79 | 49331.5 | 11109 | 4815≤12.1 | 1154 | 614.44.4 | 611818 | 49334 | 4814≤12.1 | 1143 | 8.01.01.0 |
| `a` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `b` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `c` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `d` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `e` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `f` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `fromFloat32Array` | 61 | 79 | 69 | No | 48 | 11 | 61 | 61 | 79 | 45 | 11 | 8.0 |
| `fromFloat64Array` | 61 | 79 | 69 | No | 48 | 11 | 61 | 61 | 79 | 45 | 11 | 8.0 |
| `fromMatrix` | 61 | 79 | 69 | No | 48 | 11 | 61 | 61 | 79 | 45 | 11 | 8.0 |
| `invertSelf` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m11` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m12` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m13` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m14` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m21` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m22` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m23` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m24` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m31` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m32` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m33` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m34` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m41` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m42` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m43` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m44` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `multiplySelf` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `preMultiplySelf` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `rotateAxisAngleSelf` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `rotateFromVectorSelf` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `rotateSelf` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `scale3dSelf` | 61 | 79 | 33Starting in Firefox 69, the first parameter (`scale`) is now optional with a default value of 1, per the specification. Previously it was required. | No | 48 | 11 | 61 | 61 | 33Firefox for Android requires the first parameter (`scale`). | 45 | 11 | 8.0 |
| `scaleSelf` | 61 | 79 | 33Firefox 69 introduced support for the modern six-parameter syntax for `scaleSelf()`. Previously, it only supported the older three-parameter syntax: `scale(*scaleX*[, *originX*][, *originY*]]])`. | No | 48 | 11 | 61 | 61 | 33Firefox for Android only supports the older three-parameter syntax for `scaleSelf()`: `scale(*scaleX*[, *originX*][, *originY*]]])`, and not the six-parameter syntax. | 45 | 11 | 8.0 |
| `setMatrixValue` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `skewXSelf` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `skewYSelf` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `translateSelf` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `worker_support` | 61 | 79 | 69 | No | 48 | 11 | 61 | 61 | No | 45 | 11 | 8.0 |


### api.DOMMatrix


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.DOMMatrixReadOnly


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.DOMPoint


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.DOMQuad


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.DOMRect


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.DOMRectReadOnly


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


See also
--------


* [`Path2D.addPath()`](path2d/addpath)
* [`CanvasPattern.setTransform()`](canvaspattern/settransform)
* [`CanvasRenderingContext2D.getTransform()`](canvasrenderingcontext2d/gettransform)
* [`CanvasRenderingContext2D.setTransform()`](canvasrenderingcontext2d/settransform)
* [`CSSTransformValue.toMatrix()`](csstransformvalue/tomatrix)
* [`CSSTransformComponent.toMatrix()`](csstransformcomponent/tomatrix)
* [`Element.getBoundingClientRect()`](element/getboundingclientrect)
* [`Element.getClientRects()`](element/getclientrects)
* [`VideoFrame.visibleRect`](videoframe/visiblerect)
* [`XRLightEstimate`](xrlightestimate)
* [`XRRigidTransform`](xrrigidtransform)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Geometry_interfaces>

Credential Management API
=========================


The Credential Management API lets a website store and retrieve password, public key, and federated credentials. These capabilities allow users to sign in without typing passwords, see the federated account they used to sign in to a site, and resume a session without the explicit sign-in flow of an expired session.


Credential management concepts and usage
----------------------------------------



This API lets websites interact with a user agent's password system directly so that websites can deal in a uniform way with site credentials and user agents can provide better assistance with the management of their credentials. For example, user agents have a particularly hard time dealing with federated identity providers or esoteric sign-in mechanisms.

 To address these problems, the Credential Management API provides ways for a website to store and retrieve different types of credentials. This gives users capabilities such as seeing the federated account they used to sign on to a site, or resuming a session without the explicit sign-in flow of an expired session.

  **Note:** This API is restricted to top-level contexts. Calls to `get()` and `store()` within an `<iframe>` element will resolve without effect.

 

### Subdomain-shared credentials


Later versions of the spec allow credentials to be retrieved from a different subdomain. For example, a password stored in `login.example.com` may be used to log in to `www.example.com`. To take advantage of this, a password must be explicitly stored by calling [`CredentialsContainer.store()`](credentialscontainer/store). This is sometimes referred to as public suffix list (PSL) matching; however the spec only *recommends* using PSL to determine the effective scope of a credential. It does not require it. Hence browsers may vary in their implementation.


Interfaces
----------


 [`Credential`](credential)  Provides information about an entity as a prerequisite to a trust decision.

  [`CredentialsContainer`](credentialscontainer)  Exposes methods to request credentials and notify the user agent when interesting events occur such as successful sign in or sign out. This interface is accessible from `navigator.credentials`.

  [`FederatedCredential`](federatedcredential)  Provides information about credentials from a federated identity provider, which is an entity that a website trusts to correctly authenticate a user, and which provides an API for that purpose. [OpenID Connect](https://openid.net/developers/specs/) is an example of such a framework.

  [`PasswordCredential`](passwordcredential)  Provides information about a username/password pair.

  [`PublicKeyCredential`](publickeycredential)  Provides a credential for logging in using a more secure system based on asymmetric cryptography instead of a password.

  
Specifications
--------------




| Specification |
| --- |
| [Credential Management Level 1 # the-credential-interface](https://w3c.github.io/webappsec-credential-management/#the-credential-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Credential_Management_API` | 51 | 18 | 60 | No | 38 | 13 | 51 | 51 | 60 | 41 | 13 | 5.0 |
| `id` | 51 | 18 | 60 | No | 38 | 13 | 51 | 51 | 60 | 41 | 13 | 5.0 |
| `isConditionalMediationAvailable` | No | No | No | No | No | 16 | No | No | No | No | 16 | No |
| `type` | 51 | 18 | 60 | No | 38 | 13 | 51 | 51 | 60 | 41 | 13 | 5.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Credential_Management_API>

EyeDropper API
==============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The **EyeDropper API** provides a mechanism for creating an eyedropper tool. Using this tool, users can sample colors from their screens, including outside of the browser window.



Concept
-------



Creative applications often allow users to sample colors from drawings or shapes in the application to reuse. Web applications can use the **EyeDropper API** to provide a similar eyedropper mode, provided by the browser.

 Using the API, a web application can start the eyedropper mode. Once started, the cursor changes to indicate to the user that the mode is active. The user can then either select a color from anywhere on the screen, or dismiss the eyedropper mode by pressing `Escape`.



Security and privacy measures
-----------------------------



To prevent malicious websites from getting pixel data from a user's screen without them realizing, the **EyeDropper API** implements the following measures:

 * The API doesn't let the eyedropper mode start without user intent. The [`EyeDropper.prototype.open()`](eyedropper/open) method can only be called in response to a user action (like a button click).
* No pixel information can be retrieved without user intent again. The promise returned by [`EyeDropper.prototype.open()`](eyedropper/open) only resolves to a color value in response to a user action (clicking on a pixel). So the eyedropper cannot be used in the background without the user noticing it.
* To help users notice the eyedropper mode more easily, it is made obvious by browsers. The normal mouse cursor disappears after a short delay and a magnifying glass appears instead. There is also a delay between when the eyedropper mode starts and when the user can select a pixel to ensure the user has had time to see the magnifying glass.
* Users are also able to cancel the eyedropper mode at any time (by pressing the `Escape` key).



Interfaces
----------


* [`EyeDropper`](eyedropper)  Experimental

Specifications
--------------




| Specification |
| --- |
| [EyeDropper API # eyedropper-interface](https://wicg.github.io/eyedropper-api/#eyedropper-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `EyeDropper` | 95 | 95 | No | No | 81 | No | No | No | No | No | No | No |
| `EyeDropper_API` | 95 | 95 | No | No | 81 | No | No | No | No | No | No | No |
| `open` | 95 | 95 | No | No | 81 | No | No | No | No | No | No | No |
| `secure_context_required` | 96 | 96 | No | No | 82 | No | No | No | No | No | No | No |


See also
--------


* [Picking colors of any pixel on the screen with the EyeDropper API](https://web.dev/eyedropper/)
* [The EyeDropper API W3C/SMPTE Joint Workshop](https://www.w3.org/2021/03/media-production-workshop/talks/patrick-brosset-eyedropper-api.html)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/EyeDropper_API>

The HTML DOM API
================



The **HTML DOM API** is made up of the interfaces that define the functionality of each of the [elements](https://developer.mozilla.org/en-US/docs/Glossary/Element) in [HTML](https://developer.mozilla.org/en-US/docs/Glossary/HTML), as well as any supporting types and interfaces they rely upon.

 The functional areas included in the HTML DOM API include:

 * Access to and control of HTML elements via the [DOM](https://developer.mozilla.org/en-US/docs/Glossary/DOM).
* Access to and manipulation of form data.
* Interacting with the contents of 2D images and the context of an HTML [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas), for example to draw on top of them.
* Management of media connected to the HTML media elements ([`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) and [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video)).
* Dragging and dropping of content on webpages.
* Access to the browser navigation history
* Supporting and connective interfaces for other APIs such as [Web Components](web_components), [Web Storage](web_storage_api), [Web Workers](web_workers_api), [WebSocket](websockets_api), and [Server-sent events](server-sent_events).



HTML DOM concepts and usage
---------------------------


In this article, we'll focus on the parts of the HTML DOM that involve engaging with HTML elements. Discussion of other areas, such as [Drag and Drop](html_drag_and_drop_api), [WebSockets](websockets_api), [Web Storage](web_storage_api), etc. can be found in the documentation for those APIs.


### Structure of an HTML document



The Document Object Model ([DOM](https://developer.mozilla.org/en-US/docs/Glossary/DOM)) is an architecture that describes the structure of a [`document`](document); each document is represented by an instance of the interface [`Document`](document). A document, in turn, consists of a hierarchical tree of **nodes**, in which a node is a fundamental record representing a single object within the document (such as an element or text node).

 Nodes may be strictly organizational, providing a means for grouping other nodes together or for providing a point at which a hierarchy can be constructed; other nodes may represent visible components of a document. Each node is based on the [`Node`](node) interface, which provides properties for getting information about the node as well as methods for creating, deleting, and organizing nodes within the DOM.

 Nodes don't have any concept of including the content that is actually displayed in the document. They're empty vessels. The fundamental notion of a node that can represent visual content is introduced by the [`Element`](element) interface. An `Element` object instance represents a single element in a document created using either HTML or an [XML](https://developer.mozilla.org/en-US/docs/Glossary/XML) vocabulary such as [SVG](https://developer.mozilla.org/en-US/docs/Glossary/SVG).

 For example, consider a document with two elements, one of which has two more elements nested inside it:

  ![Structure of a document with elements inside a document in a window] 

 While the [`Document`](document) interface is defined as part of the [DOM](document_object_model) specification, the HTML specification significantly enhances it to add information specific to using the DOM in the context of a web browser, as well as to using it to represent HTML documents specifically.

 Among the things added to `Document` by the HTML standard are:

 * Support for accessing various information provided by the [HTTP](https://developer.mozilla.org/en-US/docs/Glossary/HTTP) headers when loading the page, such as the [location](document/location) from which the document was loaded, [cookies](document/cookie), [modification date](document/lastmodified), [referring site](document/referrer), and so forth.
* Access to lists of elements in the document's [`<head>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head) block and [body](document/body), as well as lists of the [images](document/images), [links](document/links), [scripts](document/scripts), etc. contained in the document.
* Support for interacting with the user by examining [focus](document/hasfocus) and by executing commands on [editable content](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/contenteditable).
* Event handlers for document events defined by the HTML standard to allow access to [mouse](mouseevent) and [keyboard](keyboardevent) events, [drag and drop](html_drag_and_drop_api), [media control](htmlmediaelement), and more.
* Event handlers for events that can be delivered to both elements and documents; these presently include only [copy](htmlelement/copy_event), [cut](htmlelement/cut_event), and [paste](htmlelement/paste_event) actions.



### HTML element interfaces



The `Element` interface has been further adapted to represent HTML elements specifically by introducing the [`HTMLElement`](htmlelement) interface, which all more specific HTML element classes inherit from. This expands the `Element` class to add HTML-specific general features to the element nodes. Properties added by `HTMLElement` include for example [`hidden`](htmlelement/hidden) and [`innerText`](htmlelement/innertext).

 An [HTML](https://developer.mozilla.org/en-US/docs/Glossary/HTML) document is a DOM tree in which each of the nodes is an HTML element, represented by the [`HTMLElement`](htmlelement) interface. The `HTMLElement` class, in turn, implements `Node`, so every element is also a node (but not the other way around). This way, the structural features implemented by the [`Node`](node) interface are also available to HTML elements, allowing them to be nested within each other, created and deleted, moved around, and so forth.

 The `HTMLElement` interface is generic, however, providing only the functionality common to all HTML elements such as the element's ID, its coordinates, the HTML making up the element, information about scroll position, and so forth.

 In order to expand upon the functionality of the core `HTMLElement` interface to provide the features needed by a specific element, the `HTMLElement` class is subclassed to add the needed properties and methods. For example, the [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element is represented by an object of type [`HTMLCanvasElement`](htmlcanvaselement). `HTMLCanvasElement` augments the `HTMLElement` type by adding properties such as [`height`](htmlcanvaselement/height) and methods like [`getContext()`](htmlcanvaselement/getcontext) to provide canvas-specific features.

 The overall inheritance for HTML element classes looks like this:

  ![Hierarchy of interfaces for HTML elements] 

 As such, an element inherits the properties and methods of all of its ancestors. For example, consider a [`<a>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a) element, which is represented in the DOM by an object of type [`HTMLAnchorElement`](htmlanchorelement). The element, then, includes the anchor-specific properties and methods described in that class's documentation, but also those defined by [`HTMLElement`](htmlelement) and [`Element`](element), as well as from [`Node`](node) and, finally, [`EventTarget`](eventtarget).

 Each level defines a key aspect of the utility of the element. From `Node`, the element inherits concepts surrounding the ability for the element to be contained by another element, and to contain other elements itself. Of special importance is what is gained by inheriting from `EventTarget`: the ability to receive and handle events such as mouse clicks, play and pause events, and so forth.

 There are elements that share commonalities and thus have an additional intermediary type. For example, the [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) and [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) elements both present audiovisual media. The corresponding types, [`HTMLAudioElement`](htmlaudioelement) and [`HTMLVideoElement`](htmlvideoelement), are both based upon the common type [`HTMLMediaElement`](htmlmediaelement), which in turn is based upon [`HTMLElement`](htmlelement) and so forth. `HTMLMediaElement` defines the methods and properties held in common between audio and video elements.

 These element-specific interfaces make up the majority of the HTML DOM API, and are the focus of this article. To learn more about the actual structure of the [DOM](document_object_model), see [Introduction to the DOM](document_object_model/introduction).



HTML DOM target audience
------------------------


 The features exposed by the HTML DOM are among the most commonly-used APIs in a web developer's toolkit. All but the most simple web applications will use some features of the HTML DOM. 


HTML DOM API interfaces
-----------------------


The majority of the interfaces that comprise the HTML DOM API map almost one-to-one to individual HTML elements, or to a small group of elements with similar functionality. In addition, the HTML DOM API includes a few interfaces and types to support the HTML element interfaces.


### HTML element interfaces



These interfaces represent specific HTML elements (or sets of related elements which have the same properties and methods associated with them).

 * [`HTMLAnchorElement`](htmlanchorelement)
* [`HTMLAreaElement`](htmlareaelement)
* [`HTMLAudioElement`](htmlaudioelement)
* [`HTMLBaseElement`](htmlbaseelement)
* [`HTMLBodyElement`](htmlbodyelement)
* [`HTMLBRElement`](htmlbrelement)
* [`HTMLButtonElement`](htmlbuttonelement)
* [`HTMLCanvasElement`](htmlcanvaselement)
* [`HTMLDataElement`](htmldataelement)
* [`HTMLDataListElement`](htmldatalistelement)
* [`HTMLDetailsElement`](htmldetailselement)
* [`HTMLDialogElement`](htmldialogelement)
* `HTMLDirectoryElement`
* [`HTMLDivElement`](htmldivelement)
* [`HTMLDListElement`](htmldlistelement)
* [`HTMLElement`](htmlelement)
* [`HTMLEmbedElement`](htmlembedelement)
* [`HTMLFieldSetElement`](htmlfieldsetelement)
* [`HTMLFormElement`](htmlformelement)
* [`HTMLHRElement`](htmlhrelement)
* [`HTMLHeadElement`](htmlheadelement)
* [`HTMLHeadingElement`](htmlheadingelement)
* [`HTMLHtmlElement`](htmlhtmlelement)
* [`HTMLIFrameElement`](htmliframeelement)
* [`HTMLImageElement`](htmlimageelement)
* [`HTMLInputElement`](htmlinputelement)
* [`HTMLLabelElement`](htmllabelelement)
* [`HTMLLegendElement`](htmllegendelement)
* [`HTMLLIElement`](htmllielement)
* [`HTMLLinkElement`](htmllinkelement)
* [`HTMLMapElement`](htmlmapelement)
* [`HTMLMediaElement`](htmlmediaelement)
* [`HTMLMenuElement`](htmlmenuelement)
* [`HTMLMetaElement`](htmlmetaelement)
* [`HTMLMeterElement`](htmlmeterelement)
* [`HTMLModElement`](htmlmodelement)
* [`HTMLObjectElement`](htmlobjectelement)
* [`HTMLOListElement`](htmlolistelement)
* [`HTMLOptGroupElement`](htmloptgroupelement)
* [`HTMLOptionElement`](htmloptionelement)
* [`HTMLOutputElement`](htmloutputelement)
* [`HTMLParagraphElement`](htmlparagraphelement)
* [`HTMLPictureElement`](htmlpictureelement)
* [`HTMLPreElement`](htmlpreelement)
* [`HTMLProgressElement`](htmlprogresselement)
* [`HTMLQuoteElement`](htmlquoteelement)
* [`HTMLScriptElement`](htmlscriptelement)
* [`HTMLSelectElement`](htmlselectelement)
* [`HTMLSlotElement`](htmlslotelement)
* [`HTMLSourceElement`](htmlsourceelement)
* [`HTMLSpanElement`](htmlspanelement)
* [`HTMLStyleElement`](htmlstyleelement)
* [`HTMLTableCaptionElement`](htmltablecaptionelement)
* [`HTMLTableCellElement`](htmltablecellelement)
* [`HTMLTableColElement`](htmltablecolelement)
* [`HTMLTableElement`](htmltableelement)
* [`HTMLTableRowElement`](htmltablerowelement)
* [`HTMLTableSectionElement`](htmltablesectionelement)
* [`HTMLTemplateElement`](htmltemplateelement)
* [`HTMLTextAreaElement`](htmltextareaelement)
* [`HTMLTimeElement`](htmltimeelement)
* [`HTMLTitleElement`](htmltitleelement)
* [`HTMLTrackElement`](htmltrackelement)
* [`HTMLUListElement`](htmlulistelement)
* [`HTMLUnknownElement`](htmlunknownelement)
* [`HTMLVideoElement`](htmlvideoelement)

 #### Deprecated HTML Element Interfaces

 * [`HTMLMarqueeElement`](htmlmarqueeelement)  Deprecated

 #### Obsolete HTML Element Interfaces

 * [`HTMLFontElement`](htmlfontelement)  Deprecated
* `HTMLFrameElement`  Deprecated
* [`HTMLFrameSetElement`](htmlframesetelement)  Deprecated
* `HTMLIsIndexElement`  Deprecated
* [`HTMLMenuItemElement`](htmlmenuitemelement)  Deprecated



### Web app and browser integration interfaces



These interfaces offer access to the browser window and document that contain the HTML, as well as to the browser's state, available plugins (if any), and various configuration options.

 * [`BarProp`](barprop)
* [`Navigator`](navigator)
* [`Window`](window)

 #### Deprecated web app and browser integration interfaces

 * `External`  Deprecated

 #### Obsolete web app and browser integration interfaces

 * `ApplicationCache`  Deprecated
* [`Plugin`](plugin)  Deprecated
* [`PluginArray`](pluginarray)  Deprecated



### Form support interfaces



These interfaces provide structure and functionality required by the elements used to create and manage forms, including the [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) and [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) elements.

 * [`FormDataEvent`](formdataevent)
* [`HTMLFormControlsCollection`](htmlformcontrolscollection)
* [`HTMLOptionsCollection`](htmloptionscollection)
* [`RadioNodeList`](radionodelist)
* [`ValidityState`](validitystate)



### Canvas and image interfaces



These interfaces represent objects used by the Canvas API as well as the [`<img>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img) element and [`<picture>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture) elements.

 * [`CanvasGradient`](canvasgradient)
* [`CanvasPattern`](canvaspattern)
* [`CanvasRenderingContext2D`](canvasrenderingcontext2d)
* [`ImageBitmap`](imagebitmap)
* [`ImageBitmapRenderingContext`](imagebitmaprenderingcontext)
* [`ImageData`](imagedata)
* [`OffscreenCanvas`](offscreencanvas)
* [`OffscreenCanvasRenderingContext2D`](offscreencanvasrenderingcontext2d)
* [`Path2D`](path2d)
* [`TextMetrics`](textmetrics)



### Media interfaces



The media interfaces provide HTML access to the contents of the media elements: [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) and [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video).

 * [`AudioTrack`](audiotrack)
* [`AudioTrackList`](audiotracklist)
* [`MediaError`](mediaerror)
* [`TextTrack`](texttrack)
* [`TextTrackCue`](texttrackcue)
* [`TextTrackCueList`](texttrackcuelist)
* [`TextTrackList`](texttracklist)
* [`TimeRanges`](timeranges)
* [`TrackEvent`](trackevent)
* [`VideoTrack`](videotrack)
* [`VideoTrackList`](videotracklist)



### Drag and drop interfaces



These interfaces are used by the [HTML Drag and Drop API](html_drag_and_drop_api) to represent individual draggable (or dragged) items, groups of dragged or draggable items, and to handle the drag and drop process.

 * [`DataTransfer`](datatransfer)
* [`DataTransferItem`](datatransferitem)
* [`DataTransferItemList`](datatransferitemlist)
* [`DragEvent`](dragevent)



### Page history interfaces



The History API interfaces let you access information about the browser's history, as well as to shift the browser's current tab forward and backward through that history.

 * [`BeforeUnloadEvent`](beforeunloadevent)
* [`HashChangeEvent`](hashchangeevent)
* [`History`](history)
* [`Location`](location)
* [`PageTransitionEvent`](pagetransitionevent)
* [`PopStateEvent`](popstateevent)



### Web Components interfaces



These interfaces are used by the [Web Components API](web_components) to create and manage the available [custom elements](web_components/using_custom_elements).

 * [`CustomElementRegistry`](customelementregistry)



### Miscellaneous and supporting interfaces



These supporting object types are used in a variety of ways in the HTML DOM API. In addition, [`PromiseRejectionEvent`](promiserejectionevent) represents the event delivered when a [JavaScript](https://developer.mozilla.org/en-US/docs/Glossary/JavaScript) [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) is rejected.

 * [`DOMStringList`](domstringlist)
* [`DOMStringMap`](domstringmap)
* [`ErrorEvent`](errorevent)
* `HTMLAllCollection`
* [`MimeType`](mimetype)
* [`MimeTypeArray`](mimetypearray)
* [`PromiseRejectionEvent`](promiserejectionevent)



### Interfaces belonging to other APIs



Several interfaces are technically defined in the HTML specification while actually being part of other APIs.

 #### Web storage interfaces

 The [Web Storage API](web_storage_api) provides the ability for websites to store data either temporarily or permanently on the user's device for later re-use.

 * [`Storage`](storage)
* [`StorageEvent`](storageevent)

 #### Web Workers interfaces

 These interfaces are used by the [Web Workers API](web_workers_api) both to establish the ability for workers to interact with an app and its content, but also to support messaging between windows or apps.

 * [`BroadcastChannel`](broadcastchannel)
* [`DedicatedWorkerGlobalScope`](dedicatedworkerglobalscope)
* [`MessageChannel`](messagechannel)
* [`MessageEvent`](messageevent)
* [`MessagePort`](messageport)
* [`SharedWorker`](sharedworker)
* [`SharedWorkerGlobalScope`](sharedworkerglobalscope)
* [`Worker`](worker)
* [`WorkerGlobalScope`](workerglobalscope)
* [`WorkerLocation`](workerlocation)
* [`WorkerNavigator`](workernavigator)

 #### WebSocket interfaces

 These interfaces, defined by the HTML specification, are used by the [WebSockets API](websockets_api).

 * [`CloseEvent`](closeevent)
* [`WebSocket`](websocket)

 #### Server-sent events interfaces

 The [`EventSource`](eventsource) interface represents the source which sent or is sending [server-sent events](server-sent_events).

 * [`EventSource`](eventsource)



Examples
--------


In this example, an [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) element's [`input`](htmlelement/input_event) event is monitored in order to update the state of a form's "submit" button based on whether or not a given field currently has a value.


### JavaScript




```
const nameField = document.getElementById("userName");
const sendButton = document.getElementById("sendButton");

sendButton.disabled = true;
// [note: this is disabled since it causes this article to always load with this example focused and scrolled into view]
//nameField.focus();

nameField.addEventListener("input", (event) => {
  const elem = event.target;
  const valid = elem.value.length !== 0;

  if (valid && sendButton.disabled) {
    sendButton.disabled = false;
  } else if (!valid && !sendButton.disabled) {
    sendButton.disabled = true;
  }
});

```
 This code uses the [`Document`](document) interface's [`getElementById()`](document/getelementbyid) method to get the DOM object representing the [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) elements whose IDs are `userName` and `sendButton`. With these, we can access the properties and methods that provide information about and grant control over these elements.

 The [`HTMLInputElement`](htmlinputelement) object for the "Send" button's [`disabled`](htmlinputelement/disabled) property is set to `true`, which disables the "Send" button so it can't be clicked. In addition, the user name input field is made the active focus by calling the [`focus()`](htmlelement/focus) method it inherits from [`HTMLElement`](htmlelement).

 Then [`addEventListener()`](eventtarget/addeventlistener) is called to add a handler for the `input` event to the user name input. This code looks at the length of the current value of the input; if it's zero, then the "Send" button is disabled if it's not already disabled. Otherwise, the code ensures that the button is enabled.

 With this in place, the "Send" button is always enabled whenever the user name input field has a value, and disabled when it's empty.



### HTML



The HTML for the form looks like this:

 
```
<p>Please provide the information below. Items marked with "*" are required.</p>
<form action="" method="get">
  <p>
    <label for="userName" required>Your name:</label>
    <input type="text" id="userName" /> (*)
  </p>
  <p>
    <label for="email">Email:</label>
    <input type="email" id="userEmail" />
  </p>
  <input type="submit" value="Send" id="sendButton" />
</form>

```


### Result



Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlelement](https://html.spec.whatwg.org/multipage/dom.html#htmlelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTML_DOM_API` | 1 | 12 | 1 | 5.5 | 8 | 1 | 1 | 18 | 4 | 10.1 | 1 | 1.0 |
| `accessKey` | 17 | 12 | 5 | 5.5 | ≤12.1 | 6 | 4.4 | 18 | 5 | ≤12.1 | 6 | 1.0 |
| `accessKeyLabel` | NoSee [bug 393466](https://crbug.com/393466). | NoSee [bug 393466](https://crbug.com/393466). | 8 | No | NoSee [bug 393466](https://crbug.com/393466). | 14 | NoSee [bug 393466](https://crbug.com/393466). | NoSee [bug 393466](https://crbug.com/393466). | 8 | NoSee [bug 393466](https://crbug.com/393466). | 14 | NoSee [bug 393466](https://crbug.com/393466). |
| `attachInternals` | 77 | 79 | 93 | No | 64 | 16.4See [bug 197960](https://webkit.org/b/197960). | 77 | 77 | 93 | 55 | 16.4See [bug 197960](https://webkit.org/b/197960). | 12.0 |
| `attributeStyleMap` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `autocapitalize` | 66 | 79 | 111 | No | 53 | No | 66 | 66 | 111 | 47 | 10.3 | 9.0 |
| `autofocus` | 791–79Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. | 7912–79Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. | 1Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. | 10Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. | 66≤12.1–66Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. | 15.44Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. | 79≤37–79Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. | 7918–79Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. | 4Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. | 57≤12.1–57Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. | 15.43.2Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. | 12.01.0–12.0Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. |
| `beforeinput_event` | 60 | 79 | 87 | No | 47 | 10.1 | 60 | 60 | 87 | 44 | 10.3 | 8.0 |
| `beforematch_event` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `beforetoggle_event` | 114 | 114 | No | No | No | No | 114 | 114 | No | No | No | No |
| `blur` | 1 | 12 | 1.5 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `change_event` | 1 | 12 | 1 | 9 | 9 | 3 | 4.4 | 18 | 4 | 10.1 | 2 | 1.0 |
| `click` | 9Before Chrome 19, `click()` is only defined on buttons and inputs. | 12 | 3["Before Firefox 5, `click()` is only defined on buttons and inputs, and has no effect on text and file inputs.", "Starting in Firefox 75, the `click()` function works even when the element is not attached to a DOM tree."] | 5.5 | 10.5 | 6 | 4.4Before Android WebView 4.4, `click()` is only defined on buttons and inputs. | 18Before Chrome 19, `click()` is only defined on buttons and inputs. | 4["Before Firefox 5, `click()` is only defined on buttons and inputs, and has no effect on text and file inputs.", "Starting in Firefox for Android 79, the `click()` function works even when the element is not attached to a DOM tree."] | 11 | 6 | 1.0Before Samsung Internet 1.5, `click()` is only defined on buttons and inputs. |
| `contentEditable` | 1 | 12 | 3 | 5.5 | 9 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `dataset` | 7 | 12 | 6 | 11 | 11 | 5.1 | 3 | 18 | 6 | 11 | 5 | 1.0 |
| `dir` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `drag_event` | 1 | 12 | 9 | 9 | 12 | 3.1 | 4.4 | 18 | 9 | 12 | 2 | 1.0 |
| `dragend_event` | 1 | 12 | 9 | 9 | 12 | 3.1 | 4.4 | 18 | 9 | 12 | 2 | 1.0 |
| `dragenter_event` | 1 | 12 | 9 | 9 | 12 | 3.1 | 4.4 | 18 | 9 | 12 | 2 | 1.0 |
| `dragexit_event` | No | 12–79 | 3.5 | 10 | 12 | 3.1 | No | No | 4 | No | No | No |
| `draggable` | 4 | 12 | 2 | 10 | 12 | 5 | 4.4 | 18 | 4 | 12 | 4 | 1.0 |
| `dragleave_event` | 1 | 12 | 9 | 9 | 12 | 3.1 | 4.4 | 18 | 9 | 12 | 2 | 1.0 |
| `dragover_event` | 1 | 12 | 9 | 9 | 12 | 3.1 | 4.4 | 18 | 9 | 12 | 2 | 1.0 |
| `dragstart_event` | 1 | 12 | 9 | 9 | 12 | 3.1 | 4.4 | 18 | 9 | 12 | 2 | 1.0 |
| `drop_event` | 1 | 12 | 9 | 9 | 12 | 3.1 | 4.4 | 18 | 9 | 12 | 2 | 1.0 |
| `enterKeyHint` | 77 | 79 | 94 | No | 64 | 13.1 | 77 | 77 | 94 | 55 | 13.4 | 12.0 |
| `focus` | 1 | 12 | 1.5 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `hidden` | 6 | 12 | 4 | 11 | 11.6 | 5.1 | 3 | 18 | 4 | 12 | 5 | 1.0 |
| `hidePopover` | 114 | 114 | No | No | No | No | 114 | 114 | No | No | No | No |
| `inert` | 102 | 102 | 112 | No | 88 | 15.5 | 102 | 102 | 112 | 70 | 15.5 | 19.0 |
| `innerText` | 1 | 12 | 45 | 5.5 | 9.6 | 1 | 1 | 18 | 45 | 10.1 | 1 | 1.0 |
| `inputMode` | 66 | 79 | 95 | No | 53 | 12.1 | 66 | 66 | 79 | 47 | 12.2 | 9.0 |
| `input_event` | 1 | 7912–79Not supported on `select`, `checkbox`, or `radio` inputs. | 6 | 9Only supports `input` of type `text` and `password`. | 11.6 | 3.1 | 4.4 | 18 | 6 | 12 | 2 | 1.0 |
| `isContentEditable` | 1 | 12 | 4 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `lang` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `nonce` | 61 | 79 | 75 | No | 48 | 10The property is defined only for its useful elements: `<link>`, `<script>`, and `<style>`; it is undefined for all other elements. | 61 | 61 | 79 | 45 | 10The property is defined only for its useful elements: `<link>`, `<script>`, and `<style>`; it is undefined for all other elements. | 8.0 |
| `offsetHeight` | 1 | 12 | 1 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `offsetLeft` | 1 | 12 | 1 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `offsetParent` | 1 | 12 | 1 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `offsetTop` | 1 | 12 | 1 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `offsetWidth` | 1 | 12 | 1 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `outerText` | 1 | 12 | 98 | 5.5 | ≤12.1 | 1.3 | 1 | 18 | 98 | ≤12.1 | 1 | 1.0 |
| `popover` | 114 | 114 | No | No | No | No | 114 | 114 | No | No | No | No |
| `showPopover` | 114 | 114 | No | No | No | No | 114 | 114 | No | No | No | No |
| `spellcheck` | 9 | 12 | 2 | 10 | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `style` | 1 | 12 | 1 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `tabIndex` | 1 | 1812Returns incorrect value for elements without an explicit tabindex attribute. See [issue 4365703](https://developer.microsoft.com/microsoft-edge/platform/issues/4365703/) for details. | 1 | 5.5Returns incorrect value for elements without an explicit tabindex attribute. See [issue 4365703](https://developer.microsoft.com/microsoft-edge/platform/issues/4365703/) for details. | ≤12.1 | 3.1 | 4.4 | 18 | 4 | ≤12.1 | 2 | 1.0 |
| `title` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `togglePopover` | 114 | 114 | No | No | No | No | 114 | 114 | No | No | No | No |
| `toggle_event` | 114 | 114 | No | No | No | No | 114 | 114 | No | No | No | No |
| `translate` | 19 | 79 | 111 | No | 15 | 6 | 4.4 | 25 | 111 | 14 | 6 | 1.5 |
| `virtualKeyboardPolicy` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |


See also
--------


### References


* [HTML elements reference](https://developer.mozilla.org/en-US/docs/Web/HTML/Element)
* [HTML attribute reference](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes)
* [Document Object Model (DOM)](document_object_model) reference

### Guides


* [Manipulating documents](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents): A beginner's guide to manipulating the DOM.


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API>

HTML Drag and Drop API
======================



**HTML Drag and Drop** interfaces enable applications to use drag-and-drop features in browsers.

 The user may select *draggable* elements with a mouse, drag those elements to a *droppable* element, and drop them by releasing the mouse button. A translucent representation of the *draggable* elements follows the pointer during the drag operation.

 You can customize which elements can become *draggable*, the type of feedback the *draggable* elements produce, and the *droppable* elements.

 This overview of HTML Drag and Drop includes a description of the interfaces, basic steps to add drag-and-drop support to an application, and an interoperability summary of the interfaces.



Concepts and usage
------------------


### Drag Events



HTML drag-and-drop uses the [`DOM event model`](event) and *[`drag events`](dragevent)* inherited from [`mouse events`](mouseevent). A typical *drag operation* begins when a user selects a *draggable* element, continues when the user drags the element to a *droppable* element, and then ends when the user releases the dragged element.

 During drag operations, several event types are fired, and some events might fire many times, such as the [`drag`](htmlelement/drag_event) and [`dragover`](htmlelement/dragover_event) events.

 Each [drag event type](dragevent#event_types) has an associated event handler:

 

| Event | Fires when... |
| --- | --- |
| [`drag`](htmlelement/drag_event) | ...a *dragged item* (element or text selection) is dragged. |
| [`dragend`](htmlelement/dragend_event) | ...a drag operation ends (such as releasing a mouse button or hitting the Esc key; see [Finishing a Drag](html_drag_and_drop_api/drag_operations#dragend).) |
| [`dragenter`](htmlelement/dragenter_event) | ...a dragged item enters a valid drop target. (See [Specifying Drop Targets](html_drag_and_drop_api/drag_operations#specifying_drop_targets).) |
| [`dragleave`](htmlelement/dragleave_event) | ...a dragged item leaves a valid drop target. |
| [`dragover`](htmlelement/dragover_event) | ...a dragged item is being dragged over a valid drop target, every few hundred milliseconds. |
| [`dragstart`](htmlelement/dragstart_event) | ...the user starts dragging an item. (See [Starting a Drag Operation](html_drag_and_drop_api/drag_operations#dragstart).) |
| [`drop`](htmlelement/drop_event) | ...an item is dropped on a valid drop target. (See [Performing a Drop](html_drag_and_drop_api/drag_operations#drop).) |

  **Note:** Neither `dragstart` nor `dragend` events are fired when dragging a file into the browser from the OS.

 

### The basics



This section is a summary of the basic steps to add drag-and-drop functionality to an application.

 #### Identify what is draggable

 Making an element *draggable* requires adding the [`draggable`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#draggable) attribute and the [`ondragstart`](htmlelement/dragstart_event) event handler, as shown in the following code sample:

 
```
<script>
 function dragstart\_handler(ev) {
 // Add the target element's id to the data transfer object
 ev.dataTransfer.setData("text/plain", ev.target.id);
 }

 window.addEventListener("DOMContentLoaded", () => {
 // Get the element by id
 const element = document.getElementById("p1");
 // Add the ondragstart event listener
 element.addEventListener("dragstart", dragstart\_handler);
 });
</script>

<p id="p1" draggable="true">This element is draggable.</p>

```
 For more information, see:

 * [Draggable attribute reference](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/draggable)
* [Drag operations guide](html_drag_and_drop_api/drag_operations#draggableattribute)

 #### Define the drag's data

 The application is free to include any number of data items in a drag operation. Each data item is a string of a particular `type` — typically a MIME type such as `text/html`.

 Each [`drag event`](dragevent) has a [`dataTransfer`](dragevent/datatransfer) property that *holds* the event's data. This property (which is a [`DataTransfer`](datatransfer) object) also has methods to *manage* drag data. The [`setData()`](datatransfer/setdata) method is used to add an item to the drag data, as shown in the following example.

 
```
function dragstart\_handler(ev) {
  // Add different types of drag data
  ev.dataTransfer.setData("text/plain", ev.target.innerText);
  ev.dataTransfer.setData("text/html", ev.target.outerHTML);
  ev.dataTransfer.setData(
    "text/uri-list",
    ev.target.ownerDocument.location.href
  );
}

```
 * For a list of common data types used in drag-and-drop (such as text, HTML, links, and files), see [Recommended Drag Types](html_drag_and_drop_api/recommended_drag_types).
* For more information about drag data, see [Drag Data](html_drag_and_drop_api/drag_operations#drag_data).

 #### Define the drag image

 By default, the browser supplies an image that appears beside the pointer during a drag operation. However, an application may define a custom image with the [`setDragImage()`](datatransfer/setdragimage) method, as shown in the following example.

 
```
// Create an image and then use it for the drag image.
// NOTE: change "example.gif" to a real image URL or the image
// will not be created and the default drag image will be used.
let img = new Image();
img.src = "example.gif";
function dragstart\_handler(ev) {
  ev.dataTransfer.setDragImage(img, 10, 10);
}

```
 Learn more about drag feedback images in:

 * [Setting the Drag Feedback Image](html_drag_and_drop_api/drag_operations#setting_the_drag_feedback_image)

 #### Define the drop effect

 The [`dropEffect`](datatransfer/dropeffect) property is used to control the feedback the user is given during a drag-and-drop operation. It typically affects which cursor the browser displays while dragging. For example, when the user hovers over a drop target, the browser's cursor may indicate the type of operation that will occur.

 Three effects may be defined:

 1. `copy` indicates that the dragged data will be copied from its present location to the drop location.
2. `move` indicates that the dragged data will be moved from its present location to the drop location.
3. `link` indicates that some form of relationship or connection will be created between the source and drop locations.

 During the drag operation, drag effects may be modified to indicate that certain effects are allowed at certain locations.

 The following example shows how to use this property.

 
```
function dragstart\_handler(ev) {
  ev.dataTransfer.dropEffect = "copy";
}

```
 For more details, see:

 * [Drag Effects](html_drag_and_drop_api/drag_operations#drag_effects)

 #### Define a drop zone

 By default, the browser prevents anything from happening when dropping something onto most HTML elements. To change that behavior so that an element becomes a *drop zone* or is *droppable*, the element must have both [`ondragover`](htmlelement/dragover_event) and [`ondrop`](htmlelement/drop_event) event handler attributes.

 The following example shows how to use those attributes, and includes basic event handlers for each attribute.

 
```
<script>
 function dragover\_handler(ev) {
 ev.preventDefault();
 ev.dataTransfer.dropEffect = "move";
 }
 function drop\_handler(ev) {
 ev.preventDefault();
 // Get the id of the target and add the moved element to the target's DOM
 const data = ev.dataTransfer.getData("text/plain");
 ev.target.appendChild(document.getElementById(data));
 }
</script>

<p
 id="target"
 ondrop="drop\_handler(event)"
 ondragover="dragover\_handler(event)">
  Drop Zone
</p>

```
 Note that each handler calls [`preventDefault()`](event/preventdefault) to prevent additional event processing for this event (such as [touch events](touch_events) or [pointer events](pointer_events)).

 For more information, see:

 * [Specifying Drop Targets](html_drag_and_drop_api/drag_operations#specifying_drop_targets)

 #### Handle the drop effect

 The handler for the [`drop`](htmlelement/drop_event) event is free to process the drag data in an application-specific way.

 Typically, an application uses the [`getData()`](datatransfer/getdata) method to retrieve drag items and then process them accordingly. Additionally, application semantics may differ depending on the value of the [`dropEffect`](datatransfer/dropeffect) and/or the state of modifier keys.

 The following example shows a drop handler getting the source element's `id` from the drag data, and then using the `id` to move the source element to the drop element:

 
```
<script>
 function dragstart\_handler(ev) {
 // Add the target element's id to the data transfer object
 ev.dataTransfer.setData("application/my-app", ev.target.id);
 ev.dataTransfer.effectAllowed = "move";
 }
 function dragover\_handler(ev) {
 ev.preventDefault();
 ev.dataTransfer.dropEffect = "move";
 }
 function drop\_handler(ev) {
 ev.preventDefault();
 // Get the id of the target and add the moved element to the target's DOM
 const data = ev.dataTransfer.getData("application/my-app");
 ev.target.appendChild(document.getElementById(data));
 }
</script>

<p id="p1" draggable="true" ondragstart="dragstart\_handler(event)">
  This element is draggable.
</p>
<div
 id="target"
 ondrop="drop\_handler(event)"
 ondragover="dragover\_handler(event)">
  Drop Zone
</div>

```
 For more information, see:

 * [Performing a Drop](html_drag_and_drop_api/drag_operations#performing_a_drop)

 #### Drag end

 At the end of a drag operation, the [`dragend`](htmlelement/dragend_event) event fires at the *source* element — the element that was the target of the drag start.

 This event fires regardless of whether the drag completed or was canceled. The [`dragend`](htmlelement/dragend_event) event handler can check the value of the [`dropEffect`](datatransfer/dropeffect) property to determine if the drag operation succeeded or not.

 For more information about handling the end of a drag operation, see:

 * [Finishing a Drag](html_drag_and_drop_api/drag_operations#finishing_a_drag)



Interfaces
----------



The HTML Drag and Drop interfaces are [`DragEvent`](dragevent), [`DataTransfer`](datatransfer), [`DataTransferItem`](datatransferitem) and [`DataTransferItemList`](datatransferitemlist).

 The [`DragEvent`](dragevent) interface has a constructor and one [`dataTransfer`](dragevent/datatransfer) property, which is a [`DataTransfer`](datatransfer) object.

 [`DataTransfer`](datatransfer) objects include the drag event's state, such as the type of drag being done (like `copy` or `move`), the drag's data (one or more items), and the MIME type of each *drag item*. [`DataTransfer`](datatransfer) objects also have methods to add or remove items to the drag's data.

 The [`DragEvent`](dragevent) and [`DataTransfer`](datatransfer) interfaces should be the only ones needed to add HTML Drag and Drop capabilities to an application. (Firefox supports some [Gecko-specific extensions](#gecko_specific_interfaces) to the [`DataTransfer`](datatransfer) object, but those extensions will only work on Firefox.)

 Each [`DataTransfer`](datatransfer) object contains an [`items`](datatransfer/items) property, which is a [`list`](datatransferitemlist) of [`DataTransferItem`](datatransferitem) objects. A [`DataTransferItem`](datatransferitem) object represents a single *drag item*, each with a [`kind`](datatransferitem/kind) property (either `string` or `file`) and a [`type`](datatransferitem/type) property for the data item's MIME type. The [`DataTransferItem`](datatransferitem) object also has methods to get the drag item's data.

 The [`DataTransferItemList`](datatransferitemlist) object is a list of [`DataTransferItem`](datatransferitem) objects. The list object has methods to add a drag item to the list, remove a drag item from the list, and clear the list of all drag items.

 A key difference between the [`DataTransfer`](datatransfer) and [`DataTransferItem`](datatransferitem) interfaces is that the former uses the synchronous [`getData()`](datatransfer/getdata) method to access a drag item's data, but the latter instead uses the asynchronous [`getAsString()`](datatransferitem/getasstring) method.

  **Note:** [`DragEvent`](dragevent) and [`DataTransfer`](datatransfer) are broadly supported on desktop browsers. However, the [`DataTransferItem`](datatransferitem) and [`DataTransferItemList`](datatransferitemlist) interfaces have limited browser support. See [Interoperability](#interoperability) for more information about drag-and-drop interoperability.

 

Examples
--------


* [Copying and moving elements with the `DataTransfer` interface](https://mdn.github.io/dom-examples/drag-and-drop/copy-move-DataTransfer.html)
* [Copying and moving elements with the `DataTransferListItem` interface](https://mdn.github.io/dom-examples/drag-and-drop/copy-move-DataTransferItemList.html)
* Dragging and dropping files (Firefox only): <https://jsfiddle.net/9C2EF/>
* Dragging and dropping files (All browsers): [https://jsbin.com/hiqasek/](https://jsbin.com/hiqasek/edit?html,js,output)
* A parking project using the Drag and Drop API: <https://park.glitch.me/> (You can edit [here](https://glitch.com/edit/#!/park))

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # dnd](https://html.spec.whatwg.org/multipage/#dnd) |


See also
--------


* [Drag Operations](html_drag_and_drop_api/drag_operations)
* [Recommended Drag Types](html_drag_and_drop_api/recommended_drag_types)
* [HTML Living Standard: Drag and Drop](https://html.spec.whatwg.org/multipage/interaction.html#dnd)
* [Drag and Drop interoperability data from CanIUse](https://caniuse.com/#search=draganddrop)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API>

HTML Sanitizer API
==================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.


**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The **HTML Sanitizer API** allow developers to take untrusted strings of HTML and [`Document`](document) or [`DocumentFragment`](documentfragment) objects, and sanitize them for safe insertion into a document's DOM.



Concepts and usage
------------------



 Web applications often need to work with untrusted HTML on the client side, for example, as part of a client-side templating solution or for rendering user generated content, or when including data in a frame from another site. The Sanitizer API allows for rendering of this potentially untrusted HTML in a safe manner. 

  To access the API you would use the [`Sanitizer()`](sanitizer/sanitizer) constructor to create and configure a [`Sanitizer`](sanitizer) instance. The configuration options parameter allows you to specify the allowed and dis-allowed elements and attributes, and to enable custom elements and comments. 

  The most common use-case - preventing XSS - is handled by the default configuration. Creating a [`Sanitizer()`](sanitizer/sanitizer) with a custom configuration is necessary only to handle additional, application-specific use cases. 

 The API has three main methods for sanitizing data:

 1. [`Element.setHTML()`](element/sethtml) parses and sanitizes a string of HTML and immediately inserts it into the DOM as a child of the current element. This is essentially a "safe" version of [`Element.innerHTML`](element/innerhtml), and should be used instead of `innerHTML` when inserting untrusted data.
2. [`Sanitizer.sanitizeFor()`](sanitizer/sanitizefor) parses and sanitizes a string of HTML for later insertion into the DOM. This might be used when the target element for the string is not always ready/available for update.
3. [`Sanitizer.sanitize()`](sanitizer/sanitize) sanitizes data that is in a [`Document`](document) or [`DocumentFragment`](documentfragment). It might be used, for example, to sanitize a [`Document`](document) instance in a frame.



### Parsing and sanitizing strings



The result of parsing a string of HTML depends on the context/the element into which it is inserted.

  For example, an HTML string containing [`<td>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td) elements is valid if inserted under a [`<table>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table) elements, but will be dropped if inserted in a [`<div>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div) element. Similarly, an [`<em>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/em) element is a valid node in a [`<div>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div) but the tag will be escaped if used in a [`<textarea>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea): 

 
```
<!-- "<em>bla</em>" inserted into <div> -->
<div><em>bla</em></div>

<!-- "<em>bla</em>" inserted into <textarea> -->
<textarea>&lt;em&gt;bla</textarea>

```
 The target element must therefore be known when the parser is run and the resulting subtree must be inserted into that same type of element in the DOM, or the result will be incorrect.

  For this reason when using [`Sanitizer.sanitizeFor()`](sanitizer/sanitizefor) developers must specify the tag of the eventual target element as a parameter, and the method returns a matching HTML element with the parsed string as a child (for example, the target tag `"div"` results in a returned object that is an instance of [`HTMLDivElement`](htmldivelement)). The return type ensures that a user always has the context in which the object must be inserted into the DOM. 

 This consideration does not matter for [`Element.setHTML()`](element/sethtml) as it is called on a particular element and the context is therefore implicit.

  The parser may also perform normalization operations on the input string. As a result, even if the HTML is valid and the sanitizer method does nothing, the sanitized output may not precisely match the unsanitized input. This applies to both methods. 



Interfaces
----------


 
[`Sanitizer`](sanitizer)  Experimental 
  Provides the functionality to define a sanitizer configuration, to sanitize untrusted strings of HTML for later insertion into the DOM, and to sanitize [`Document`](document) and [`DocumentFragment`](documentfragment) objects.

  [`Element.setHTML()`](element/sethtml)  Parses a string of HTML into a subtree of nodes, sanitizes it using a `Sanitizer` object, then sets it as a child of the current element.

  
Examples
--------


The following examples show how to use the sanitizer API using the *default* sanitizer (at time of writing configuration operations are not yet supported).


### Sanitize a string immediately



The code below demonstrates how [`Element.setHTML()`](element/sethtml) is used to sanitize a string of HTML and insert it into the `Element` with an id of `target`.

 The `script` element is disallowed by the default sanitizer so the alert is removed.

 
```
const unsanitized_string = "abc <script>alert(1)<" + "/script> def"; // Unsanitized string of HTML

const sanitizer = new Sanitizer(); // Default sanitizer;

// Get the Element with id "target" and set it with the sanitized string.
const target = document.getElementById("target");
target.setHTML(unsanitized_string, { sanitizer });

console.log(target.innerHTML);
// "abc def"

```


### Sanitize a string for deferred use



The example below shows the same sanitization operation using the [`Sanitizer.sanitizeFor()`](sanitizer/sanitizefor) method, with the intent of later inserting the returned element into a `<div>` element:

 
```
const unsanitized_string = "abc <script>alert(1)<" + "/script> def"; // Unsanitized string of HTML
const sanitizer = new Sanitizer(); // Default sanitizer;

// Sanitize the string
const sanitizedDiv = sanitizer.sanitizeFor("div", unsanitized_string);

//We can verify the returned element type, and view sanitized HTML in string form:
console.log(sanitizedDiv instanceof HTMLDivElement);
// true
console.log(sanitizedDiv.innerHTML);
// "abc def"

// At some point later…

// Get the element to update. This must be a div to match our sanitizeFor() context.
// Set its content to be the children of our sanitized element.
document.querySelector("div#target").replaceChildren(sanitizedDiv.children);

```
   **Note:** If you really must perform a string-to-string operation you can extract the string using `innerHTML`, but you must remember to use the correct context when the string is applied: 

 
```
const unsanitized_string = "abc <script>alert(1)<" + "/script> def";
const sanitizedString = new Sanitizer().sanitizeFor(
  "div",
  unsanitized_string
).innerHTML;

```
 

### Sanitize a frame



To sanitize data from an [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe) with id `userFrame`:

 
```
const sanitizer = new Sanitizer(); // Default sanitizer;

// Get the frame and its Document object
const frame_element = document.getElementById("userFrame");
const unsanitized_frame_tree = frame_element.contentWindow.document;

// Sanitize the document tree and update the frame.
const sanitized_frame_tree = sanitizer.sanitize(unsanitized_frame_tree);
frame_element.replaceChildren(sanitized_frame_tree);

```


Specifications
--------------




| Specification |
| --- |
| [HTML Sanitizer API # sanitizer-api](https://wicg.github.io/sanitizer-api/#sanitizer-api) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Sanitizer` | 10593–105 | 10593–105 | 83 | No | 79 | No | 105 | 10593–105 | No | 72 | No | 20.0 |
| `HTML_Sanitizer_API` | 10593–105 | 10593–105 | 83 | No | 79 | No | 105 | 10593–105 | No | 72 | No | 20.0 |
| `getConfiguration` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `getDefaultConfiguration` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `sanitize` | 93 | 93 | 83 | No | 79 | No | No | 93 | No | No | No | No |
| `sanitizeFor` | 93 | 93 | No | No | 79 | No | No | 93 | No | No | No | No |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTML_Sanitizer_API>

History API
===========



The **History API** provides access to the browser's session history (not to be confused with [WebExtensions history](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/history)) through the [`history`](window/history) global object. It exposes useful methods and properties that let you navigate back and forth through the user's history, and manipulate the contents of the history stack.

  **Note:** This API is only available on the main thread ([`Window`](window)). It cannot be accessed in [`Worker`](worker) or [`Worklet`](worklet) contexts.

 

Concepts and usage
------------------


Moving backward and forward through the user's history is done using the [`back()`](history/back), [`forward()`](history/forward), and [`go()`](history/go) methods.


### Moving forward and backward



To move backward through history:

 
```
history.back();

```
 This acts exactly as if the user clicked on the `**Back**` button in their browser toolbar.

 Similarly, you can move forward (as if the user clicked the `**Forward**` button), like this:

 
```
history.forward();

```


### Moving to a specific point in history



You can use the [`go()`](history/go) method to load a specific page from session history, identified by its relative position to the current page. (The current page's relative position is `0`.)

 To move back one page (the equivalent of calling [`back()`](history/back)):

 
```
history.go(-1);

```
 To move forward a page, just like calling [`forward()`](history/forward):

 
```
history.go(1);

```
 Similarly, you can move forward 2 pages by passing `2`, and so forth.

 Another use for the `go()` method is to refresh the current page by either passing `0`, or by invoking it without an argument:

 
```
// The following statements
// both have the effect of
// refreshing the page
history.go(0);
history.go();

```
 You can determine the number of pages in the history stack by looking at the value of the `length` property:

 
```
const numberOfEntries = history.length;

```


Interfaces
----------


 [`History`](history)  Allows manipulation of the browser *session history* (that is, the pages visited in the tab or frame that the current page is loaded in).

  [`PopStateEvent`](popstateevent)  The interface of the [`popstate`](window/popstate_event) event.

  
Examples
--------



The following example assigns a listener for the [`popstate`](window/popstate_event) event. It then illustrates some of the methods of the history object to add, replace, and move within the browser history for the current tab.

 
```
window.addEventListener("popstate", (event) => {
  alert(
    `location: ${document.location}, state: ${JSON.stringify(event.state)}`
  );
});

history.pushState({ page: 1 }, "title 1", "?page=1");
history.pushState({ page: 2 }, "title 2", "?page=2");
history.replaceState({ page: 3 }, "title 3", "?page=3");
history.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // alerts "location: http://example.com/example.html, state: null"
history.go(2); // alerts "location: http://example.com/example.html?page=3, state: {"page":3}"

```


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-history-interface](https://html.spec.whatwg.org/multipage/nav-history-apis.html#the-history-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `History_API` | 1 | 12 | 1 | 10 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `back` | 1 | 12 | 1 | 10 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `forward` | 1 | 12 | 1 | 10 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `go` | 1 | 12 | 1 | 10 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `length` | 1 | 12 | 1 | 10 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `pushState` | 5 | 12 | 4Until Firefox 5, the passed object is serialized using JSON. Starting in Firefox 6, the object is serialized using [the structured clone algorithm](https://developer.mozilla.org/docs/DOM/The_structured_clone_algorithm). This allows a wider variety of objects to be safely passed. | 10 | 11.5 | 5 | ≤37 | 18 | 4Until Firefox 5, the passed object is serialized using JSON. Starting in Firefox 6, the object is serialized using [the structured clone algorithm](https://developer.mozilla.org/docs/DOM/The_structured_clone_algorithm). This allows a wider variety of objects to be safely passed. | 11.5 | 4 | 1.0 |
| `replaceState` | 5 | 12 | 4Until Firefox 5, the passed object is serialized using JSON. Starting in Firefox 6, the object is serialized using [the structured clone algorithm](https://developer.mozilla.org/docs/DOM/The_structured_clone_algorithm). This allows a wider variety of objects to be safely passed. | 10 | 11.5 | 5 | ≤37 | 18 | 4Until Firefox 5, the passed object is serialized using JSON. Starting in Firefox 6, the object is serialized using [the structured clone algorithm](https://developer.mozilla.org/docs/DOM/The_structured_clone_algorithm). This allows a wider variety of objects to be safely passed. | 11.5 | 4 | 1.0 |
| `scrollRestoration` | 46 | 79 | 46 | No | 33 | 11 | 46 | 46 | 46 | 33 | 11 | 5.0 |
| `state` | 19 | 12 | 4 | 10 | ≤12.1 | 6 | 4.4 | 25 | 4 | ≤12.1 | 6 | 1.5 |


See also
--------


* [`history`](window/history) global object
* [`popstate`](window/popstate_event) event


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/History_API>

Idle Detection API
==================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The Idle Detection API provides a means to detect the user's idle status, active, idle, and locked, specifically, and to be notified of changes to idle status without polling from a script.



Concepts and Usage
------------------


Native applications and browser extensions use idle detection base user experiences on when a user is interacting with a device. For example, chat applications can show other users of an application whether someone is available. Other applications might choose to show notifications only when a user is interacting with the app. A web application could use this API for similar use cases. Additionally, a progressive web app could use idle detection to trigger a service worker update when the app isn't being used.


Interfaces
----------


 
[`IdleDetector`](idledetector)  Experimental 
  Provides methods and events for detecting user activity on a device or screen.

  
Examples
--------



 The following example shows creating a detector and logging changes to the user's idle state. A button is used to get the necessary user activation before requesting permission. 

 
```
const controller = new AbortController();
const signal = controller.signal;

startButton.addEventListener("click", async () => {
  if ((await IdleDetector.requestPermission()) !== "granted") {
    console.error("Idle detection permission denied.");
    return;
  }

  try {
    const idleDetector = new IdleDetector();
    idleDetector.addEventListener("change", () => {
      const userState = idleDetector.userState;
      const screenState = idleDetector.screenState;
      console.log(`Idle change: ${userState}, ${screenState}.`);
    });

    await idleDetector.start({
      threshold: 60\_000,
      signal,
    });
    console.log("IdleDetector is active.");
  } catch (err) {
    // Deal with initialization errors like permission denied,
    // running outside of top-level frame, etc.
    console.error(err.name, err.message);
  }
});

stopButton.addEventListener("click", () => {
  controller.abort();
  console.log("IdleDetector is stopped.");
});

```


Specifications
--------------




| Specification |
| --- |
| [Idle Detection API # api-idledetector](https://wicg.github.io/idle-detection/#api-idledetector) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `IdleDetector` | 94 | 94–96 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `Idle_Detection_API` | 94 | 94–96 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `change_event` | 94 | 94–96 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `requestPermission` | 94 | 94–96 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `screenState` | 94 | 94–96 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `start` | 94 | 94–96 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `userState` | 94 | 94–96 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Idle_Detection_API>

MediaStream Image Capture API
=============================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The **MediaStream Image Capture API** is an API for capturing images or videos from a photographic device. In addition to capturing data, it also allows you to retrieve information about device capabilities such as image size, red-eye reduction and whether or not there is a flash and what they are currently set to. Conversely, the API allows the capabilities to be configured within the constraints what the device allows.



MediaStream image capture concepts and usage
--------------------------------------------



The process of retrieving an image or video stream happens as described below. The example code is adapted from [Chrome's Image Capture examples](https://googlechrome.github.io/samples/image-capture/).

 First, get a reference to a device by calling [`MediaDevices.getUserMedia()`](mediadevices/getusermedia). The example below says give me whatever video device is available, though the `getUserMedia()` method allows more specific capabilities to be requested. This method returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with a [`MediaStream`](mediastream) object.

 
```
navigator.mediaDevices.getUserMedia({ video: true }).then((mediaStream) => {
  // Do something with the stream.
});

```
 Next, isolate the visual part of the media stream. Do this by calling [`MediaStream.getVideoTracks()`](mediastream/getvideotracks). This returns an array of [`MediaStreamTrack`](mediastreamtrack) objects. The code below assumes that the first item in the `MediaStreamTrack` array is the one to use. You can use the properties of the `MediaStreamTrack` objects to select the one you need.

 
```
const track = mediaStream.getVideoTracks()[0];

```
 At this point, you might want to configure the device capabilities before capturing an image. You can do this by calling [`applyConstraints()`](mediastreamtrack/applyconstraints) on the track object before doing anything else.

 
```
let zoom = document.querySelector("#zoom");
const capabilities = track.getCapabilities();
// Check whether zoom is supported or not.
if (!capabilities.zoom) {
  return;
}
track.applyConstraints({ advanced: [{ zoom: zoom.value }] });

```
 Finally, pass the `MediaStreamTrack` object to the [`ImageCapture()`](imagecapture/imagecapture) constructor. Though a `MediaStream` holds several types of tracks and provides multiple methods for retrieving them, the ImageCapture constructor will throw a [`DOMException`](domexception) of type `NotSupportedError` if [`MediaStreamTrack.kind`](mediastreamtrack/kind) is not `"video"`.

 
```
let imageCapture = new ImageCapture(track);

```


Interfaces
----------


 
[`ImageCapture`](imagecapture)  Experimental 
  An interface for capturing images from a photographic device referenced through a valid [`MediaStreamTrack`](mediastreamtrack).

  
Specifications
--------------




| Specification |
| --- |
| [MediaStream Image Capture # imagecaptureapi](https://w3c.github.io/mediacapture-image/#imagecaptureapi) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ImageCapture` | 59 | 79 | NoSee [bug 888177](https://bugzil.la/888177). | No | 46 | No | 59 | 59 | NoSee [bug 888177](https://bugzil.la/888177). | 43 | No | 7.0 |
| `MediaStream_Image_Capture_API` | 59 | 79 | NoSee [bug 888177](https://bugzil.la/888177). | No | 46 | No | 59 | 59 | NoSee [bug 888177](https://bugzil.la/888177). | 43 | No | 7.0 |
| `getPhotoCapabilities` | 59 | 79 | NoSee [bug 888177](https://bugzil.la/888177). | No | 46 | No | 59 | 59 | NoSee [bug 888177](https://bugzil.la/888177). | 43 | No | 7.0 |
| `getPhotoSettings` | 61 | 79 | NoSee [bug 888177](https://bugzil.la/888177). | No | 46 | No | 61 | 61 | NoSee [bug 888177](https://bugzil.la/888177). | 43 | No | 8.0 |
| `grabFrame` | 59 | 79 | NoSee [bug 888177](https://bugzil.la/888177). | No | 46 | No | 59 | 59 | NoSee [bug 888177](https://bugzil.la/888177). | 43 | No | 7.0 |
| `takePhoto` | 6059–60`photoSettings` parameter not supported. | 79 | NoSee [bug 888177](https://bugzil.la/888177). | No | 4746–47`photoSettings` parameter not supported. | No | 6059–60`photoSettings` parameter not supported. | 6059–60`photoSettings` parameter not supported. | NoSee [bug 888177](https://bugzil.la/888177). | 4443–44`photoSettings` parameter not supported. | No | 8.07.0–8.0`photoSettings` parameter not supported. |
| `track` | 59 | 79 | NoSee [bug 888177](https://bugzil.la/888177). | No | 46 | No | 59 | 59 | NoSee [bug 888177](https://bugzil.la/888177). | 43 | No | 7.0 |


See also
--------


* [`MediaStream`](mediastream)
* [`MediaStreamTrack`](mediastreamtrack)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaStream_Image_Capture_API>

IndexedDB API
=============



IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files/blobs. This API uses indexes to enable high-performance searches of this data. While [Web Storage](web_storage_api) is useful for storing smaller amounts of data, it is less useful for storing larger amounts of structured data. IndexedDB provides a solution. This is the main landing page for MDN's IndexedDB coverage — here we provide links to the full API reference and usage guides, browser support details, and some explanation of key concepts.


 **Note:** This feature is available in [Web Workers](web_workers_api)

   **Note:** IndexedDB API is powerful, but may seem too complicated for simple cases. If you'd prefer a simple API, try libraries in [See also](#see_also) section that make IndexedDB more programmer-friendly.

 

Key concepts and usage
----------------------



IndexedDB is a transactional database system, like an SQL-based RDBMS. However, unlike SQL-based RDBMSes, which use fixed-column tables, IndexedDB is a JavaScript-based object-oriented database. IndexedDB lets you store and retrieve objects that are indexed with a **key**; any objects supported by the [structured clone algorithm](web_workers_api/structured_clone_algorithm) can be stored. You need to specify the database schema, open a connection to your database, and then retrieve and update data within a series of **transactions**.

 * Read more about [IndexedDB key characteristics and basic terminology](indexeddb_api/basic_terminology).
* Learn to use IndexedDB asynchronously from first principles with our [Using IndexedDB](indexeddb_api/using_indexeddb) guide.
* Combine IndexedDB for storing data offline with Service Workers for storing assets offline, as outlined in [Making PWAs work offline with Service workers](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Tutorials/js13kGames/Offline_Service_workers).

  **Note:** Like most web storage solutions, IndexedDB follows a [same-origin policy](https://www.w3.org/Security/wiki/Same_Origin_Policy). So while you can access stored data within a domain, you cannot access data across different domains.

 

### Synchronous and asynchronous


Operations performed using IndexedDB are done asynchronously, so as not to block applications.


### Storage limits and eviction criteria


There are a number of web technologies that store data of one kind or another on the client side (i.e. on your local disk). IndexedDB is most commonly talked about. The process by which the browser works out how much space to allocate to web data storage and what to delete when that limit is reached is not simple, and differs between browsers. [Browser storage quotas and eviction criteria](storage_api/storage_quotas_and_eviction_criteria) attempts to explain how this works, at least in the case of Firefox.


Interfaces
----------


To get access to a database, call [`open()`](idbfactory/open) on the [`indexedDB`](indexeddb) attribute of a <window> object. This method returns an [`IDBRequest`](idbrequest) object; asynchronous operations communicate to the calling application by firing events on [`IDBRequest`](idbrequest) objects.


### Connecting to a database


 [`IDBFactory`](idbfactory)  Provides access to a database. This is the interface implemented by the global object [`indexedDB`](indexeddb) and is therefore the entry point for the API.

  [`IDBOpenDBRequest`](idbopendbrequest)  Represents a request to open a database.

  [`IDBDatabase`](idbdatabase)  Represents a connection to a database. It's the only way to get a transaction on the database.

  
### Retrieving and modifying data


 [`IDBTransaction`](idbtransaction)  Represents a transaction. You create a transaction on a database, specify the scope (such as which object stores you want to access), and determine the kind of access (read only or readwrite) that you want.

  [`IDBRequest`](idbrequest)  Generic interface that handles database requests and provides access to results.

  [`IDBObjectStore`](idbobjectstore)  Represents an object store that allows access to a set of data in an IndexedDB database, looked up via primary key.

  [`IDBIndex`](idbindex)  Also allows access to a subset of data in an IndexedDB database, but uses an index to retrieve the record(s) rather than the primary key. This is sometimes faster than using [`IDBObjectStore`](idbobjectstore).

  [`IDBCursor`](idbcursor)  Iterates over object stores and indexes.

  [`IDBCursorWithValue`](idbcursorwithvalue)  Iterates over object stores and indexes and returns the cursor's current value.

  [`IDBKeyRange`](idbkeyrange)  Defines a key range that can be used to retrieve data from a database in a certain range.

  
[`IDBLocaleAwareKeyRange`](idblocaleawarekeyrange)  Non-standard 
  Defines a key range that can be used to retrieve data from a database in a certain range, sorted according to the rules of the locale specified for a certain index (see the [`options`](idbobjectstore/createindex#options) parameter to [`IDBObjectStore.createIndex()`](idbobjectstore/createindex).) This interface isn't part of the 2.0 specification.

  
### Custom event interfaces



This specification fires events with the following custom interface:

  [`IDBVersionChangeEvent`](idbversionchangeevent)  The `IDBVersionChangeEvent` interface indicates that the version of the database has changed, as the result of an [`IDBOpenDBRequest.onupgradeneeded`](idbopendbrequest/upgradeneeded_event) event handler function.

  

Examples
--------


* [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([view example live](https://mdn.github.io/dom-examples/to-do-notifications/)): The reference application for the examples in the reference docs.

Specifications
--------------




| Specification |
| --- |
| [Indexed Database API 3.0](https://w3c.github.io/IndexedDB/)  |


See also
--------


* [localForage](https://localforage.github.io/localForage/): A Polyfill providing a simple name:value syntax for client-side data storage, which uses IndexedDB in the background, but falls back to Web SQL (deprecated) and then localStorage in browsers that don't support IndexedDB.
* [Dexie.js](https://dexie.org/): A wrapper for IndexedDB that allows much faster code development via nice, simple syntax.
* [JsStore](https://jsstore.net/): An IndexedDB wrapper with SQL like syntax.
* [MiniMongo](https://github.com/mWater/minimongo): A client-side in-memory mongodb backed by localstorage with server sync over http. MiniMongo is used by MeteorJS.
* [PouchDB](https://pouchdb.com): A client-side implementation of CouchDB in the browser using IndexedDB
* [idb](https://www.npmjs.com/package/idb): A tiny (~1.15k) library that mostly mirrors the IndexedDB API, but with small improvements that make a big difference to usability.
* [idb-keyval](https://www.npmjs.com/package/idb-keyval): A super-simple-small (~600B) promise-based keyval store implemented with IndexedDB
* [$mol\_db](https://github.com/hyoo-ru/mam_mol/tree/master/db): Tiny (~1.3kB) TypeScript facade with promise-based API and automatic migrations.
* [RxDB](https://rxdb.info/) A NoSQL client side database that can be used on top of IndexedDB. Supports indexes, compression and replication. Also adds cross tab functionality and observability to IndexedDB.


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API>

Ink API
=======



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The Ink API allows browsers to directly make use of available OS-level compositors when drawing pen stokes in an inking app feature, thereby reducing latency and increasing performance.



Concepts and usage
------------------



Inking on the web refers to app features that involve using [pointer events](pointer_events) to draw a smooth pen stroke — for example, a drawing app or document signing feature.

 Pointers events are usually sent first to the browser process, which then forwards these events to the JavaScript event loop to execute the associated handler functions and render the result in the app. The time delay between the start and finish of this process can be significant, resulting in latency between the user initiating drawing (for example, with a stylus or mouse), and the stroke showing up on the screen.

 The Ink API significantly reduces this latency by allowing browsers to bypass the JavaScript event loop entirely. Where possible, browsers will pass such rendering instructions directly to OS-level compositors. If the underlying operating system does not have a specialized OS-level compositor to use for this purpose, browsers will use their own optimized rendering code. This is not as powerful as a compositor, but it still confers some improvements.

  **Note:** Compositors are part of the rendering machinery that draws the UI to the screen in a browser or operating system. See [Inside look at modern web browser (part 3)](https://developer.chrome.com/blog/inside-browser-part3/) for some interesting insights into how a compositor functions inside a web browser.

  The entry point is the [`Navigator.ink`](navigator/ink) property, which returns an [`Ink`](ink) object for the current document. The [`Ink.requestPresenter()`](ink/requestpresenter) method returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that fulfills with an [`InkPresenter`](inkpresenter) object instance. This instructs the OS-level compositor to render ink strokes between pointer event dispatches in the next available frame in each case.



Interfaces
----------


 [`Ink`](ink)  Provides access to [`InkPresenter`](inkpresenter) objects for the application to use to render the strokes.

  [`InkPresenter`](inkpresenter)  Instructs the OS-level compositor to render ink strokes between pointer event dispatches.

  
### Extensions to other interfaces


 
[`Navigator.ink`](navigator/ink) Read only   Experimental 
  Returns an [`Ink`](ink) object for the current document.

  
Example
-------



In this example, we draw a trail onto a 2D canvas. Near the start of the code, we call [`Ink.requestPresenter()`](ink/requestpresenter), passing it the canvas as the presentation area for it to take care of and storing the promise it returns in the `presenter` variable.

 Later on, in the `pointermove` event listener, the new position of the trailhead is drawn onto the canvas each time the event fires. In addition, the [`InkPresenter`](inkpresenter) object returned when the `presenter` promise fulfills has its [`updateInkTrailStartPoint()`](inkpresenter/updateinktrailstartpoint) method invoked; this is passed:

 * The last trusted pointer event representing the rendering point for the current frame.
* A `style` object containing color and diameter settings.

 The result is that a delegated ink trail is drawn ahead of the default browser rendering on the app's behalf, in the specified style, until the next time it receives a `pointermove` event.

 
```
const ctx = canvas.getContext("2d");
let presenter = navigator.ink.requestPresenter({ presentationArea: canvas });
let move_cnt = 0;
let style = { color: "rgba(0, 0, 255, 1)", diameter: 10 };

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() \* (max - min + 1)) + min;
}

canvas.addEventListener("pointermove", (evt) => {
  const pointSize = 10;
  ctx.fillStyle = "#000000";
  ctx.fillRect(evt.pageX, evt.pageY, pointSize, pointSize);
  if (move_cnt == 50) {
    let r = getRandomInt(0, 255);
    let g = getRandomInt(0, 255);
    let b = getRandomInt(0, 255);
    style = { color: "rgba(" + r + ", " + g + ", " + b + ", 1)", diameter: 10 };
    move_cnt = 0;
    document.getElementById("div").style.backgroundColor =
      "rgba(" + r + ", " + g + ", " + b + ", 1)";
  }
  move_cnt += 1;
  presenter.then(function (v) {
    v.updateInkTrailStartPoint(evt, style);
  });
});

window.addEventListener("pointerdown", (evt) => {
  evt.pointerId;
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
});

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

```
  **Note:** See this example running live — [Delegated ink trail](https://mabian-ms.github.io/delegated-ink-trail.html).

 

Specifications
--------------




| Specification |
| --- |
| [Ink API # ink-interface](https://wicg.github.io/ink-enhancement/#ink-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Ink_API` | 94 | 93 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `requestPresenter` | 94 | 93 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |


See also
--------


* [Enhancing Inking on the Web](https://blogs.windows.com/msedgedev/2021/08/18/enhancing-inking-on-the-web/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Ink_API>

Keyboard API
============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The Keyboard API provides methods for working with a physical keyboard that is attached to a device running a browser.

 It provides several capabilities. *Keyboard mapping* provides an interface for retrieving the string generated by particular physical key on a keyboard to correctly identify that key to a user. *Keyboard locking* enables a web page to capture keys that are normally reserved by the user agent or the underlying operating system. The intended use of the Keyboard API is by web applications such as games or remote access apps that provide a fullscreen immersive experience.



Keyboard API concepts and usage
-------------------------------


### Keyboard mapping



On physical keyboards, the `code` attribute contains the physical location of the key that was pressed, and the `key` attribute contains the string generated by pressing the key at that physical location on the keyboard. The `key` value takes into account the keyboard's locale (for example, 'en-US'), layout (for example, 'QWERTY'), and modifier-key state (`Shift`, `Control`, etc.). Historically there has been no way to retrieve that information.

 The Keyboard Map API provides a way to retrieve the string generated by a particular key press, through the [`Keyboard`](keyboard) interface and the [`KeyboardLayoutMap`](keyboardlayoutmap) interface. The [`Keyboard`](keyboard) interface is accessed through [`navigator.keyboard`](navigator/keyboard). [`Keyboard`](keyboard) provides the [`Keyboard.getLayoutMap`](keyboard/getlayoutmap) method, which returns a promise that resolves with a [`KeyboardLayoutMap`](keyboardlayoutmap) object that contains members for converting codes to keys. A list of valid code values is found in the [Writing System Keys](https://w3c.github.io/uievents-code/#key-alphanumeric-writing-system) section of the [UI Events KeyboardEvent code Values](https://w3c.github.io/uievents-code/) spec.

 The following example demonstrates how to get the location-specific or layout-specific string associated with the key labeled `W` on an English QWERTY keyboard.

 
```
if (navigator.keyboard) {
  const keyboard = navigator.keyboard;
  keyboard.getLayoutMap().then((keyboardLayoutMap) => {
    const upKey = keyboardLayoutMap.get("KeyW");
    window.alert(`Press ${upKey} to move up.`);
  });
} else {
  // Do something else.
}

```


### Keyboard locking



Richly interactive web pages, games, and remote-streaming experiences often require access to special keys and keyboard shortcuts while in fullscreen mode. Examples of such key/key combinations include `Escape`, `Alt+Tab`, and `Ctrl+N`. Those keys and key combinations are typically captured by the user agent or the underlying operating system, as illustrated in the following example.

 To capture the `W`, `A`, `S`, and `D` keys, call `lock()` with a list that contains the key code attribute value for each of these keys:

 
```
navigator.keyboard.lock(["KeyW", "KeyA", "KeyS", "KeyD"]);

```
 This captures these keys regardless of which modifiers are used with the key press. Assuming a standard United States QWERTY layout, registering `KeyW` ensures that `W`, `Shift+W`, `Control+W`, `Control+Shift+W`, and all other key modifier combinations with `W` are sent to the app. The same applies to for `KeyA`, `KeyS`, and `KeyD`.



### Writing system keys



The codes passed [`Keyboard.lock`](keyboard/lock) and the various methods of the [`KeyboardLayoutMap`](keyboardlayoutmap) interface are called "writing system keys".

 "Writing system keys" are defined in the [Writing System Keys](https://w3c.github.io/uievents-code/#key-alphanumeric-writing-system) section of the [UI Events KeyboardEvent code Values](https://w3c.github.io/uievents-code/) spec, since the physical keys change meaning based on the current locale and keyboard layout. These keys are shown below. Blue keys are present on all standard keyboards while green keys are only available on some keyboards.

  ![Writing system keys as defined by the UI Events KeyboardEvent code Values spec.] 



Interfaces
----------


 
[`Keyboard`](keyboard)  Experimental 
  Provides functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard.

  
[`KeyboardLayoutMap`](keyboardlayoutmap)  Experimental 
  A map-like object with functions for retrieving the string associated with specific physical keys.

  
[`navigator.keyboard`](navigator/keyboard) Read only   Experimental 
  Returns a [`Keyboard`](keyboard) object which provides access to functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard.

  
Specifications
--------------




| Specification |
| --- |
| [Keyboard Map # keyboard-interface](https://wicg.github.io/keyboard-map/#keyboard-interface) |
| [Keyboard Lock # keyboard-interface](https://wicg.github.io/keyboard-lock/#keyboard-interface) |
| [Keyboard Map # keyboardlayoutmap-interface](https://wicg.github.io/keyboard-map/#keyboardlayoutmap-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@iterator` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `Keyboard_API` | 69 | 79 | No | No | 55 | No | 69 | 69 | No | 48 | No | 10.0 |
| `entries` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `forEach` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `get` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `has` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `keys` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `size` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `values` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Keyboard_API` | 68 | 79 | No | No | 55 | No | 68 | 68 | No | 48 | No | 10.0 |
| `getLayoutMap` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `lock` | 68 | 79 | No | No | 55 | No | 68 | 68 | No | 48 | No | 10.0 |
| `unlock` | 68 | 79 | No | No | 55 | No | 68 | 68 | No | 48 | No | 10.0 |


### api.Keyboard


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.KeyboardLayoutMap


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Keyboard_API>

Launch Handler API
==================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The **Launch Handler API** allows developers to control how a [progressive web app](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps) (PWA) is launched — for example if it uses an existing window or creates a new one, and how the app's target launch URL is handled.



Concepts and usage
------------------



You can specify launch behavior for your app by adding the [`launch_handler`](https://developer.mozilla.org/en-US/docs/Web/Manifest/launch_handler) field to your web app manifest file. This has one sub-field, `client_mode`, which contains a string value specifying how the app should be launched and navigated to. For example:

 
```
"launch\_handler": {
    "client\_mode": "focus-existing"
}

```
 If not specified, the default `client_mode` value is `auto`. Available values are:

  `focus-existing`  The most recently interacted with browsing context in a web app window is chosen to handle the launch. This will populate the target launch URL in the [`targetURL`](launchparams/targeturl) property of the [`LaunchParams`](launchparams) object passed into the [`window.launchQueue.setConsumer()`](launchqueue/setconsumer)'s callback function. As you'll see below, this allows you to set custom launch handing functionality for your app.

  `navigate-existing`  The most recently interacted with browsing context in a web app window is navigated to the target launch URL. The target URL is still made available via [`window.launchQueue.setConsumer()`](launchqueue/setconsumer) to allow additional custom launch navigation handling to be implemented.

  `navigate-new`  A new browsing context is created in a web app window to load the target launch URL. The target URL is still made available via [`window.launchQueue.setConsumer()`](launchqueue/setconsumer) to allow additional custom launch navigation handling to be implemented.

  `auto`  The user agent decides what works best for the platform. For example, `navigate-existing` might make more sense on mobile, where single app instances are commonplace, whereas `navigate-new` might make more sense in a desktop context. This is the default value used if provided values are invalid.

   When `focus-existing` is used, you can include code inside the [`window.launchQueue.setConsumer()`](launchqueue/setconsumer)'s callback function to provide custom handling of the [`targetURL`](launchparams/targeturl)

 
```
window.launchQueue.setConsumer((launchParams) => {
  // Do something with launchParams.targetURL
});

```
  **Note:** [`LaunchParams`](launchparams) also has a [`LaunchParams.files`](launchparams/files) property, which returns a read-only array of [`FileSystemHandle`](filesystemhandle) objects representing any files passed along with the launch navigation via the [`POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) method. This allows custom file handling to be implemented.

 

Interfaces
----------


 [`LaunchParams`](launchparams)  Used when implementing custom launch navigation handling in a PWA. When [`window.launchQueue.setConsumer()`](launchqueue/setconsumer) is invoked to set up the launch navigation handling functionality, the callback function inside `setConsumer()` is passed a `LaunchParams` object instance.

  [`LaunchQueue`](launchqueue)  When a [progressive web app](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps) (PWA) is launched with a [`launch_handler`](https://developer.mozilla.org/en-US/docs/Web/Manifest/launch_handler) `client_mode` value of `focus-existing`, `navigate-new`, or `navigate-existing`, `LaunchQueue` provides access to functionality that allows custom launch navigation handling to be implemented in the PWA. This functionality is controlled by the properties of the [`LaunchParams`](launchparams) object passed into the [`setConsumer()`](launchqueue/setconsumer) callback function.

  
Extensions to other interfaces
------------------------------


 [`window.launchQueue`](window/launchqueue)  Provides access to the [`LaunchQueue`](launchqueue) class, which allows custom launch navigation handling to be implemented in a [progressive web app](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps) (PWA), with the handling context signified by the [`launch_handler`](https://developer.mozilla.org/en-US/docs/Web/Manifest/launch_handler) manifest field `client_mode` value.

  
Examples
--------




```
if ("launchQueue" in window) {
  window.launchQueue.setConsumer((launchParams) => {
    if (launchParams.targetURL) {
      const params = new URL(launchParams.targetURL).searchParams;

      // Assuming a music player app that gets a track passed to it to be played
      const track = params.get("track");
      if (track) {
        audio.src = track;
        title.textContent = new URL(track).pathname.substr(1);
        audio.play();
      }
    }
  });
}

```
 This code is included in the PWA, and executed when the app loads, upon launch. The [`window.launchQueue.setConsumer()`](launchqueue/setconsumer)'s callback function extracts the search param out of the [`LaunchParams.targetURL`](launchparams/targeturl) and, if it finds a `track` param, uses it to populate an [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) element's `src` and play the audio track that this points to.

 See the [Musicr 2.0](https://launch-handler.glitch.me/) demo app for full working code.



Specifications
--------------




| Specification |
| --- |
| [Web App Launch Handler API # launchqueue-interface](https://wicg.github.io/web-app-launch/#launchqueue-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Launch_Handler_API` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |


See also
--------


* [Launch Handler API: Control how your app is launched](https://developer.chrome.com/docs/web-platform/launch-handler/)
* [Musicr 2.0](https://launch-handler.glitch.me/) demo app


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Launch_Handler_API>

Local Font Access API
=====================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The **Local Font Access API** provides a mechanism to access the user's locally installed font data — this includes higher-level details such as names, styles, and families, as well as the raw bytes of the underlying font files.



Concepts and usage
------------------



[Web fonts](https://developer.mozilla.org/en-US/docs/Learn/CSS/Styling_text/Web_fonts) were revolutionary in enabling typography on the web by allowing web designers to provide custom fonts to use on a web document. Specified via the [`@font-face`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face) at-rule, a web font can be loaded from a URL provided in the `url()` function.

 `@font-face` has several other useful features available. In particular, you can also specify the font's full or Postscript name inside the `local()` function to tell the browser to use a local copy if the user has the font installed on their computer. This is not without its problems — `local()` has become notorious as a [fingerprinting vector](https://developer.chrome.com/articles/local-fonts/#local-fonts-as-fingerprint-vector).

 In addition, high-end design tools have historically been difficult to deliver on the web, due to challenges in accurate font enumeration and accessing low-level font data (for example, to apply filters and transformations). Current apps often rely on workarounds such as asking users to upload their fonts to a server where they are processed to get raw byte data, or installing a separate local program to provide additional capabilities.

 The Local Font Access API has been created to address these problems.

 The [`Window.queryLocalFonts()`](window/querylocalfonts) method provides access to an array of locally-installed fonts, each represented by a [`FontData`](fontdata) object instance. [`FontData`](fontdata) has several properties providing access to names, styles, and families, and it also has a [`blob()`](fontdata/blob) method providing access to a [`Blob`](blob) containing the raw bytes of the underlying font file.

 In terms of privacy and security:

 * The Local Font Access API is designed to only provide access to the data required to solve the above problems. There is also no requirement for browsers to provide the full list of available local fonts, nor to provide the data in the same order as it appears on disk.
* When [`Window.queryLocalFonts()`](window/querylocalfonts) is invoked, the user is asked for permission to access their local fonts. The status of this permission can be queried via the [`Permissions API`](permissions_api) (the `local-fonts` permission).
* You can control access to this feature using a [`local-fonts`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy/local-fonts) [Permissions Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy).



Interfaces
----------


 [`FontData`](fontdata)  Represents a single local font face.

  
Extensions to other interfaces
------------------------------


 [`Window.queryLocalFonts()`](window/querylocalfonts)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that fulfills with an array of [`FontData`](fontdata) objects representing the font faces available locally.

  
Examples
--------


For a working live demo, see [Font Select Demo](https://local-font-access.glitch.me/demo/).


### Feature detection



```
if ("queryLocalFonts" in window) {
  // The Local Font Access API is supported
}

```

### Font enumeration



The following snippet will query for all available fonts, and log metadata. This could be used, for example, to populate a font-picker control.

 
```
async function logFontData() {
  try {
    const availableFonts = await window.queryLocalFonts();
    for (const fontData of availableFonts) {
      console.log(fontData.postscriptName);
      console.log(fontData.fullName);
      console.log(fontData.family);
      console.log(fontData.style);
    }
  } catch (err) {
    console.error(err.name, err.message);
  }
}

```


### Accessing low-level data



The [`blob()`](fontdata/blob) method provides access to low-level [SFNT](https://en.wikipedia.org/wiki/SFNT) data — this is a font file format that can contain other font formats, such as PostScript, TrueType, OpenType, or Web Open Font Format (WOFF).

 
```
async function computeOutlineFormat() {
  try {
    const availableFonts = await window.queryLocalFonts({
      postscriptNames: ["ComicSansMS"],
    });
    for (const fontData of availableFonts) {
      // `blob()` returns a Blob containing valid and complete
      // SFNT-wrapped font data.
      const sfnt = await fontData.blob();
      // Slice out only the bytes we need: the first 4 bytes are the SFNT
      // version info.
      // Spec: https://docs.microsoft.com/en-us/typography/opentype/spec/otff#organization-of-an-opentype-font
      const sfntVersion = await sfnt.slice(0, 4).text();

      let outlineFormat = "UNKNOWN";
      switch (sfntVersion) {
        case "\x00\x01\x00\x00":
        case "true":
        case "typ1":
          outlineFormat = "truetype";
          break;
        case "OTTO":
          outlineFormat = "cff";
          break;
      }
      console.log("Outline format:", outlineFormat);
    }
  } catch (err) {
    console.error(err.name, err.message);
  }
}

```


Specifications
--------------




| Specification |
| --- |
| [Local Font Access # dom-window-querylocalfonts](https://wicg.github.io/local-font-access/#dom-window-querylocalfonts) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Local_Font_Access_API` | 103 | 103 | No | No | No | No | No | No | No | No | No | No |


See also
--------


* [Use advanced typography with local fonts](https://developer.chrome.com/articles/local-fonts/)
* [`@font-face`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face)
* The [`local-fonts`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy/local-fonts) [Permissions Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy) directive


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Local_Font_Access_API>

Media Capabilities API
======================


The **Media Capabilities API** allows developers to determine decoding and encoding abilities of the device, exposing information such as whether media is supported and whether playback should be smooth and power efficient, with real time feedback about playback to better enable adaptive streaming, and access to display property information.


Examples
--------


### Detect audio file support and expected performance



This example defines an audio configuration then checks to see if the user agent supports decoding that media configuration, and whether it will perform well in terms of smoothness and power efficiency.

 
```
if ("mediaCapabilities" in navigator) {
  const audioFileConfiguration = {
    type: "file",
    audio: {
      contentType: "audio/mp3",
      channels: 2,
      bitrate: 132700,
      samplerate: 5200,
    },
  };

  navigator.mediaCapabilities
    .decodingInfo(audioFileConfiguration)
    .then((result) => {
      console.log(
        `This configuration is ${result.supported ? "" : "not "}supported,`
      );
      console.log(`${result.smooth ? "" : "not "}smooth, and`);
      console.log(`${result.powerEfficient ? "" : "not "}power efficient.`);
    })
    .catch(() => {
      console.log(`decodingInfo error: ${contentType}`);
    });
}

```


Media Capabilities API concepts and usage
-----------------------------------------



There are a myriad of video and audio codecs. Different browsers support different media types and new media types are always being developed. With the Media Capabilities API, developers can ensure each user is getting the best bitrate and storage savings for their browser, device, and OS capabilities.

 Whether a device uses hardware or software decoding impacts how smooth and power efficient the video decoding is and how efficient the playback will be. The Media Capabilities API enables determining which codecs are supported and how performant a media file will be both in terms of smoothness and power efficiency.

 The Media Capabilities API provide more powerful features than say [`MediaRecorder.isTypeSupported()`](mediarecorder/istypesupported) or [`HTMLMediaElement.canPlayType()`](htmlmediaelement/canplaytype), which only address general browser support, not performance. The API also provides abilities to access display property information such as supported color [gamut](https://developer.mozilla.org/en-US/docs/Glossary/Gamut), dynamic range abilities, and real-time feedback about the playback.

 To test support, smoothness, and power efficiency of a video or audio file, you use the [`MediaCapabilities`](mediacapabilities) interface's [`encodingInfo()`](mediacapabilities/encodinginfo) and [`decodingInfo()`](mediacapabilities/decodinginfo) methods.

 Media capabilities information enables websites to enable adaptive streaming to alter the quality of content based on actual user-perceived quality, and react to a pick of CPU/GPU usage in real time.



Media Capabilities Interfaces
-----------------------------


 [`MediaCapabilities`](mediacapabilities)  Provides information about the decoding abilities of the device, system and browser based on codecs, profile, resolution, and bitrates. The information can be used to serve optimal media streams to the user and determine if playback should be smooth and power efficient .

  ScreenColorGamut  Will describe the color [gamut](https://developer.mozilla.org/en-US/docs/Glossary/Gamut), or the range of color, the screen can display (not currently supported anywhere).

  ScreenLuminance  Will describe the known luminance characteristics of the screen (not currently supported anywhere).

  
Specifications
--------------




| Specification |
| --- |
| [Media Capabilities # media-capabilities-interface](https://w3c.github.io/media-capabilities/#media-capabilities-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Media_Capabilities_API` | 66 | 79 | 63 | No | 53 | 13 | 66 | 66 | 63 | 48 | 13 | 9.0 |
| `decodingInfo` | 66["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 79["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 63["The `webrtc` value of the `type` option is named `transmission`.", "Before Firefox 101, `decodingInfo()` ignored `codecs` parameter options for `av01` codecs (treating them as `av1`)."] | No | 53["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 13 | 66["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 66["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 63["The `webrtc` value of the `type` option is named `transmission`.", "Before Firefox 101, `decodingInfo()` ignored `codecs` parameter options for `av01` codecs (treating them as `av1`)."] | 48["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 13 | 9.0["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] |
| `encodingInfo` | 101 | 101 | 63The `webrtc` value of the `type` option is named `transmission`. | No | 87 | 15.4 | 101 | 101 | 63The `webrtc` value of the `type` option is named `transmission`. | 70 | 15.4 | 19.0 |


See also
--------


* [HTMLMediaElement](htmlmediaelement)'s method [canPlayType()](htmlmediaelement/canplaytype)
* [MediaSource](mediasource)'s method [isTypeSupported()](mediasource/istypesupported)
* [`Navigator`](navigator) interface
* [Using the Media Capabilities API](media_capabilities_api/using_the_media_capabilities_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Media_Capabilities_API>

Media Capture and Streams API (Media Stream)
============================================



The **Media Capture and Streams** API, often called the **Media Streams API** or **MediaStream API**, is an API related to [WebRTC](webrtc_api) which provides support for streaming audio and video data.

 It provides the interfaces and methods for working with the streams and their constituent tracks, the constraints associated with data formats, the success and error callbacks when using the data asynchronously, and the events that are fired during the process.



Concepts and usage
------------------



The API is based on the manipulation of a [`MediaStream`](mediastream) object representing a flux of audio- or video-related data. See an example in [Get the media stream](media_capture_and_streams_api/taking_still_photos#the_startup_function).

 A `MediaStream` consists of zero or more [`MediaStreamTrack`](mediastreamtrack) objects, representing various audio or video **tracks**. Each `MediaStreamTrack` may have one or more **channels**. The channel represents the smallest unit of a media stream, such as an audio signal associated with a given speaker, like *left* or *right* in a stereo audio track.

 `MediaStream` objects have a single **input** and a single **output**. A `MediaStream` object generated by [`getUserMedia()`](mediadevices/getusermedia) is called *local*, and has as its source input one of the user's cameras or microphones. A non-local `MediaStream` may be representing a media element, like [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) or [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio), a stream originating over the network, and obtained via the WebRTC [`RTCPeerConnection`](rtcpeerconnection) API, or a stream created using the [Web Audio API](web_audio_api) [`MediaStreamAudioDestinationNode`](mediastreamaudiodestinationnode).

 The output of the `MediaStream` object is linked to a **consumer**. It can be a media element, like [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) or [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video), the WebRTC [`RTCPeerConnection`](rtcpeerconnection) API or a [Web Audio API](web_audio_api) [`MediaStreamAudioSourceNode`](mediastreamaudiosourcenode).



Interfaces
----------



In these reference articles, you'll find the fundamental information you'll need to know about each of the interfaces that make up the Media Capture and Streams API.

 * [`CanvasCaptureMediaStreamTrack`](canvascapturemediastreamtrack)
* [`InputDeviceInfo`](inputdeviceinfo)
* [`MediaDeviceInfo`](mediadeviceinfo)
* [`MediaDevices`](mediadevices)
* [`MediaStream`](mediastream)
* [`MediaStreamEvent`](mediastreamevent)
* [`MediaStreamTrack`](mediastreamtrack)
* [`MediaStreamTrackEvent`](mediastreamtrackevent)
* [`MediaTrackConstraints`](mediatrackconstraints)
* [`MediaTrackSettings`](mediatracksettings)
* [`MediaTrackSupportedConstraints`](mediatracksupportedconstraints)
* [`OverconstrainedError`](overconstrainederror)
* [`URL`](url)



Events
------


* [`addtrack`](mediastream/addtrack_event)
* [`ended`](mediastreamtrack/ended_event)
* [`mute`](mediastreamtrack/mute_event)
* [`overconstrained`](mediastreamtrack/overconstrained_event)
* [`removetrack`](mediastream/removetrack_event)
* [`unmute`](mediastreamtrack/unmute_event)

Guides and tutorials
--------------------



The [Capabilities, constraints, and settings](media_capture_and_streams_api/constraints) article discusses the concepts of **constraints** and **capabilities**, as well as media settings, and includes a [Constraint Exerciser](media_capture_and_streams_api/constraints#example_constraint_exerciser) that lets you experiment with the results of different constraint sets being applied to the audio and video tracks coming from the computer's A/V input devices (such as its webcam and microphone).

 The [Taking still photos with getUserMedia()](media_capture_and_streams_api/taking_still_photos) article shows how to use [`getUserMedia()`](mediadevices/getusermedia) to access the camera on a computer or mobile phone with `getUserMedia()` support and take a photo with it.



Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaStream` | 5521 | 7912 | 44 | No | 4215 | 11 | 554.4 | 5525 | 42 | 4214 | 11 | 6.01.5 |
| `Media_Capture_and_Streams_API` | 5521 | 7912 | 15 | No | 4215 | 11 | 554.4 | 5525 | 15 | 4214 | 11 | 6.01.5 |
| `active` | 42 | 12 | 52 | No | 29 | 11 | 42 | 42 | 52 | 29 | 11 | 4.0 |
| `active_event` | 42 | 12 | No | No | 29 | No | 42 | 42 | No | 29 | No | 4.0 |
| `addTrack` | 26 | 12 | 44 | No | No | 11 | 37 | 26 | No | No | 11 | 1.5 |
| `addtrack_event` | 26 | 12 | 50 | No | No | 11 | 4.4 | 26 | 50 | No | 11 | 1.5 |
| `clone` | 35 | 12 | 48 | No | 22 | 11 | 37 | 35 | 48 | 22 | 11 | 3.0 |
| `getAudioTracks` | 26 | 12 | 22Before Firefox 64, this method returned an array of `AudioStreamTrack` objects. However, `MediaStreamTrack` has now subsumed that interface's functionality. | No | 15 | 11 | 37 | 26 | 22Before Firefox 64, this method returned an array of `AudioStreamTrack` objects. However, `MediaStreamTrack` has now subsumed that interface's functionality. | No | 11 | 1.5 |
| `getTrackById` | 26 | 12 | 49 | No | No | 11 | 37 | 26 | 49 | No | 11 | 1.5 |
| `getTracks` | 38 | 12 | 34 | No | 25 | 11 | 38 | 38 | 34 | 25 | 11 | 3.0 |
| `getVideoTracks` | 26 | 12 | 22Before Firefox 64, this method returned an array of `VideoStreamTrack` objects. However, `MediaStreamTrack` has now subsumed that interface's functionality. | No | 15 | 11 | 37 | 26 | 22Before Firefox 64, this method returned an array of `VideoStreamTrack` objects. However, `MediaStreamTrack` has now subsumed that interface's functionality. | No | 11 | 1.5 |
| `id` | 26 | 12 | 41 | No | 15 | 11 | 4.4 | 26 | 41 | 14 | 11 | 1.5 |
| `inactive_event` | 42 | 12 | No | No | 29 | No | 42 | 42 | No | 29 | No | 4.0 |
| `removeTrack` | 26 | 12 | 44 | No | 15 | 11 | 37 | 26 | 44 | No | 11 | 1.5 |
| `removetrack_event` | 26 | 12 | 7259–72Before Firefox 72, the event handler was exposed but had no effect. | No | No | 11 | 4.4 | 26 | 7959–79Before Firefox 72, the event handler was exposed but had no effect. | No | 11 | 1.5 |


See also
--------


* [WebRTC](webrtc_api) - the introductory page to the API
* [`mediaDevices.getUserMedia()`](mediadevices/getusermedia)
* [Taking still photos with WebRTC](media_capture_and_streams_api/taking_still_photos): a demonstration and tutorial about using `getUserMedia()`.


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Media_Capture_and_Streams_API>

Media Session API
=================



The Media Session API provides a way to customize media notifications. It does this by providing metadata for display by the user agent for the media your web app is playing.

 It also provides action handlers that the browser can use to access platform media keys such as hardware keys found on keyboards, headsets, remote controls, and software keys found in notification areas and on lock screens of mobile devices. So you can seamlessly control web-provided media via your device, even when not looking at the web page.

 The aim is to allow users to know what's playing and to control it, without needing to open the specific page that launched it. To be able to support the Media Session API, a browser first needs a mechanism by which to access and be controlled by the OS-level media controls (such as Firefox's [MediaControl](https://bugzil.la/1648100)).



Media Session concepts and usage
--------------------------------



The [`MediaMetadata`](mediametadata) interface lets a web site provide rich metadata to the platform UI for media that is playing. This metadata includes the title, artist (creator) name, album (collection), and artwork. The platform can show this metadata in media centers, notifications, device lockscreens, etc.

 The [`MediaSession`](mediasession) interface lets users control playback of media through user-agent defined interface elements. Interaction with these elements triggers action handlers in the web page, playing the media. Since multiple pages may be simultaneously using this API, the user agent is responsible for calling the correct page's action handlers. The user agent provides default behaviors, when no page-defined behavior is available.



Accessing the Media Session API
-------------------------------



The primary interface for the Media Session API is the [`MediaSession`](mediasession) interface. Rather than creating your own `MediaSession` instance, you access the API using the [`navigator.mediaSession`](navigator/mediasession) property. For example, to set the current state of the media session to `playing`:

 
```
navigator.mediaSession.playbackState = "playing";

```


Interfaces
----------


 [`MediaMetadata`](mediametadata)  Allows a web page to provide rich media metadata for display in a platform UI.

  [`MediaSession`](mediasession)  Allows a web page to provide custom behaviors for standard media playback interactions.

  
Dictionaries
------------


 [`MediaImage`](mediaimage)  A `MediaImage` object contains information describing an image associated with the media. This might be a CD or DVD cover, a movie poster, a poster frame, or the like.

  
Examples
--------


### Setting up action handlers for a music player



The following example shows feature detection for the Media Session API. It then instantiates a metadata object for the session, and adds action handlers for the user control actions:

 
```
if ("mediaSession" in navigator) {
  navigator.mediaSession.metadata = new MediaMetadata({
    title: "Unforgettable",
    artist: "Nat King Cole",
    album: "The Ultimate Collection (Remastered)",
    artwork: [
      {
        src: "https://dummyimage.com/96x96",
        sizes: "96x96",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/128x128",
        sizes: "128x128",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/192x192",
        sizes: "192x192",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/256x256",
        sizes: "256x256",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/384x384",
        sizes: "384x384",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/512x512",
        sizes: "512x512",
        type: "image/png",
      },
    ],
  });

  navigator.mediaSession.setActionHandler("play", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("pause", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("stop", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("seekbackward", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("seekforward", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("seekto", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("previoustrack", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("nexttrack", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("skipad", () => {
    /\* Code excerpted. \*/
  });
}

```
 Some user agents disable autoplay for media elements on mobile devices and require a user gesture to start media. The following example adds a `pointerup` event to an on-page play button, which is then used to kick off the media session code:

 
```
playButton.addEventListener("pointerup", (event) => {
  const audio = document.querySelector("audio");

  // User interacted with the page. Let's play audio!
  audio
    .play()
    .then(() => {
      /\* Set up media session controls, as shown above. \*/
    })
    .catch((error) => {
      console.error(error);
    });
});

```


### Using action handlers to control a slide presentation



The `"previousslide"` and `"nextslide"` action handlers can be used to handle moving forward and backward through a slide presentation, for example when the user puts their presentation into a [Picture-in-Picture](picture-in-picture_api) window, and presses the browser-supplied controls for navigating through slides.

 
```
try {
  navigator.mediaSession.setActionHandler("previousslide", () => {
    log('> User clicked "Previous Slide" icon.');
    if (slideNumber > 1) slideNumber--;
    updateSlide();
  });
} catch (error) {
  log('Warning! The "previousslide" media session action is not supported.');
}

try {
  navigator.mediaSession.setActionHandler("nextslide", () => {
    log('> User clicked "Next Slide" icon.');
    slideNumber++;
    updateSlide();
  });
} catch (error) {
  log('Warning! The "nextslide" media session action is not supported.');
}

```
 See [Presenting Slides / Media Session Sample](https://googlechrome.github.io/samples/media-session/slides.html) for a working example.



Specifications
--------------




| Specification |
| --- |
| [Media Session Standard # the-mediasession-interface](https://w3c.github.io/mediasession/#the-mediasession-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Media_Session_API` | 73 | 79 | 82 | No | 60 | 15 | No | 57 | 82Firefox exposes the API, but does not provide a corresponding user-facing media control interface. | 43 | 15 | 7.0 |
| `metadata` | 73 | 79 | 82 | No | 60 | 15 | No | 57 | 82Firefox exposes the API, but does not provide a corresponding user-facing media control interface. | 43 | 15 | 7.0 |
| `playbackState` | 73 | 79 | 82 | No | 60 | 15 | No | 57 | 82Firefox exposes the API, but does not provide a corresponding user-facing media control interface. | 43 | 15 | 7.0 |
| `setActionHandler` | 73 | 79 | 82Firefox does not support the `togglemicrophone`, `togglecamera`, and `hangup` action types. | No | 60 | 15Safari does not support for the `togglemicrophone`, `togglecamera`, and `hangup` action types. | No | 57 | 82Firefox exposes the API, but does not provide a corresponding user-facing media control interface. | 43 | 15Safari does not support for the `togglemicrophone`, `togglecamera`, and `hangup` action types. | 7.0 |
| `setCameraActive` | 93 | 93 | No | No | 79 | No | No | 93 | No | 66 | No | 17.0 |
| `setMicrophoneActive` | 93 | 93 | No | No | 79 | No | No | 93 | No | 66 | No | 17.0 |
| `setPositionState` | 81 | 81 | 82 | No | 68 | 15 | No | 57 | 82Firefox exposes the API, but does not provide a corresponding user-facing media control interface. | 43 | 15 | 7.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Media_Session_API>

Media Source API
================


The **Media Source API**, formally known as **Media Source Extensions** (**MSE**), provides functionality enabling plugin-free web-based streaming media. Using MSE, media streams can be created via JavaScript, and played using [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) and [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) elements.


Media Source Extensions concepts and usage
------------------------------------------


Playing video and audio has been available in web applications without plugins for a few years now, but the basic features offered have really only been useful for playing single whole tracks. We can't, for example, combine/split arraybuffers. Streaming media has up until recently been the domain of Flash, with technologies like Flash Media Server serving video streams using the RTMP protocol.


### The MSE standard



With Media Source Extensions (MSE), this is changing. MSE allows us to replace the usual single progressive `src` URI fed to media elements with a reference to a `MediaSource` object, which is a container for information like the ready state of the media for being played, and references to multiple `SourceBuffer` objects that represent the different chunks of media that make up the entire stream. MSE gives us finer-grained control over how much and how often content is fetched, and some control over memory usage details, such as when buffers are evicted. It lays the groundwork for adaptive bitrate streaming clients (such as those using DASH or HLS) to be built on its extensible API.

 Creating assets that work with MSE in modern browsers is a laborious process, taking significant time, computing power, and energy. The usage of external utilities to massage the content into a suitable format is required. While browser support for the various media containers with MSE is spotty, usage of the H.264 video codec, AAC audio codec, and MP4 container format is a common baseline. MSE also provides an API for runtime detection of container and codec support.

 If you do not require explicit control of video quality over time, the rate at which content is fetched, or the rate at which memory is evicted, then the [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) and [`<source>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/source) tags may well be a simple and adequate solution.



### DASH



Dynamic Adaptive Streaming over HTTP (DASH) is a protocol for specifying how adaptive content should be fetched. It is effectively a layer built on top of MSE for building adaptive bitrate streaming clients. While there are other protocols available (such as HTTP Live Streaming (HLS)), DASH has the most platform support.

 DASH moves lots of logic out of the network protocol and into the client side application logic, using the simpler HTTP protocol to fetch files. Indeed, one can support DASH with a simple static file server, which is also great for CDNs. This is in direct contrast with previous streaming solutions that required expensive licenses for proprietary non-standard client/server protocol implementations.

 The two most common use cases for DASH involve watching content "on demand" or "live." On demand allows a developer to take their time transcoding the assets into multiple resolutions of various quality.

 Live profile content can introduce latency due to its transcoding and broadcasting, so DASH is not suitable for real time communication like [WebRTC](webrtc_api) is. It can however support significantly more client connections than WebRTC.

 There are numerous available free and open source tools for transcoding content and preparing it for use with DASH, DASH file servers, and DASH client libraries written in JavaScript.



### Availability in workers



Starting with Chrome 108, MSE features are available in dedicated [web workers](web_workers_api), which allows for improved performance when manipulating [`MediaSource`](mediasource)s and [`SourceBuffer`](sourcebuffer)s. To play back the media, the [`MediaSource.handle`](mediasource/handle) property is used to get a reference to a [`MediaSourceHandle`](mediasourcehandle) object, a proxy for the `MediaSource` that can be transferred back to the main thread and attached to a media element via its [`HTMLMediaElement.srcObject`](htmlmediaelement/srcobject) property.

 See [MSE-in-Workers Demo by Matt Wolenetz](https://wolenetz.github.io/mse-in-workers-demo/mse-in-workers-demo.html) for a live example.



Interfaces
----------


 [`MediaSource`](mediasource)  Represents a media source to be played via an [`HTMLMediaElement`](htmlmediaelement) object.

  [`SourceBuffer`](sourcebuffer)  Represents a chunk of media to be passed into an [`HTMLMediaElement`](htmlmediaelement) via a `MediaSource` object.

  [`SourceBufferList`](sourcebufferlist)  A simple container list for multiple `SourceBuffer` objects.

  [`VideoPlaybackQuality`](videoplaybackquality)  Contains information about the quality of video being played by a [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) element, such as number of dropped or corrupted frames. Returned by the [`HTMLVideoElement.getVideoPlaybackQuality()`](htmlvideoelement/getvideoplaybackquality) method.

  
Extensions to other interfaces
------------------------------


 [`URL.createObjectURL()`](url/createobjecturl)  Creates an object URL pointing to a `MediaSource` object that can then be specified as the `src` value of an HTML media element to play a media stream.

  [`HTMLMediaElement.seekable`](htmlmediaelement/seekable)  When a `MediaSource` object is played by an HTML media element, this property will return a [`TimeRanges`](timeranges) object that contains the time ranges that the user is able to seek to.

  [`HTMLVideoElement.getVideoPlaybackQuality()`](htmlvideoelement/getvideoplaybackquality)  Returns a [`VideoPlaybackQuality`](videoplaybackquality) object for the currently played video.

  
[`AudioTrack.sourceBuffer`](audiotrack/sourcebuffer), [`VideoTrack.sourceBuffer`](videotrack/sourcebuffer), `TextTrack.sourceBuffer`
  Returns the [`SourceBuffer`](sourcebuffer) that created the track in question.

  
Specifications
--------------




| Specification |
| --- |
| [Media Source Extensions™](https://w3c.github.io/media-source/)  |


See also
--------


* [Transcoding assets for Media Source Extensions](media_source_extensions_api/transcoding_assets_for_mse)
* Using MSE to create a basic streaming service (TBD)
* Using MPEG DASH to create a streaming application (TBD)
* The [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) and [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) elements.
* [`HTMLMediaElement`](htmlmediaelement), [`HTMLVideoElement`](htmlvideoelement), [`HTMLAudioElement`](htmlaudioelement).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Media_Source_Extensions_API>

MediaStream Recording API
=========================


The **MediaStream Recording API**, sometimes referred to as the *Media Recording API* or the *MediaRecorder API*, is closely affiliated with the [Media Capture and Streams API](media_capture_and_streams_api) and the [WebRTC API](webrtc_api). The MediaStream Recording API makes it possible to capture the data generated by a [`MediaStream`](mediastream) or [`HTMLMediaElement`](htmlmediaelement) object for analysis, processing, or saving to disk. It's also surprisingly easy to work with.


Basic concepts
--------------


The MediaStream Recording API is comprised of a single major interface, [`MediaRecorder`](mediarecorder), which does all the work of taking the data from a [`MediaStream`](mediastream) and delivering it to you for processing. The data is delivered by a series of [`dataavailable`](mediarecorder/dataavailable_event) events, already in the format you specify when creating the `MediaRecorder`. You can then process the data further or write it to file as desired.


### Overview of the recording process



The process of recording a stream is simple:

 1. Set up a [`MediaStream`](mediastream) or [`HTMLMediaElement`](htmlmediaelement) (in the form of an [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) or [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) element) to serve as the source of the media data.
2. Create a [`MediaRecorder`](mediarecorder) object, specifying the source stream and any desired options (such as the container's MIME type or the desired bit rates of its tracks).
3. Set [`ondataavailable`](mediarecorder/dataavailable_event) to an event handler for the [`dataavailable`](mediarecorder/dataavailable_event) event; this will be called whenever data is available for you.
4. Once the source media is playing and you've reached the point where you're ready to record video, call [`MediaRecorder.start()`](mediarecorder/start) to begin recording.
5. Your [`dataavailable`](mediarecorder/dataavailable_event) event handler gets called every time there's data ready for you to do with as you will; the event has a `data` attribute whose value is a [`Blob`](blob) that contains the media data. You can force a `dataavailable` event to occur, thereby delivering the latest sound to you so you can filter it, save it, or whatever.
6. Recording stops automatically when the source media stops playing.
7. You can stop recording at any time by calling [`MediaRecorder.stop()`](mediarecorder/stop).

  **Note:** Individual [`Blob`](blob)s containing slices of the recorded media will not necessarily be individually playable. The media needs to be reassembled before playback.

  If anything goes wrong during recording, an [`error`](mediarecorder/error_event) event is sent to the `MediaRecorder`. You can listen for `error` events by setting up a [`onerror`](mediarecorder/error_event) event handler.

 Example here, we use an HTML Canvas as source of the [`MediaStream`](mediastream), and stop recording after 9 seconds.

 
```
const canvas = document.querySelector("canvas");

// Optional frames per second argument.
const stream = canvas.captureStream(25);
const recordedChunks = [];

console.log(stream);
const options = { mimeType: "video/webm; codecs=vp9" };
const mediaRecorder = new MediaRecorder(stream, options);

mediaRecorder.ondataavailable = handleDataAvailable;
mediaRecorder.start();

function handleDataAvailable(event) {
  console.log("data-available");
  if (event.data.size > 0) {
    recordedChunks.push(event.data);
    console.log(recordedChunks);
    download();
  } else {
    // …
  }
}
function download() {
  const blob = new Blob(recordedChunks, {
    type: "video/webm",
  });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  document.body.appendChild(a);
  a.style = "display: none";
  a.href = url;
  a.download = "test.webm";
  a.click();
  window.URL.revokeObjectURL(url);
}

// demo: to download after 9sec
setTimeout((event) => {
  console.log("stopping");
  mediaRecorder.stop();
}, 9000);

```


### Examining and controlling the recorder status



You can also use the properties of the `MediaRecorder` object to determine the state of the recording process, and its [`pause()`](mediarecorder/pause) and [`resume()`](mediarecorder/resume) methods to pause and resume recording of the source media.

 If you need or want to check to see if a specific MIME type is supported, that's possible as well. Just call [`MediaRecorder.isTypeSupported()`](mediarecorder/istypesupported).



### Examining potential input sources



If your goal is to record camera and/or microphone input, you may wish to examine the available input devices before beginning the process of constructing the `MediaRecorder`. To do so, you'll need to call [`navigator.mediaDevices.enumerateDevices()`](mediadevices/enumeratedevices) to get a list of the available media devices. You can then examine that list and identify the potential input sources, and even filter the list based on desired criteria.

 In this code snippet, `enumerateDevices()` is used to examine the available input devices, locate those which are audio input devices, and create [`<option>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option) elements that are then added to a [`<select>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select) element representing an input source picker.

 
```
navigator.mediaDevices.enumerateDevices().then((devices) => {
  devices.forEach((device) => {
    const menu = document.getElementById("inputdevices");
    if (device.kind === "audioinput") {
      const item = document.createElement("option");
      item.textContent = device.label;
      item.value = device.deviceId;
      menu.appendChild(item);
    }
  });
});

```
 Code similar to this can be used to let the user restrict the set of devices they wish to use.



### For more information


To learn more about using the MediaStream Recording API, see [Using the MediaStream Recording API](mediastream_recording_api/using_the_mediastream_recording_api), which shows how to use the API to record audio clips. A second article, [Recording a media element](mediastream_recording_api/recording_a_media_element), describes how to receive a stream from an [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) or [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) element and use the captured stream (in this case, recording it and saving it to a local disk).


Reference
---------


 [`BlobEvent`](blobevent)  Each time a chunk of media data is finished being recorded, it's delivered to consumers in [`Blob`](blob) form using a [`BlobEvent`](blobevent) of type `dataavailable`.

  [`MediaRecorder`](mediarecorder)  The primary interface that implements the MediaStream Recording API.

  [`MediaRecorderErrorEvent`](mediarecordererrorevent)  The interface that represents errors thrown by the MediaStream Recording API. Its [`error`](mediarecordererrorevent/error) property is a [`DOMException`](domexception) that specifies that error occurred.

  
Specifications
--------------




| Specification |
| --- |
| [MediaStream Recording # mediarecorder-api](https://w3c.github.io/mediacapture-record/#mediarecorder-api) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaRecorder` | 47 | 79 | 25 | No | 36 | 14 | 47 | 47 | 25 | 36 | 14 | 5.0 |
| `MediaStream_Recording_API` | 47 | 79 | 25Before Firefox 58, using `MediaStream.addTrack()` on a stream obtained using `getUserMedia()`, then attempting to record the resulting stream would result in only recording the original stream without the added tracks (severe bug). | No | 36 | 14 | 47 | 47 | 25Before Firefox 58, using `MediaStream.addTrack()` on a stream obtained using `getUserMedia()`, then attempting to record the resulting stream would result in only recording the original stream without the added tracks (severe bug). | 36 | 14 | 5.0 |
| `audioBitrateMode` | 89 | 89 | No | No | 75 | No | 89 | 89 | No | 63 | No | 15.0 |
| `audioBitsPerSecond` | 49 | 79 | 71 | No | 36 | 14.1 | 49 | 49 | 79 | 36 | 14.5 | 5.0 |
| `dataavailable_event` | 49 | 79 | 25 | No | 36 | 14 | 49 | 49 | 25 | 36 | 14 | 5.0 |
| `error_event` | 49The interface for this event is a plain [`Event`](https://developer.mozilla.org/docs/Web/API/Event), not [`MediaRecorderErrorEvent`](https://developer.mozilla.org/docs/Web/API/MediaRecorderErrorEvent). See [bug 1250432](https://crbug.com/1250432). | 79The interface for this event is a plain [`Event`](https://developer.mozilla.org/docs/Web/API/Event), not [`MediaRecorderErrorEvent`](https://developer.mozilla.org/docs/Web/API/MediaRecorderErrorEvent). See [bug 1250432](https://crbug.com/1250432). | 25 | No | 36The interface for this event is a plain [`Event`](https://developer.mozilla.org/docs/Web/API/Event), not [`MediaRecorderErrorEvent`](https://developer.mozilla.org/docs/Web/API/MediaRecorderErrorEvent). See [bug 1250432](https://crbug.com/1250432). | 14 | 49The interface for this event is a plain [`Event`](https://developer.mozilla.org/docs/Web/API/Event), not [`MediaRecorderErrorEvent`](https://developer.mozilla.org/docs/Web/API/MediaRecorderErrorEvent). See [bug 1250432](https://crbug.com/1250432). | 49The interface for this event is a plain [`Event`](https://developer.mozilla.org/docs/Web/API/Event), not [`MediaRecorderErrorEvent`](https://developer.mozilla.org/docs/Web/API/MediaRecorderErrorEvent). See [bug 1250432](https://crbug.com/1250432). | 25 | 36The interface for this event is a plain [`Event`](https://developer.mozilla.org/docs/Web/API/Event), not [`MediaRecorderErrorEvent`](https://developer.mozilla.org/docs/Web/API/MediaRecorderErrorEvent). See [bug 1250432](https://crbug.com/1250432). | 14 | 5.0The interface for this event is a plain [`Event`](https://developer.mozilla.org/docs/Web/API/Event), not [`MediaRecorderErrorEvent`](https://developer.mozilla.org/docs/Web/API/MediaRecorderErrorEvent). See [bug 1250432](https://crbug.com/1250432). |
| `isTypeSupported` | 47 | 79 | 25 | No | 36 | 14 | 47 | 47 | 25 | 36 | 14 | 5.0 |
| `mimeType` | 4947–49Before Chrome 49, only video is supported, not audio. | 79 | 25Starting with Firefox 71, the behavior of `mimeType` is more consistent. For example, it now returns the media type even after recording has stopped. | No | 36 | 14 | 4947–49Before Chrome 49, only video is supported, not audio. | 4947–49Before Chrome 49, only video is supported, not audio. | 25 | 36 | 14 | 5.0 |
| `pause` | 49 | 79 | 25 | No | 36 | 14.1 | 49 | 49 | 25 | 36 | 14.5 | 5.0 |
| `pause_event` | 49 | 79 | 65 | No | 36 | 14.1 | 49 | 49 | 65 | 36 | 14.5 | 5.0 |
| `requestData` | 49 | 79 | 25 | No | 36 | 14 | 49 | 49 | 25 | 36 | 14 | 5.0 |
| `resume` | 49 | 79 | 25 | No | 36 | 14.1 | 49 | 49 | 25 | 36 | 14.5 | 5.0 |
| `resume_event` | 49 | 79 | 65 | No | 36 | 14.1 | 49 | 49 | 65 | 36 | 14.5 | 5.0 |
| `start` | 47 | 79 | 25 | No | 36 | 14 | 47 | 47 | 25 | 36 | 14 | 5.0 |
| `start_event` | 49 | 79 | 25 | No | 36 | 14 | 49 | 49 | 25 | 36 | 14 | 5.0 |
| `state` | 4947–49Before Chrome 49, only video is supported, not audio. | 79 | 25 | No | 36 | 14 | 4947–49Before Chrome 49, only video is supported, not audio. | 4947–49Before Chrome 49, only video is supported, not audio. | 25 | 36 | 14 | 5.0 |
| `stop` | 49 | 79 | 25 | No | 36 | 14 | 49 | 49 | 25 | 36 | 14 | 5.0 |
| `stop_event` | 49 | 79 | 25 | No | 36 | 14 | 49 | 49 | 25 | 36 | 14 | 5.0 |
| `stream` | 4947–49Before Chrome 49, only video is supported, not audio. | 79 | 25 | No | 36 | 14 | 49 | 4947–49Before Chrome 49, only video is supported, not audio. | 25 | 36 | 14 | 5.0 |
| `videoBitsPerSecond` | 49 | 79 | 71 | No | 36 | 14.1 | 49 | 49 | 79 | 36 | 14.5 | 5.0 |
| `warning_event` | 49 | 79 | 25–71 | No | 36 | No | 49 | 49 | 25 | 36 | No | 5.0 |


See also
--------


* [Using the MediaStream Recording API](mediastream_recording_api/using_the_mediastream_recording_api)
* [Recording a media element](mediastream_recording_api/recording_a_media_element)
* [simpl.info MediaStream Recording demo](https://simpl.info/mediarecorder/), by [Sam Dutton](https://twitter.com/sw12)
* [`MediaDevices.getUserMedia`](mediadevices/getusermedia)
* [HTML5's Media Recorder API in Action on Chrome and Firefox](https://blog.addpipe.com/mediarecorder-api/)
* [MediaRecorder polyfill](https://github.com/ai/audio-recorder-polyfill) for Safari and Edge
* [TutorRoom](https://github.com/chrisjohndigital/TutorRoom): HTML video capture/playback/download using getUserMedia and the MediaStream Recording API ([source on GitHub](https://github.com/chrisjohndigital/TutorRoom))
* [Simple video recording demo](https://codepen.io/anon/pen/gpmPzm)
* [Advanced media stream recorder sample](https://quickblox.github.io/javascript-media-recorder/sample/)
* [OpenLang](https://github.com/chrisjohndigital/OpenLang): HTML video language lab web application using MediaDevices and the MediaStream Recording API for video recording ([source on GitHub](https://github.com/chrisjohndigital/OpenLang))
* [MediaStream Recorder API Now Available in Safari Technology Preview 73](https://blog.addpipe.com/safari-technology-preview-73-adds-limited-mediastream-recorder-api-support/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaStream_Recording_API>

Navigation API
==============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The **Navigation API** provides the ability to initiate, intercept, and manage browser navigation actions. It can also examine an application's history entries. This is a successor to previous web platform features such as the [History API](history_api) and [`window.location`](window/location), which solves their shortcomings and is specifically aimed at the needs of [single-page applications (SPAs)](https://developer.mozilla.org/en-US/docs/Glossary/SPA).



Concepts and usage
------------------



In SPAs, the page template tends to stay the same during usage, and the content is dynamically rewritten as the user visits different pages or features. As a result, only one distinct page is loaded in the browser, which breaks the expected user experience of navigating back and forth between different locations in the viewing history. This problem can be solved to a degree via the [History API](history_api), but it is not designed for the needs of SPAs. The Navigation API aims to bridge that gap.

 The API is accessed via the [`Window.navigation`](window/navigation) property, which returns a reference to a global [`Navigation`](navigation) object. Each `window` object has its own corresponding `navigation` instance.



### Handling navigations



The `navigation` interface has several associated events, the most notable being the [`navigate`](navigation/navigate_event) event. This is fired when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated, meaning that you can control all page navigations from one central place, ideal for routing functionality in SPA frameworks. (This is not the case with the [History API](history_api), where it is sometimes hard to figure out responding to all navigations.) The `navigate` event handler is passed a [`NavigateEvent`](navigateevent) object, which contains detailed information including details around the navigation's destination, type, whether it contains `POST` form data or a download request, and more.

 The `NavigationEvent` object also provides two methods:

 * [`intercept()`](navigateevent/intercept) takes as an argument a callback handler function returning a promise. It allows you to control what happens when the navigation is initiated. For example, in the case of an SPA, it can be used to load relevant new content into the UI based on the path of the URL navigated to.
* [`scroll()`](navigateevent/scroll) allows you to manually initiate the browser's scroll behavior (e.g. to a fragment identifier in the URL), if it makes sense for your code, rather than waiting for the browser to handle it automatically.

 Once a navigation is initiated, and your `intercept()` handler is called, a [`NavigationTransition`](navigationtransition) object instance is created (accessible via [`Navigation.transition`](navigation/transition)), which can be used to track the process of the ongoing navigation.

  **Note:** In this context "transition" refers to the transition between one history entry and another. It isn't related to CSS transitions.

   **Note:** You can also call [`preventDefault()`](event/preventdefault) to stop the navigation entirely for most [navigation types](navigateevent/navigationtype#value); cancellation of traverse navigations is not yet implemented.

  When the `intercept()` handler function's promise fulfills, the `Navigation` object's [`navigatesuccess`](navigation/navigatesuccess_event) event fires, allowing you to run cleanup code after a successful navigation has completed. If it rejects, meaning the navigation has failed, [`navigateerror`](navigation/navigateerror_event) fires instead, allowing you to gracefully handle the failure case. There is also a [`finished`](navigationtransition/finished) property on the `NavigationTransition` object, which fulfills or rejects at the same time as the aforementioned events are fired, providing another path for handling the success and failure cases.

  **Note:** Before the Navigation API was available, to do something similar you'd have to listen for all click events on links, run `e.preventDefault()`, perform the appropriate [`History.pushState()`](history/pushstate) call, then set up the page view based on the new URL. And this wouldn't handle all navigations — only user-initiated link clicks.

 

### Programmatically updating and traversing the navigation history



As the user navigates through your application, each new location navigated to results in the creation of a navigation history entry. Each history entry is represented by a distinct [`NavigationHistoryEntry`](navigationhistoryentry) object instance. These contain several properties such as the entry's key, URL, and state information. You can get the entry that the user is currently on right now using [`Navigation.currentEntry`](navigation/currententry), and an array of all existing history entries using [`Navigation.entries()`](navigation/entries). Each `NavigationHistoryEntry` object has a [`dispose`](navigationhistoryentry/dispose_event) event, which fires when the entry is no longer part of the browser history. For example, if the user navigates back three times, then navigates forward to somewhere else, those three history entries will be disposed of.

  **Note:** The Navigation API only exposes history entries created in the current browsing context that have the same origin as the current page (e.g. not navigations inside embedded [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe)s, or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than with the older [History API](history_api).

  The `Navigation` object contains all the methods you'll need to update and traverse through the navigation history:

  
[`navigate()`](navigation/navigate)  Experimental 
  Navigates to a new URL, creating a new navigation history entry.

  
[`reload()`](navigation/reload)  Experimental 
  Reloads the current navigation history entry.

  
[`back()`](navigation/back)  Experimental 
  Navigates to the previous navigation history entry, if that is possible.

  
[`forward()`](navigation/forward)  Experimental 
  Navigates to the next navigation history entry, if that is possible.

  
[`traverseTo()`](navigation/traverseto)  Experimental 
  Navigates to a specific navigation history entry identified by its key value, which is obtained via the relevant entry's [`NavigationHistoryEntry.key`](navigationhistoryentry/key) property.

   Each one of the above methods returns an object containing two promises — `{ committed, finished }`. This allows the invoking function to wait on taking further action until:

 * `committed` fulfills, meaning that the visible URL has changed and a new [`NavigationHistoryEntry`](navigationhistoryentry) has been created.
* `finished` fulfills, meaning that all promises returned by your `intercept()` handler are fulfilled. This is equivalent to the [`NavigationTransition.finished`](navigationtransition/finished) promise fulfilling, when the [`navigatesuccess`](navigation/navigatesuccess_event) event fires, as mentioned earlier.
* either one of the above promises rejects, meaning that the navigation has failed for some reason.



### State



The Navigation API allows you to store state on each history entry. This is developer-defined information — it can be whatever you like. For example, you might want to store a `visitCount` property that records the number of times a view has been visited, or an object containing multiple properties related to UI state, so that state can be restored when a user returns to that view.

 To get a [`NavigationHistoryEntry`](navigationhistoryentry)'s state, you call its [`getState()`](navigationhistoryentry/getstate) method. It is initially `undefined`, but when state information is set on the entry, it will return the previously-set state information.

 Setting state is a bit more nuanced. You can't retrieve the state value and then update it directly — the copy stored on the entry will not change. Instead, you update it while performing a [`navigate()`](navigation/navigate) or [`reload()`](navigation/reload) — each one of these optionally takes an options object parameter, which includes a `state` property containing the new state to set on the history entry. When these navigations commit, the state change will be automatically applied.

 In some cases however, a state change will be independent from a navigation or reload — for example when a page contains an expandable/collapsible [`<details>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details) element. In this case, you might want to store the expanded/collapsed state in your history entry, so you can restore it when the user returns to the page or restarts their browser. Cases like this are handled using [`Navigation.updateCurrentEntry()`](navigation/updatecurrententry). The [`currententrychange`](navigation/currententrychange_event) will fire when the current entry change is complete.



### Limitations



There are a few perceived limitations with the Navigation API:

 1. The current specification doesn't trigger a [`navigate`](navigation/navigate_event) event on a page's first load. This might be fine for sites that use Server Side Rendering (SSR)—your server could return the correct initial state, which is the fastest way to get content to your users. But sites that leverage client-side code to create their pages may need an additional function to initialize the page.
2. The Navigation API operates only within a single frame—the top-level page, or a single specific [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe). This has some interesting implications that are [further documented in the spec](https://github.com/WICG/navigation-api#warning-backforward-are-not-always-opposites), but in practice, will reduce developer confusion. The previous [History API](history_api) has several confusing edge cases, like support for frames, which the Navigation API handles up-front.
3. You can't currently use the Navigation API to programmatically modify or rearrange the history list. It might be useful to have a temporary state, for example navigating the user to a temporary modal that asks them for some information, then going back to the previous URL. In this case, you'd want to delete the temporary modal navigation entry so the user cannot mess up the application flow by hitting the forward button and opening it again.



Interfaces
----------


 [`NavigateEvent`](navigateevent)  Event object for the [`navigate`](navigation/navigate_event) event, which fires when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated. It provides access to information about that navigation, and most notably the [`intercept()`](navigateevent/intercept), which allows you to control what happens when the navigation is initiated.

  [`Navigation`](navigation)  Allows control over all navigation actions for the current `window` in one central place, including initiating navigations programmatically, examining navigation history entries, and managing navigations as they happen.

  [`NavigationCurrentEntryChangeEvent`](navigationcurrententrychangeevent)  Event object for the [`currententrychange`](navigation/currententrychange_event) event, which fires when the [`Navigation.currentEntry`](navigation/currententry) has changed. It provides access to the navigation type, and the previous history entry that was navigated from.

  [`NavigationDestination`](navigationdestination)  Represents the destination being navigated to in the current navigation.

  [`NavigationHistoryEntry`](navigationhistoryentry)  Represents a single navigation history entry.

  [`NavigationTransition`](navigationtransition)  Represents an ongoing navigation.

  
Extensions to other interfaces
------------------------------


 [`Window.navigation`](window/navigation)  Returns the current `window`'s associated [`Navigation`](navigation) object. Entry point for the API.

  
Examples
--------


 **Note:** Check out Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/).

 
### Handling a navigation using `intercept()`



```
navigation.addEventListener("navigate", (event) => {
  // Exit early if this navigation shouldn't be intercepted,
  // e.g. if the navigation is cross-origin, or a download request
  if (shouldNotIntercept(event)) {
    return;
  }

  const url = new URL(event.destination.url);

  if (url.pathname.startsWith("/articles/")) {
    event.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);
        renderArticlePage(articleContent);
      },
    });
  }
});

```

### Handling scrolling using `scroll()`



In this example of intercepting a navigation, the `handler()` function starts by fetching and rendering some article content, but then fetches and renders some secondary content afterwards. It makes sense to scroll the page to the main article content as soon as it is available so the user can interact with it, rather than waiting until the secondary content is also rendered. To achieve this, we have added a [`scroll()`](navigateevent/scroll) call between the two.

 
```
navigation.addEventListener("navigate", (event) => {
  if (shouldNotIntercept(event)) {
    return;
  }
  const url = new URL(event.destination.url);

  if (url.pathname.startsWith("/articles/")) {
    event.intercept({
      async handler() {
        const articleContent = await getArticleContent(url.pathname);
        renderArticlePage(articleContent);

        event.scroll();

        const secondaryContent = await getSecondaryContent(url.pathname);
        addSecondaryContent(secondaryContent);
      },
    });
  }
});

```


### Traversing to a specific history entry



```
// On JS startup, get the key of the first loaded page
// so the user can always go back there.
const { key } = navigation.currentEntry;
backToHomeButton.onclick = () => navigation.traverseTo(key);

// Navigate away, but the button will always work.
await navigation.navigate("/another\_url").finished;

```

### Updating state




```
navigation.navigate(url, { state: newState });

```
 Or

 
```
navigation.reload({ state: newState });

```
 Or if the state is independent from a navigation or reload:

 
```
navigation.updateCurrentEntry({ state: newState });

```


Specifications
--------------




| Specification |
| --- |
| [Unknown specification # global](https://wicg.github.io/navigation-api/#global) |
| [Unknown specification # navigate-event-class](https://wicg.github.io/navigation-api/#navigate-event-class) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `NavigateEvent` | 102 | 102 | No | No | No | No | 102 | 102 | No | 70 | No | 19.0 |
| `Navigation_API` | 102 | 102 | No | No | No | No | 102 | 102 | No | 70 | No | 19.0 |
| `canIntercept` | 105 | 105 | No | No | No | No | 105 | 105 | No | 72 | No | 20.0 |
| `canTransition` | 102–108 | 102–108 | No | No | No | No | 102–108 | 102–108 | No | 70–73 | No | 19.0 |
| `destination` | 102 | 102 | No | No | No | No | 102 | 102 | No | 70 | No | 19.0 |
| `downloadRequest` | 102 | 102 | No | No | No | No | 102 | 102 | No | 70 | No | 19.0 |
| `formData` | 102 | 102 | No | No | No | No | 102 | 102 | No | 70 | No | 19.0 |
| `hashChange` | 102 | 102 | No | No | No | No | 102 | 102 | No | 70 | No | 19.0 |
| `info` | 102 | 102 | No | No | No | No | 102 | 102 | No | 70 | No | 19.0 |
| `intercept` | 105 | 105 | No | No | No | No | 105 | 105 | No | 72 | No | 20.0 |
| `navigationType` | 102 | 102 | No | No | No | No | 102 | 102 | No | 70 | No | 19.0 |
| `restoreScroll` | 102–108 | 102–108 | No | No | No | No | 102–108 | 102–108 | No | 70–73 | No | 19.0 |
| `scroll` | 105 | 105 | No | No | No | No | 105 | 105 | No | 72 | No | 20.0 |
| `signal` | 102 | 102 | No | No | No | No | 102 | 102 | No | 70 | No | 19.0 |
| `transitionWhile` | 102–108 | 102–108 | No | No | No | No | 102–108 | 102–108 | No | 70–73 | No | 19.0 |
| `userInitiated` | 102 | 102 | No | No | No | No | 102 | 102 | No | 70 | No | 19.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Navigation_API` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `back` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `canGoBack` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `canGoForward` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `currentEntry` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `currententrychange_event` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `entries` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `forward` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `navigate` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `navigate_event` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `navigateerror_event` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `navigatesuccess_event` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `reload` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `transition` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `traverseTo` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `updateCurrentEntry` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |


### api.Navigation


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.NavigateEvent


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


See also
--------


* [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/)
* [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Navigation_API>

Network Information API
=======================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

  The Network Information API provides information about the system's connection in terms of general connection type (e.g., 'wifi, 'cellular', etc.). This can be used to select high definition content or low definition content based on the user's connection. 

 The interface consists of a single [`NetworkInformation`](networkinformation) object, an instance of which is returned by the [`Navigator.connection`](navigator/connection) property.


 **Note:** This feature is available in [Web Workers](web_workers_api)

 

Interfaces
----------


 [`NetworkInformation`](networkinformation)  Provides information about the connection a device is using to communicate with the network and provides a means for scripts to be notified if the connection type changes. The `NetworkInformation` interface cannot be instantiated. It is instead accessed through the [`Navigator`](navigator) interface.

  
Examples
--------


### Detect connection changes



This example watches for changes to the user's connection.

 
```
let type = navigator.connection.effectiveType;

function updateConnectionStatus() {
  console.log(
    `Connection type changed from ${type} to ${navigator.connection.effectiveType}`
  );
  type = navigator.connection.effectiveType;
}

navigator.connection.addEventListener("change", updateConnectionStatus);

```


### Preload large resources



The connection object is useful for deciding whether to preload resources that take large amounts of bandwidth or memory. This example would be called soon after page load to check for a connection type where preloading a video may not be desirable. If a cellular connection is found, then the `preloadVideo` flag is set to `false`. For simplicity and clarity, this example only tests for one connection type. A real-world use case would likely use a switch statement or some other method to check all of the possible values of [`NetworkInformation.type`](networkinformation/type). Regardless of the `type` value you can get an estimate of connection speed through the [`NetworkInformation.effectiveType`](networkinformation/effectivetype) property.

 
```
let preloadVideo = true;
const connection = navigator.connection;
if (connection) {
  if (connection.effectiveType === "slow-2g") {
    preloadVideo = false;
  }
}

```


Specifications
--------------




| Specification |
| --- |
| [Network Information API # networkinformation-interface](https://wicg.github.io/netinfo/#networkinformation-interface) |
| [Network Information API # connection-attribute](https://wicg.github.io/netinfo/#connection-attribute) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Network_Information_API` | 61 | 79 | 31–32 | No | 48 | NoSee [bug 185697](https://webkit.org/b/185697). | 50 | 38 | 14–99 | 37 | NoSee [bug 185697](https://webkit.org/b/185697). | 3.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Network_Information_API` | 61 | 79 | 31–32 | No | 48 | NoSee [bug 185697](https://webkit.org/b/185697). | 50 | 38 | 31–99 | 25 | NoSee [bug 185697](https://webkit.org/b/185697). | 3.0 |
| `change_event` | 61 | 79 | No | No | 48 | No | 50 | 38 | NoOn Firefox, the event handler property corresponding to the `change` event is `ontypechange`. | 45 | No | 3.0 |
| `downlink` | 61The value is never greater than 10 Mbps, as a non-standard anti-fingerprinting measure. | 79The value is never greater than 10 Mbps, as a non-standard anti-fingerprinting measure. | No | No | 48The value is never greater than 10 Mbps, as a non-standard anti-fingerprinting measure. | No | 50The value is never greater than 10 Mbps, as a non-standard anti-fingerprinting measure. | 38The value is never greater than 10 Mbps, as a non-standard anti-fingerprinting measure. | No | 25The value is never greater than 10 Mbps, as a non-standard anti-fingerprinting measure. | No | 3.0The value is never greater than 10 Mbps, as a non-standard anti-fingerprinting measure. |
| `downlinkMax` | 61Only supported in Chrome OS | No | No | No | No | No | 50 | 38 | No | 45 | No | 3.0 |
| `effectiveType` | 61 | 79 | No | No | 48 | No | 50 | 38 | No | 45 | No | 3.0 |
| `rtt` | 61The value is never greater than 3000 ms, as a non-standard anti-fingerprinting measure. | 79The value is never greater than 3000 ms, as a non-standard anti-fingerprinting measure. | No | No | 48The value is never greater than 3000 ms, as a non-standard anti-fingerprinting measure. | No | 50The value is never greater than 3000 ms, as a non-standard anti-fingerprinting measure. | 38The value is never greater than 3000 ms, as a non-standard anti-fingerprinting measure. | No | 25The value is never greater than 3000 ms, as a non-standard anti-fingerprinting measure. | No | 3.0The value is never greater than 3000 ms, as a non-standard anti-fingerprinting measure. |
| `saveData` | 65 | 79 | No | No | 52 | No | 65 | 65 | No | 47 | No | 9.0 |
| `type` | 61Only supported in Chrome OS | No | 31–32 | No | No | No | 50 | 38 | 31–99 | 45 | No | 3.0 |
| `typechange_event` | No | No | 31–32 | No | No | No | 50 | 38Removal proposed in [bug 699892](https://crbug.com/699892). | 31–99 | 25Removal proposed in [bug 699892](https://crbug.com/699892). | No | 3.0Removal proposed in [bug 699892](https://crbug.com/699892). |
| `worker_support` | 61 | 79 | 31–32 | No | 48 | No | 50 | 38 | 53–99 | 45 | No | 3.0 |


### api.NetworkInformation


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.Navigator.connection


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


See also
--------


* [Online and offline events](navigator/online)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API>

Page Visibility API
===================



The Page Visibility API provides events you can watch for to know when a document becomes visible or hidden, as well as features to look at the current visibility state of the page.

 This is especially useful for saving resources and improving performance by letting a page avoid performing unnecessary tasks when the document isn't visible.



Concepts and usage
------------------



When the user minimizes the window or switches to another tab, the API sends a [`visibilitychange`](document/visibilitychange_event) event to let listeners know the state of the page has changed. You can detect the event and perform some actions or behave differently. For example, if your web app is playing a video, it can pause the video when the user puts the tab into the background, and resume playback when the user returns to the tab. The user doesn't lose their place in the video, the video's soundtrack doesn't interfere with audio in the new foreground tab, and the user doesn't miss any of the video in the meantime.

 Visibility states of an [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe) are the same as the parent document. Hiding an `<iframe>` using CSS properties (such as [`display: none;`](https://developer.mozilla.org/en-US/docs/Web/CSS/display)) doesn't trigger visibility events or change the state of the document contained within the frame.



### Use cases



Let's consider a few use cases for the Page Visibility API.

 * A site has an image carousel that shouldn't advance to the next slide unless the user is viewing the page
* An application showing a dashboard of information doesn't want to poll the server for updates when the page isn't visible
* A page wants to detect when it is being prerendered so it can keep accurate count of page views
* A site wants to switch off sounds when a device is in standby mode (user pushes power button to turn screen off)

 Developers have historically used imperfect proxies to detect this. For example, watching for [`blur`](window/blur_event) and [`focus`](window/focus_event) events on the window helps you know when your page is not the active page, but it does not tell you that your page is actually hidden to the user. The Page Visibility API addresses this.

  **Note:** While [`onblur`](window/blur_event) and [`onfocus`](window/focus_event) will tell you if the user switches windows, it doesn't necessarily mean it's hidden. Pages only become hidden when the user switches tabs or minimizes the browser window containing the tab.

 

### Policies in place to aid background page performance



Separately from the Page Visibility API, user agents typically have a number of policies in place to mitigate the performance impact of background or hidden tabs. These may include:

 * Most browsers stop sending [`requestAnimationFrame()`](window/requestanimationframe) callbacks to background tabs or hidden [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe)s in order to improve performance and battery life.
* Timers such as [`setTimeout()`](settimeout) are throttled in background/inactive tabs to help improve performance. See [Reasons for delays longer than specified](settimeout#reasons_for_delays_longer_than_specified) for more details.
* Browsers implement budget-based background timeout throttling. This operates in a similar way across modern browsers, with the details being as follows:
	+ In Firefox, windows in background tabs each have their own time budget in milliseconds — a max and a min value of +50 ms and -150 ms, respectively. Chrome is very similar except that the budget is specified in seconds.
	+ Windows are subjected to throttling after 30 seconds, with the same throttling delay rules as specified for window timers (again, see [Reasons for delays longer than specified](settimeout#reasons_for_delays_longer_than_specified)). In Chrome, this value is 10 seconds.
	+ Timer tasks are only permitted when the budget is non-negative.
	+ Once a timer's code has finished running, the duration of time it took to execute is subtracted from its window's timeout budget.
	+ The budget regenerates at a rate of 10 ms per second, in both Firefox and Chrome.

 Some processes are exempt from this throttling behavior. In these cases, you can use the Page Visibility API to reduce the tabs' performance impact while they're hidden.

 * Tabs which are playing audio are considered foreground and aren't throttled.
* Tabs running code that's using real-time network connections ([WebSockets](websockets_api) and [WebRTC](webrtc_api)) go unthrottled in order to avoid closing these connections timing out and getting unexpectedly closed.
* [IndexedDB](indexeddb_api) processes are also left unthrottled in order to avoid timeouts.



Extensions to other interfaces
------------------------------


### Instance properties



The Page Visibility API adds the following properties to the [`Document`](document) interface:

  
[`Document.hidden`](document/hidden)  Deprecated  Read only 
  Returns `true` if the page is in a state considered to be hidden to the user, and `false` otherwise.

  
[`Document.visibilityState`](document/visibilitystate) Read only 
  A string indicating the document's current visibility state. Possible values are:

  `visible`  The page content may be at least partially visible. In practice this means that the page is the foreground tab of a non-minimized window.

  `hidden`  The page's content is not visible to the user, either due to the document's tab being in the background or part of a window that is minimized, or because the device's screen is off.

    

### Events



The Page Visibility API adds the following events to the [`Document`](document) interface:

  [`visibilitychange`](document/visibilitychange_event)  Fired when the content of a tab has become visible or has been hidden.

  

Examples
--------


### Pausing audio on page hide



This example pauses audio when the user switches to a different tab, and plays when they switch back.

 #### HTML

 
```
<audio
 controls
 src="https://mdn.github.io/webaudio-examples/audio-basics/outfoxing.mp3"></audio>

```
 #### JavaScript

 
```
const audio = document.querySelector("audio");

// Handle page visibility change:
// - If the page is hidden, pause the video
// - If the page is shown, play the video
document.addEventListener("visibilitychange", () => {
  if (document.hidden) {
    audio.pause();
  } else {
    audio.play();
  }
});

```
 #### Result


 Try playing the audio, then switching to a different tab and back again.



Specifications
--------------




| Specification |
| --- |
| [HTML Standard # dom-document-visibilitystate](https://html.spec.whatwg.org/multipage/interaction.html#dom-document-visibilitystate) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Page_Visibility_API` | 3313 | 12 | 1810–52 | 10 | 201512.1–15 | 7 | ≤374.4.3 | 3318 | 1810–52 | 201412.1–14 | 7 | 2.01.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API>

Intersection Observer API
=========================



The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's [viewport](https://developer.mozilla.org/en-US/docs/Glossary/Viewport).

 Historically, detecting visibility of an element, or the relative visibility of two elements in relation to each other, has been a difficult task for which solutions have been unreliable and prone to causing the browser and the sites the user is accessing to become sluggish. As the web has matured, the need for this kind of information has grown. Intersection information is needed for many reasons, such as:

 * Lazy-loading of images or other content as a page is scrolled.
* Implementing "infinite scrolling" web sites, where more and more content is loaded and rendered as you scroll, so that the user doesn't have to flip through pages.
* Reporting of visibility of advertisements in order to calculate ad revenues.
* Deciding whether or not to perform tasks or animation processes based on whether or not the user will see the result.

 Implementing intersection detection in the past involved event handlers and loops calling methods like [`Element.getBoundingClientRect()`](element/getboundingclientrect) to build up the needed information for every element affected. Since all this code runs on the main thread, even one of these can cause performance problems. When a site is loaded with these tests, things can get downright ugly.

 Consider a web page that uses infinite scrolling. It uses a vendor-provided library to manage the advertisements placed periodically throughout the page, has animated graphics here and there, and uses a custom library that draws notification boxes and the like. Each of these has its own intersection detection routines, all running on the main thread. The author of the web site may not even realize this is happening, since they may know very little about the inner workings of the two libraries they are using. As the user scrolls the page, these intersection detection routines are firing constantly during the scroll handling code, resulting in an experience that leaves the user frustrated with the browser, the web site, and their computer.

 The Intersection Observer API lets code register a callback function that is executed whenever an element they wish to monitor enters or exits another element (or the [viewport](https://developer.mozilla.org/en-US/docs/Glossary/Viewport)), or when the amount by which the two intersect changes by a requested amount. This way, sites no longer need to do anything on the main thread to watch for this kind of element intersection, and the browser is free to optimize the management of intersections as it sees fit.

 One thing the Intersection Observer API can't tell you: the exact number of pixels that overlap or specifically which ones they are; however, it covers the much more common use case of "If they intersect by somewhere around *N*%, I need to do something."



Intersection observer concepts and usage
----------------------------------------



The Intersection Observer API allows you to configure a callback that is called when either of these circumstances occur:

 * A **target** element intersects either the device's viewport or a specified element. That specified element is called the **root element** or **root** for the purposes of the Intersection Observer API.
* The first time the observer is initially asked to watch a target element.

 Typically, you'll want to watch for intersection changes with regard to the target element's closest scrollable ancestor, or, if the target element isn't a descendant of a scrollable element, the device's viewport. To watch for intersection relative to the device's viewport, specify `null` for `root` option. Keep reading for a more detailed explanation about intersection observer options.

 Whether you're using the viewport or some other element as the root, the API works the same way, executing a callback function you provide whenever the visibility of the target element changes so that it crosses desired amounts of intersection with the root.

 The degree of intersection between the target element and its root is the **intersection ratio**. This is a representation of the percentage of the target element which is visible as a value between 0.0 and 1.0.



### Creating an intersection observer



Create the intersection observer by calling its constructor and passing it a callback function to be run whenever a threshold is crossed in one direction or the other:

 
```
let options = {
  root: document.querySelector("#scrollArea"),
  rootMargin: "0px",
  threshold: 1.0,
};

let observer = new IntersectionObserver(callback, options);

```
 A threshold of 1.0 means that when 100% of the target is visible within the element specified by the `root` option, the callback is invoked.

 #### Intersection observer options

 The `options` object passed into the [`IntersectionObserver()`](intersectionobserver/intersectionobserver) constructor let you control the circumstances under which the observer's callback is invoked. It has the following fields:

  `root`  The element that is used as the viewport for checking visibility of the target. Must be the ancestor of the target. Defaults to the browser viewport if not specified or if `null`.

  `rootMargin`  Margin around the root. Can have values similar to the CSS [`margin`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin) property, e.g. "`10px 20px 30px 40px"` (top, right, bottom, left). The values can be percentages. This set of values serves to grow or shrink each side of the root element's bounding box before computing intersections. Defaults to all zeros.

  `threshold`  Either a single number or an array of numbers which indicate at what percentage of the target's visibility the observer's callback should be executed. If you only want to detect when visibility passes the 50% mark, you can use a value of 0.5. If you want the callback to run every time visibility passes another 25%, you would specify the array [0, 0.25, 0.5, 0.75, 1]. The default is 0 (meaning as soon as even one pixel is visible, the callback will be run). A value of 1.0 means that the threshold isn't considered passed until every pixel is visible.

   #### Targeting an element to be observed

 Once you have created the observer, you need to give it a target element to watch:

 
```
let target = document.querySelector("#listItem");
observer.observe(target);

// the callback we setup for the observer will be executed now for the first time
// it waits until we assign a target to our observer (even if the target is currently not visible)

```
 Whenever the target meets a threshold specified for the `IntersectionObserver`, the callback is invoked. The callback receives a list of [`IntersectionObserverEntry`](intersectionobserverentry) objects and the observer:

 
```
let callback = (entries, observer) => {
  entries.forEach((entry) => {
    // Each entry describes an intersection change for one observed
    // target element:
    // entry.boundingClientRect
    // entry.intersectionRatio
    // entry.intersectionRect
    // entry.isIntersecting
    // entry.rootBounds
    // entry.target
    // entry.time
  });
};

```
 The list of entries received by the callback includes one entry for each target which reported a change in its intersection status. Check the value of the [`isIntersecting`](intersectionobserverentry/isintersecting) property to see if the entry represents an element that currently intersects with the root.

 Be aware that your callback is executed on the main thread. It should operate as quickly as possible; if anything time-consuming needs to be done, use [`Window.requestIdleCallback()`](window/requestidlecallback).

 Also, note that if you specified the `root` option, the target must be a descendant of the root element.



### How intersection is calculated



All areas considered by the Intersection Observer API are rectangles; elements which are irregularly shaped are considered as occupying the smallest rectangle which encloses all of the element's parts. Similarly, if the visible portion of an element is not rectangular, the element's intersection rectangle is considered to be the smallest rectangle that contains all the visible portions of the element.

 It's useful to understand a bit about how the various properties provided by [`IntersectionObserverEntry`](intersectionobserverentry) describe an intersection.

 #### The intersection root and root margin

 Before we can track the intersection of an element with a container, we need to know what that container is. That container is the **intersection root**, or **root element**. This can be either a specific element in the document which is an ancestor of the element to be observed, or `null` to use the document's viewport as the container.

 The ***root intersection rectangle*** is the rectangle used to check against the target or targets. This rectangle is determined like this:

 * If the intersection root is the implicit root (that is, the top-level [`Document`](document)), the root intersection rectangle is the viewport's rectangle.
* If the intersection root has an overflow clip, the root intersection rectangle is the root element's content area.
* Otherwise, the root intersection rectangle is the intersection root's bounding client rectangle (as returned by calling [`getBoundingClientRect()`](element/getboundingclientrect) on it).

 The root intersection rectangle can be adjusted further by setting the **root margin**, `rootMargin`, when creating the [`IntersectionObserver`](intersectionobserver). The values in `rootMargin` define offsets added to each side of the intersection root's bounding box to create the final intersection root bounds (which are disclosed in [`IntersectionObserverEntry.rootBounds`](intersectionobserverentry/rootbounds) when the callback is executed).

 #### Thresholds

 Rather than reporting every infinitesimal change in how much a target element is visible, the Intersection Observer API uses **thresholds**. When you create an observer, you can provide one or more numeric values representing percentages of the target element which are visible. Then, the API only reports changes to visibility which cross these thresholds.

 For example, if you want to be informed every time a target's visibility passes backward or forward through each 25% mark, you would specify the array [0, 0.25, 0.5, 0.75, 1] as the list of thresholds when creating the observer.

 When the callback is invoked, it receives a list of `IntersectionObserverEntry` objects, one for each observed target which has had the degree to which it intersects the root change such that the amount exposed crosses over one of the thresholds, in either direction.

 You can see if the target *currently* intersects the root by looking at the entry's [`isIntersecting`](intersectionobserverentry/isintersecting) property; if its value is `true`, the target is at least partially intersecting the root element or document. This lets you determine whether the entry represents a transition from the elements intersecting to no longer intersecting or a transition from not intersecting to intersecting.

 Note that it's possible to have a non-zero intersection rectangle, which can happen if the intersection is exactly along the boundary between the two or the area of [`boundingClientRect`](intersectionobserverentry/boundingclientrect) is zero. This state of the target and root sharing a boundary line is not considered enough to be considered transitioning into an intersecting state.

 To get a feeling for how thresholds work, try scrolling the box below around. Each colored box within it displays the percentage of itself that's visible in all four of its corners, so you can see these ratios change over time as you scroll the container. Each box has a different set of thresholds:

 * The first box has a threshold for each percentage point of visibility; that is, the [`IntersectionObserver.thresholds`](intersectionobserver/thresholds) array is `[0.00, 0.01, 0.02, /*…,*/ 0.99, 1.00]`.
* The second box has a single threshold, at the 50% mark.
* The third box has thresholds every 10% of visibility (0%, 10%, 20%, etc.).
* The last box has thresholds each 25%.


 #### Clipping and the intersection rectangle

 The browser computes the final intersection rectangle as follows; this is all done for you, but it can be helpful to understand these steps in order to better grasp exactly when intersections will occur.

 1. The target element's bounding rectangle (that is, the smallest rectangle that fully encloses the bounding boxes of every component that makes up the element) is obtained by calling [`getBoundingClientRect()`](element/getboundingclientrect) on the target. This is the largest the intersection rectangle may be. The remaining steps will remove any portions that don't intersect.
2. Starting at the target's immediate parent block and moving outward, each containing block's clipping (if any) is applied to the intersection rectangle. A block's clipping is determined based on the intersection of the two blocks and the clipping mode (if any) specified by the [`overflow`](https://developer.mozilla.org/en-US/docs/Web/CSS/overflow) property. Setting `overflow` to anything but `visible` causes clipping to occur.
3. If one of the containing elements is the root of a nested browsing context (such as the document contained in an [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe)), the intersection rectangle is clipped to the containing context's viewport, and recursion upward through the containers continues with the container's containing block. So if the top level of an `<iframe>` is reached, the intersection rectangle is clipped to the frame's viewport, then the frame's parent element is the next block recursed through toward the intersection root.
4. When recursion upward reaches the intersection root, the resulting rectangle is mapped to the intersection root's coordinate space.
5. The resulting rectangle is then updated by intersecting it with the [root intersection rectangle](#root-intersection-rectangle).
6. This rectangle is, finally, mapped to the coordinate space of the target's [`document`](document).



### Intersection change callbacks



When the amount of a target element which is visible within the root element crosses one of the visibility thresholds, the [`IntersectionObserver`](intersectionobserver) object's callback is executed. The callback receives as input an array of all of [`IntersectionObserverEntry`](intersectionobserverentry) objects, one for each threshold which was crossed, and a reference to the `IntersectionObserver` object itself.

 Each entry in the list of thresholds is an [`IntersectionObserverEntry`](intersectionobserverentry) object describing one threshold that was crossed; that is, each entry describes how much of a given element is intersecting with the root element, whether or not the element is considered to be intersecting or not, and the direction in which the transition occurred.

 The code snippet below shows a callback which keeps a counter of how many times elements transition from not intersecting the root to intersecting by at least 75%. For a threshold value of 0.0 (default) the callback is called [approximately](https://www.w3.org/TR/intersection-observer/#dom-intersectionobserverentry-isintersecting) upon transition of the boolean value of [`isIntersecting`](intersectionobserverentry/isintersecting). The snippet thus first checks that the transition is a positive one, then determines whether [`intersectionRatio`](intersectionobserverentry/intersectionratio) is above 75%, in which case it increments the counter.

 
```
const intersectionCallback = (entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      let elem = entry.target;

      if (entry.intersectionRatio >= 0.75) {
        intersectionCounter++;
      }
    }
  });
};

```


Interfaces
----------


 [`IntersectionObserver`](intersectionobserver)  The primary interface for the Intersection Observer API. Provides methods for creating and managing an observer which can watch any number of target elements for the same intersection configuration. Each observer can asynchronously observe changes in the intersection between one or more target elements and a shared ancestor element or with their top-level [`Document`](document)'s [viewport](https://developer.mozilla.org/en-US/docs/Glossary/Viewport). The ancestor or viewport is referred to as the **root**.

  [`IntersectionObserverEntry`](intersectionobserverentry)  Describes the intersection between the target element and its root container at a specific moment of transition. Objects of this type can only be obtained in two ways: as an input to your `IntersectionObserver` callback, or by calling [`IntersectionObserver.takeRecords()`](intersectionobserver/takerecords).

  
A simple example
----------------


This simple example causes a target element to change its color and transparency as it becomes more or less visible. At [Timing element visibility with the Intersection Observer API](intersection_observer_api/timing_element_visibility), you can find a more extensive example showing how to time how long a set of elements (such as ads) are visible to the user and to react to that information by recording statistics or by updating elements.


### HTML



The HTML for this example is very short, with a primary element which is the box that we'll be targeting (with the creative ID `"box"`) and some contents within the box.

 
```
<div id="box">
  <div class="vertical">Welcome to <strong>The Box!</strong></div>
</div>

```


### CSS



The CSS isn't terribly important for the purposes of this example; it lays out the element and establishes that the [`background-color`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) and [`border`](https://developer.mozilla.org/en-US/docs/Web/CSS/border) attributes can participate in [CSS transitions](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions), which we'll use to affect the changes to the element as it becomes more or less obscured.

 
```
#box {
  background-color: rgba(40, 40, 190, 1);
  border: 4px solid rgb(20, 20, 120);
  transition: background-color 1s, border 1s;
  width: 350px;
  height: 350px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.vertical {
  color: white;
  font: 32px "Arial";
}

.extra {
  width: 350px;
  height: 350px;
  margin-top: 10px;
  border: 4px solid rgb(20, 20, 120);
  text-align: center;
  padding: 20px;
}

```


### JavaScript



Finally, let's take a look at the JavaScript code that uses the Intersection Observer API to make things happen.

 #### Setting up

 First, we need to prepare some variables and install the observer.

 
```
const numSteps = 20.0;

let boxElement;
let prevRatio = 0.0;
let increasingColor = "rgba(40, 40, 190, ratio)";
let decreasingColor = "rgba(190, 40, 40, ratio)";

// Set things up
window.addEventListener(
  "load",
  (event) => {
    boxElement = document.querySelector("#box");

    createObserver();
  },
  false
);

```
 The constants and variables we set up here are:

  `numSteps`  A constant which indicates how many thresholds we want to have between a visibility ratio of 0.0 and 1.0.

  `prevRatio`  This variable will be used to record what the visibility ratio was the last time a threshold was crossed; this will let us figure out whether the target element is becoming more or less visible.

  `increasingColor`  A string defining a color we'll apply to the target element when the visibility ratio is increasing. The word "ratio" in this string will be replaced with the target's current visibility ratio, so that the element not only changes color but also becomes increasingly opaque as it becomes less obscured.

  `decreasingColor`  Similarly, this is a string defining a color we'll apply when the visibility ratio is decreasing.

   We call [`Window.addEventListener()`](eventtarget/addeventlistener) to start listening for the [`load`](window/load_event) event; once the page has finished loading, we get a reference to the element with the ID `"box"` using [`querySelector()`](document/queryselector), then call the `createObserver()` method we'll create in a moment to handle building and installing the intersection observer.

 #### Creating the intersection observer

 The `createObserver()` method is called once page load is complete to handle actually creating the new [`IntersectionObserver`](intersectionobserver) and starting the process of observing the target element.

 
```
function createObserver() {
  let observer;

  let options = {
    root: null,
    rootMargin: "0px",
    threshold: buildThresholdList(),
  };

  observer = new IntersectionObserver(handleIntersect, options);
  observer.observe(boxElement);
}

```
 This begins by setting up an `options` object containing the settings for the observer. We want to watch for changes in visibility of the target element relative to the document's viewport, so `root` is `null`. We need no margin, so the margin offset, `rootMargin`, is specified as "0px". This causes the observer to watch for changes in the intersection between the target element's bounds and those of the viewport, without any added (or subtracted) space.

 The list of visibility ratio thresholds, `threshold`, is constructed by the function `buildThresholdList()`. The threshold list is built programmatically in this example since there are a number of them and the number is intended to be adjustable.

 Once `options` is ready, we create the new observer, calling the [`IntersectionObserver()`](intersectionobserver/intersectionobserver) constructor, specifying a function to be called when intersection crosses one of our thresholds, `handleIntersect()`, and our set of options. We then call [`observe()`](intersectionobserver/observe) on the returned observer, passing into it the desired target element.

 We could opt to monitor multiple elements for visibility intersection changes with respect to the viewport by calling `observer.observe()` for each of those elements, if we wanted to do so.

 #### Building the array of threshold ratios

 The `buildThresholdList()` function, which builds the list of thresholds, looks like this:

 
```
function buildThresholdList() {
  let thresholds = [];
  let numSteps = 20;

  for (let i = 1.0; i <= numSteps; i++) {
    let ratio = i / numSteps;
    thresholds.push(ratio);
  }

  thresholds.push(0);
  return thresholds;
}

```
 This builds the array of thresholds—each of which is a ratio between 0.0 and 1.0, by pushing the value `i/numSteps` onto the `thresholds` array for each integer `i` between 1 and `numSteps`. It also pushes 0 to include that value. The result, given the default value of `numSteps` (20), is the following list of thresholds:

 

| # | Ratio | # | Ratio |
| --- | --- | --- | --- |
| 1 | 0.05 | 11 | 0.55 |
| 2 | 0.1 | 12 | 0.6 |
| 3 | 0.15 | 13 | 0.65 |
| 4 | 0.2 | 14 | 0.7 |
| 5 | 0.25 | 15 | 0.75 |
| 6 | 0.3 | 16 | 0.8 |
| 7 | 0.35 | 17 | 0.85 |
| 8 | 0.4 | 18 | 0.9 |
| 9 | 0.45 | 19 | 0.95 |
| 10 | 0.5 | 20 | 1.0 |

 We could, of course, hard-code the array of thresholds into our code, and often that's what you'll end up doing. But this example leaves room for adding configuration controls to adjust the granularity, for example.

 #### Handling intersection changes

 When the browser detects that the target element (in our case, the one with the ID `"box"`) has been unveiled or obscured such that its visibility ratio crosses one of the thresholds in our list, it calls our handler function, `handleIntersect()`:

 
```
function handleIntersect(entries, observer) {
  entries.forEach((entry) => {
    if (entry.intersectionRatio > prevRatio) {
      entry.target.style.backgroundColor = increasingColor.replace(
        "ratio",
        entry.intersectionRatio
      );
    } else {
      entry.target.style.backgroundColor = decreasingColor.replace(
        "ratio",
        entry.intersectionRatio
      );
    }

    prevRatio = entry.intersectionRatio;
  });
}

```
 For each [`IntersectionObserverEntry`](intersectionobserverentry) in the list `entries`, we look to see if the entry's [`intersectionRatio`](intersectionobserverentry/intersectionratio) is going up; if it is, we set the target's [`background-color`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-color) to the string in `increasingColor` (remember, it's `"rgba(40, 40, 190, ratio)"`), replaces the word "ratio" with the entry's `intersectionRatio`. The result: not only does the color get changed, but the transparency of the target element changes, too; as the intersection ratio goes down, the background color's alpha value goes down with it, resulting in an element that's more transparent.

 Similarly, if the `intersectionRatio` is going down, we use the string `decreasingColor` and replace the word "ratio" in that with the `intersectionRatio` before setting the target element's `background-color`.

 Finally, in order to track whether the intersection ratio is going up or down, we remember the current ratio in the variable `prevRatio`.



### Result



Below is the resulting content. Scroll this page up and down and notice how the appearance of the box changes as you do so.


 There's an even more extensive example at [Timing element visibility with the Intersection Observer API](intersection_observer_api/timing_element_visibility).



Specifications
--------------




| Specification |
| --- |
| [Intersection Observer # intersection-observer-interface](https://w3c.github.io/IntersectionObserver/#intersection-observer-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `IntersectionObserver` | 51 | 15 | 55Before version 96, the constructor throws a `DOMException` if the `options.rootMargin` option is passed an empty string (see [bug 1738791](https://bugzil.la/1738791)). | No | 38 | 12.1 | 51 | 51 | 55 | 41 | 12.2 | 5.0 |
| `Intersection_Observer_API` | 51 | 15 | 55 | No | 38 | 12.1 | 51 | 51 | 55 | 41 | 12.2 | 5.0 |
| `disconnect` | 51 | 15Available since [Windows Insider Preview Build 14986](https://developer.microsoft.com/microsoft-edge/platform/status/intersectionobserver/). | 55 | No | 38 | 12.1 | 51 | 51 | 55 | 41 | 12.2 | 5.0 |
| `observe` | 51 | 15 | 55 | No | 38 | 12.1 | 51 | 51 | 55 | 41 | 12.2 | 5.0 |
| `root` | 51 | 15 | 55 | No | 38 | 12.1 | 51 | 51 | 55 | 41 | 12.2 | 5.0 |
| `rootMargin` | 51 | 15 | 55 | No | 38 | 12.1`rootMargin` does not work with `<iframe>`s. | 51 | 51 | 55 | 41 | 12.2`rootMargin` does not work with `<iframe>`s. | 5.0 |
| `takeRecords` | 51 | 15Available since [Windows Insider Preview Build 14986](https://developer.microsoft.com/microsoft-edge/platform/status/intersectionobserver/). | 55 | No | 38 | 12.1 | 51 | 51 | 55 | 41 | 12.2 | 5.0 |
| `thresholds` | 52 | 15 | 55 | No | 39 | 12.1 | 52 | 52 | 55 | 41 | 12.2 | 6.0 |
| `unobserve` | 51 | 15Available since [Windows Insider Preview Build 14986](https://developer.microsoft.com/microsoft-edge/platform/status/intersectionobserver/). | 55 | No | 38 | 12.1 | 51 | 51 | 55 | 41 | 12.2 | 5.0 |


See also
--------


* [Intersection Observer polyfill](https://github.com/w3c/IntersectionObserver)
* [Timing element visibility with the Intersection Observer API](intersection_observer_api/timing_element_visibility)
* [`IntersectionObserver`](intersectionobserver) and [`IntersectionObserverEntry`](intersectionobserverentry)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API>

Payment Handler API
===================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The Payment Handler API provides a standardized set of functionality for web applications to directly handle payments, rather than having to be redirected to a separate site for payment handling.

 When a merchant website initiates payment via the [Payment Request API](payment_request_api), the Payment Handler API handles discovery of applicable payment apps, presenting them as choices to the user, opening a payment handler window once a choice has been made to allow the user to enter their payment details, and handling the payment transaction with the payment app.

 Communication with payment apps (authorization, passing of payment credentials) is handled via Service Workers.



Concepts and usage
------------------



On a merchant website, a payment request is initiated by the construction of a new [`PaymentRequest`](paymentrequest) object:

 
```
const request = new PaymentRequest(
  [
    {
      supportedMethods: "https://bobbucks.dev/pay",
    },
  ],
  {
    total: {
      label: "total",
      amount: { value: "10", currency: "USD" },
    },
  }
);

```
 The `supportedMethods` property specifies a URL representing the payment method supported by the merchant. To use more than one payment method, you would specify them in an array of objects, like this:

 
```
const request = new PaymentRequest(
  [
    {
      supportedMethods: "https://alicebucks.dev/pay",
    },
    {
      supportedMethods: "https://bobbucks.dev/pay",
    },
  ],
  {
    total: {
      label: "total",
      amount: { value: "10", currency: "USD" },
    },
  }
);

```


### Making payment apps available



In supporting browsers, the process starts by requesting a payment method manifest file from each URL. A payment method manifest is typically called something like `payment-manifest.json` (the exact name can be whatever you like), and should be structured like this:

 
```
{
  "default\_applications": ["https://bobbucks.dev/manifest.json"],
  "supported\_origins": ["https://alicepay.friendsofalice.example"]
}

```
 Given a payment method identifier like `https://bobbucks.dev/pay`, the browser:

 1. Starts loading `https://bobbucks.dev/pay` and checks its HTTP headers.
	1. If a [`Link`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link) header is found with `rel="payment-method-manifest"`, then it downloads the payment method manifest at that location instead (see [Optionally route the browser to find the payment method manifest in another location](https://web.dev/setting-up-a-payment-method/#optionally-route-the-browser-to-find-the-payment-method-manifest-in-another-location) for details).
	2. Otherwise, parse the response body of `https://bobbucks.dev/pay` as the payment method manifest.
2. Parses the downloaded content as JSON with `default_applications` and `supported_origins` members.

 These members have the following purposes:

 * `default_applications` tells the browser where to find the default payment app that can use the BobBucks payment method if it doesn't already have one installed.
* `supported_origins` tells the browser what other payment apps are permitted to handle the BobBucks payment if needed. If they are already installed on the device, they will be presented to the user as alternative payment options alongside the default application.

 From the payment method manifest, the browser gets the URL of the default payment apps' [web app manifest](https://developer.mozilla.org/en-US/docs/Web/Manifest) files, which can be called whatever you like, and look something like this:

 
```
{
  "name": "Pay with BobBucks",
  "short\_name": "BobBucks",
  "description": "This is an example of the Payment Handler API.",
  "icons": [
    {
      "src": "images/manifest/icon-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "images/manifest/icon-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ],
  "serviceworker": {
    "src": "service-worker.js",
    "scope": "/",
    "use\_cache": false
  },
  "start\_url": "/",
  "display": "standalone",
  "theme\_color": "#3f51b5",
  "background\_color": "#3f51b5",
  "related\_applications": [
    {
      "platform": "play",
      "id": "com.example.android.samplepay",
      "min\_version": "1",
      "fingerprints": [
        {
          "type": "sha256\_cert",
          "value": "4C:FC:14:C6:97:DE:66:4E:66:97:50:C0:24:CE:5F:27:00:92:EE:F3:7F:18:B3:DA:77:66:84:CD:9D:E9:D2:CB"
        }
      ]
    }
  ]
}

```
 When the [`PaymentRequest.show()`](paymentrequest/show) method is invoked by the merchant app in response to a user gesture, the browser uses the [`name`](https://developer.mozilla.org/en-US/docs/Web/Manifest/name) and [`icons`](https://developer.mozilla.org/en-US/docs/Web/Manifest/icons) information found in each manifest to present the payment apps to the user in the browser-provided Payment Request UI.

 * If there are multiple payment app options, a list of options is presented to the user for them to choose from. Selecting a payment app will start the payment flow, which causes the browser to Just-In-Time (JIT) install the web app if necessary, registering the service worker specified in the [`serviceworker`](https://developer.mozilla.org/en-US/docs/Web/Manifest/serviceworker) member so it can handle the payment.
* If there is only one payment app option, the [`PaymentRequest.show()`](paymentrequest/show) method will start the payment flow with this payment app, JIT-installing it if necessary, as described above. This is an optimization to avoid presenting the user with a list that contains only one payment app choice.

  **Note:** If [`prefer_related_applications`](https://developer.mozilla.org/en-US/docs/Web/Manifest/prefer_related_applications) is set to `true` in the payment app manifest, the browser will launch the platform-specific payment app specified in [`related_applications`](https://developer.mozilla.org/en-US/docs/Web/Manifest/related_applications) to handle the payment (if it is available) instead of the web payment app.

  See [Serve a web app manifest](https://web.dev/setting-up-a-payment-method/#step-3-serve-a-web-app-manifest) for more details.



### Checking whether the payment app is ready to pay with



The Payment Request API's [`PaymentRequest.canMakePayment()`](paymentrequest/canmakepayment) method returns `true` if a payment app is available on the customer's device, meaning that a payment app that supports the payment method is discovered, and that the platform-specific payment app is installed, or the web-based payment app is ready to be registered.

 
```
async function checkCanMakePayment() {
  // ...

  const canMakePayment = await request.canMakePayment();
  if (!canMakePayment) {
    // Fallback to other means of payment or hide the button.
  }
}

```
 The Payment Handler API adds an additional mechanism to prepare for handling a payment. The [`canmakepayment`](serviceworkerglobalscope/canmakepayment_event) event is fired on a payment app's service worker to check whether it is ready to handle a payment. Specifically, it is fired when the merchant website calls [`new PaymentRequest()`](paymentrequest/paymentrequest). The service worker can then use the [`CanMakePaymentEvent.respondWith()`](canmakepaymentevent/respondwith) method to respond appropriately:

 
```
self.addEventListener("canmakepayment", (e) => {
  e.respondWith(
    new Promise((resolve, reject) => {
      someAppSpecificLogic()
        .then((result) => {
          resolve(result);
        })
        .catch((error) => {
          reject(error);
        });
    })
  );
});

```
 The promise returned by `respondWith()` resolves with a boolean to signal that it is ready to handle a payment request (`true`), or not (`false`).



### Handling the payment



After the [`PaymentRequest.show()`](paymentrequest/show) method is invoked, a [`paymentrequest`](serviceworkerglobalscope/paymentrequest_event) event is fired on the service worker of the payment app. This event is listened for inside the payment app's service worker to begin the next stage of the payment process.

 
```
let payment_request_event;
let resolver;
let client;

// `self` is the global object in service worker
self.addEventListener("paymentrequest", async (e) => {
  if (payment_request_event) {
    // If there's an ongoing payment transaction, reject it.
    resolver.reject();
  }
  // Preserve the event for future use
  payment_request_event = e;

  // ...
});

```
 When a `paymentrequest` event is received, the payment app can open a payment handler window by calling [`PaymentRequestEvent.openWindow()`](paymentrequestevent/openwindow). The payment handler window will present the customers with a payment app interface where they can authenticate, choose shipping address and options, and authorize the payment.

 When the payment has been handled, [`PaymentRequestEvent.respondWith()`](paymentrequestevent/respondwith) is used to pass the payment result back to the merchant website.

 See [Receive a payment request event from the merchant](https://web.dev/orchestrating-payment-transactions/#receive-payment-request-event) for more details of this stage.



### Managing payment app functionality



Once a payment app service worker is registered, you can use the service worker's [`PaymentManager`](paymentmanager) instance (accessed via [`ServiceWorkerRegistration.paymentManager`](serviceworkerregistration/paymentmanager)) to manage various aspects of the payment app's functionality.

 For example:

 
```
navigator.serviceWorker.register("serviceworker.js").then((registration) => {
  registration.paymentManager.userHint = "Card number should be 16 digits";

  registration.paymentManager
    .enableDelegations(["shippingAddress", "payerName"])
    .then(() => {
      // ...
    });

  // ...
});

```
 * [`PaymentManager.userHint`](paymentmanager/userhint) is used to provide a hint for the browser to display along with the payment app's name and icon in the Payment Handler UI.
* [`PaymentManager.enableDelegations()`](paymentmanager/enabledelegations) is used to delegate responsibility for providing various parts of the required payment information to the payment app rather than collecting it from the browser (for example, via autofill).



Interfaces
----------


 [`CanMakePaymentEvent`](canmakepaymentevent)  The event object for the [`canmakepayment`](serviceworkerglobalscope/canmakepayment_event) event, fired on a payment app's service worker when it has been successfully registered to signal that it is ready to handle payments.

  [`PaymentManager`](paymentmanager)  Used to manage various aspects of payment app functionality. Accessed via the [`ServiceWorkerRegistration.paymentManager`](serviceworkerregistration/paymentmanager) property.

  
[`PaymentRequestEvent`](paymentrequestevent)  Experimental 
  The event object for the [`paymentrequest`](serviceworkerglobalscope/paymentrequest_event) event, fired on a payment app's service worker when a payment flow has been initiated on the merchant website via the [`PaymentRequest.show()`](paymentrequest/show) method.

  
Extensions to other interfaces
------------------------------


 
[`canmakepayment`](serviceworkerglobalscope/canmakepayment_event) event  Fired on a payment app's [`ServiceWorkerGlobalScope`](serviceworkerglobalscope) when it has been successfully registered, to signal that it is ready to handle payments.

  
[`paymentrequest`](serviceworkerglobalscope/paymentrequest_event) event  Fired on a payment app's [`ServiceWorkerGlobalScope`](serviceworkerglobalscope) when a payment flow has been initiated on the merchant website via the [`PaymentRequest.show()`](paymentrequest/show) method.

  [`ServiceWorkerRegistration.paymentManager`](serviceworkerregistration/paymentmanager)  Returns a payment app's [`PaymentManager`](paymentmanager) instance, which is used to manage various payment app functionality.

  
Specifications
--------------




| Specification |
| --- |
| [Payment Handler API # the-paymentrequestevent](https://w3c.github.io/payment-handler/#the-paymentrequestevent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PaymentRequestEvent` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |
| `Payment_Handler_API` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |
| `changePaymentMethod` | 76 | 79 | No | No | 63 | No | No | 76 | No | 54 | No | 12.0 |
| `changeShippingAddress` | 80 | 80 | No | No | 67 | No | No | 80 | No | 57 | No | 13.0 |
| `changeShippingOption` | 80 | 80 | No | No | 67 | No | No | 80 | No | 57 | No | 13.0 |
| `instrumentKey` | 70–111 | 79–111 | No | No | 57–97 | No | No | 70–111 | No | 49 | No | 10.0 |
| `methodData` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |
| `modifiers` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |
| `openWindow` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |
| `paymentOptions` | 80 | 80 | No | No | 67 | No | No | 80 | No | 57 | No | 13.0 |
| `paymentRequestId` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |
| `paymentRequestOrigin` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |
| `respondWith` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |
| `shippingOptions` | 80 | 80 | No | No | 67 | No | No | 80 | No | 57 | No | 13.0 |
| `topOrigin` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |
| `total` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |


See also
--------


* [BobBucks sample payment app](https://bobbucks.dev/)
* [Web-based payment apps overview](https://web.dev/web-based-payment-apps-overview/)
* [Setting up a payment method](https://web.dev/setting-up-a-payment-method/)
* [Life of a payment transaction](https://web.dev/life-of-a-payment-transaction/)
* [Using the Payment Request API](payment_request_api/using_the_payment_request_api)
* [Payment processing concepts](payment_request_api/concepts)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Payment_Handler_API>

Payment Request API
===================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The Payment Request API provides a consistent user experience for both merchants and users. It is not a new way for paying for things; rather, it's a way for users to select their preferred way of paying for things, and make that information available to a merchant.



Payment Request concepts and usage
----------------------------------



Many problems related to online shopping-cart abandonment can be traced to checkout forms, which can be difficult and time consuming to fill out and often require multiple steps to complete. The **Payment Request API** is meant to reduce the number of steps needed to complete a payment online, potentially doing away with checkout forms. It aims to make the checkout process easier, by having payment apps store a user's details, which are then passed along to a merchant, hopefully without requiring an HTML form.

 To request a payment, a web page creates a [`PaymentRequest`](paymentrequest) object in response to a user action that initiates a payment, such as clicking a "Purchase" button. The `PaymentRequest` allows the web page to exchange information with the user agent while the user provides input to complete the transaction.

 You can find a complete guide in [Using the Payment Request API](payment_request_api/using_the_payment_request_api).

  **Note:** The API is available inside cross-origin [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe) elements only if they have had the [`allowpaymentrequest`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#allowpaymentrequest) attribute set on them.

 

Interfaces
----------


 [`PaymentAddress`](paymentaddress)  An object that contains address information; used for billing and shipping addresses, for example.

  [`PaymentRequest`](paymentrequest)  An object that provides the API for creating and managing the [user agent's](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) payment interface.

  [`PaymentRequestEvent`](paymentrequestevent)  An event delivered to a payment handler when a [`PaymentRequest`](paymentrequest) is made.

  [`PaymentRequestUpdateEvent`](paymentrequestupdateevent)  Enables the web page to update the details of the payment request in response to a user action.

  [`PaymentMethodChangeEvent`](paymentmethodchangeevent)  Represents the user changing payment instrument (e.g., switching from one payment method to another).

  [`PaymentResponse`](paymentresponse)  An object returned after the user selects a payment method and approves a payment request.

  [`MerchantValidationEvent`](merchantvalidationevent)  Represents the browser requiring the merchant (website) to validate themselves as allowed to use a particular payment handler (e.g., registered as allowed to use Apple Pay).

  
Dictionaries
------------


 `AddressErrors`  A dictionary containing strings providing descriptive explanations of any errors in any [`PaymentAddress`](paymentaddress) entries which have errors.

  [`PaymentDetailsUpdate`](paymentrequestupdateevent/updatewith#parameters)  An object describing changes that need to be made to the payment details in the event that the server needs to update information following the instantiation of the payment interface but before the user begins to interact with it.

  
Specifications
--------------




| Specification |
| --- |
| [Payment Request API 1.1 # paymentrequest-interface](https://w3c.github.io/payment-request/#paymentrequest-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PaymentRequest` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `Payment_Request_API` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `abort` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `canMakePayment` | 60 | 16 | 55 | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `id` | 60 | 16 | 55 | No | 47 | 11.1 | No | 60 | No | 44 | 11.3 | 8.0 |
| `merchantvalidation_event` | No | No | 55 | No | No | 11.1 | No | No | No | No | 11.3 | No |
| `paymentmethodchange_event` | 76 | 79 | 55 | No | 47 | 12.1 | No | 76 | No | 44 | 12.2 | 12.0 |
| `shippingAddress` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `shippingOption` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `shippingType` | 60 | 15 | 55 | No | 47 | 11.1 | No | 55 | No | 44 | 11.3 | 6.0 |
| `shippingaddresschange_event` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `shippingoptionchange_event` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `show` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |


See also
--------


* [Using the Payment Request API](payment_request_api/using_the_payment_request_api)
* [Payment processing concepts](payment_request_api/concepts)
* [Introducing the Payment Request API for Apple Pay](https://webkit.org/blog/8182/introducing-the-payment-request-api-for-apple-pay/)
* [Google Pay API PaymentRequest Tutorial](https://developers.google.com/pay/api/web/guides/paymentrequest/tutorial)
* [Samsung Pay Web Payments Integration Guide](https://developer.samsung.com/internet/android/web-payments-integration-guide.html)
* [W3C Payment Request API FAQ](https://github.com/w3c/payment-request-info/wiki/FAQ)
* Permissions Policy directive [`payment`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy/payment)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Payment_Request_API>

Performance API
===============


The Performance API is a group of standards used to measure the performance of web applications.


Concepts and usage
------------------



To ensure web applications are fast, it's important to measure and analyze various performance metrics. The Performance API provides important built-in metrics and the ability to add your own measurements to the browser's performance timeline. The performance timeline contains high precision timestamps and can be displayed in developer tools. You can also send its data to analytics end points to record performance metrics over time.

 Each performance metric is represented by a single [`PerformanceEntry`](performanceentry). A performance entry has a `name`, a `duration`, a `startTime`, and a `type`. All performance metrics extend the `PerformanceEntry` interface and qualify it further.

 Most of the performance entries are recorded for you without you having to do anything, and are then accessible either through [`Performance.getEntries()`](performance/getentries) or (preferably) through [`PerformanceObserver`](performanceobserver). For example, [`PerformanceEventTiming`](performanceeventtiming) entries are recorded for events that take longer than a set threshold. But the Performance API also enables you to define and record your own custom events, using the [`PerformanceMark`](performancemark) and [`PerformanceMeasure`](performancemeasure) interfaces.

 The main [`Performance`](performance) interface is available for each global using [`self.performance`](performance_property) and enables you to add custom performance entries, to clear performance entries, and to retrieve performance entries.

 The [`PerformanceObserver`](performanceobserver) interface enables you to listen for various types of performance entry as they are recorded.

 For more conceptual information, see the [Performance API guides](#guides) below.

  ![UML diagram of Performance APIs] 



Reference
---------



The following interfaces are present in the Performance API:

  [`EventCounts`](eventcounts)  A read-only map returned by [`performance.eventCounts`](performance/eventcounts) containing the number of events which have been dispatched per event type.

  [`LargestContentfulPaint`](largestcontentfulpaint)  Measures the render time of the largest image or text block visible within the viewport, recorded from when the page first begins to load.

  [`LayoutShift`](layoutshift)  Provides insights into the layout stability of web pages based on movements of the elements on the page.

  [`LayoutShiftAttribution`](layoutshiftattribution)  Provides debugging information about elements which have shifted.

  [`Performance`](performance)  Main interface to access performance measurements. Available to window and worker contexts using [`self.performance`](performance_property).

  [`PerformanceElementTiming`](performanceelementtiming)  Measures rendering timestamps of specific elements.

  [`PerformanceEntry`](performanceentry)  An entry on the performance timeline encapsulating a single performance metric. All performance metrics inherit from this interface.

  [`PerformanceEventTiming`](performanceeventtiming)  Measures latency of events and first input delay (FID).

  [`PerformanceLongTaskTiming`](performancelongtasktiming)  Detects long tasks that occupy rendering and block other tasks from being executed.

  [`PerformanceMark`](performancemark)  Custom marker for your own entry on the performance timeline.

  [`PerformanceMeasure`](performancemeasure)  Custom time measurement between two performance entries.

  [`PerformanceNavigationTiming`](performancenavigationtiming)  Measures document navigation events, like how much time it takes to load a document.

  [`PerformanceObserver`](performanceobserver)  Listens for new performance entries as they are recorded in the performance timeline.

  [`PerformanceObserverEntryList`](performanceobserverentrylist)  List of entries that were observed in a performance observer.

  [`PerformancePaintTiming`](performancepainttiming)  Measures render operations during web page construction.

  [`PerformanceResourceTiming`](performanceresourcetiming)  Measures network loading metrics such as redirect start and end times, fetch start, DNS lookup start and end times, response start and end times for resources such as images, scripts, fetch calls, etc.

  [`PerformanceServerTiming`](performanceservertiming)  Surfaces server metrics that are sent with the response in the [`Server-Timing`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Server-Timing) HTTP header.

  [`TaskAttributionTiming`](taskattributiontiming)  Identifies the type of task and the container that is responsible for the long task.

  

Guides
------



The following guides help you to understand key concepts of the Performance API and provide an overview about its abilities:

 * [Performance data](performance_api/performance_data): Collecting, accessing, and working with performance data.
* [High precision timing](performance_api/high_precision_timing): Measuring with high precision time and monotonic clocks.
* [Resource timing](performance_api/resource_timing): Measuring network timing for fetched resources, such as images, CSS, and JavaScript.
* [Navigation timing](performance_api/navigation_timing): Measuring navigation timing of a document.
* [User timing](performance_api/user_timing): Measuring and recording performance data custom to your application.
* Server timing
* Paint timing
* Long task timing
* Largest contentful paint
* Event timing
* Element timing
* Layout shift



How-Tos
-------



The following how-to pages provide practical information and best practices when using the Performance API:

 How to ...

 * Observe performance data
* Collect custom metrics on the client side
* Collect custom metrics on the server side
* Measure FCP
* Measure LCP
* Measure FID
* Measure TTI
* Measure TBT
* Measure CLS
* Measure TTFB
* Sync timings between window and worker contexts
* Set HTTP headers for Performance APIs to work best
* Use the Beacon API to log performance information
* Record rage clicks
* Manage buffer sizes when recording a lot of PerformanceEntry objects



Tutorials
---------



The following course helps you to take your first steps with the Performance API:

 * Instrumenting a sample application



Specifications
--------------




| Specification |
| --- |
| [Element Timing API](https://wicg.github.io/element-timing/)  |
| [Event Timing API](https://w3c.github.io/event-timing/)  |
| [High Resolution Time](https://w3c.github.io/hr-time/)  |
| [Largest Contentful Paint](https://w3c.github.io/largest-contentful-paint/)  |
| [Layout Instability](https://wicg.github.io/layout-instability/)  |
| [Long Tasks API 1](https://w3c.github.io/longtasks/)  |
| [Navigation Timing Level 2](https://w3c.github.io/navigation-timing/)  |
| [Paint Timing 1](https://w3c.github.io/paint-timing/)  |
| [Performance Timeline](https://w3c.github.io/performance-timeline/)  |
| [Resource Timing](https://w3c.github.io/resource-timing/)  |
| [Server Timing](https://w3c.github.io/server-timing/)  |
| [User Timing](https://w3c.github.io/user-timing/)  |


See also
--------


* [Web performance](https://developer.mozilla.org/en-US/docs/Web/Performance)
* [Learn: Web performance](https://developer.mozilla.org/en-US/docs/Learn/Performance)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Performance_API>

Web Periodic Background Synchronization API
===========================================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The Web Periodic Background Synchronization API provides a way to register tasks to be run in a [`service worker`](service_worker_api) at periodic intervals with network connectivity. These tasks are referred to as periodic background sync requests.



Web Periodic Background Synchronization Concepts and Usage
----------------------------------------------------------



The Periodic Background Sync API allows web applications to alert their service worker to make any updates, at a periodic time interval. Uses may include fetching latest content whilst a device is connected to Wi-Fi, or allowing background updates to an application.

 The minimum time interval is set when the API is invoked; however the user agent might also take into account other factors which affect when the service worker receives the event. For instance previous website engagement, or connection to a known network.

 The [`PeriodicSyncManager`](periodicsyncmanager) interface is available through [`ServiceWorkerRegistration.periodicSync`](serviceworkerregistration/periodicsync). A unique tag identifier is set to 'name' the sync event, which can then be listened for within the [`ServiceWorker`](serviceworker) script. Once the event is received you can then run any functionality available, such as updating caches or fetching new resources.

 As this API relies on service workers, functionality provided by this API is only available in a secure context.

  **Note:** At the time of writing, the Web Periodic Background Synchronization API is only available through an installed [Progressive Web App](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps)

 

Web Periodic Background Synchronization Interfaces
--------------------------------------------------


 [`PeriodicSyncManager`](periodicsyncmanager)  Registers tasks to be run in a service worker at periodic intervals with network connectivity. These tasks are referred to as periodic background sync requests.

  [`PeriodicSyncEvent`](periodicsyncevent)  Represents a synchronization event, sent to the [`global scope`](serviceworkerglobalscope) of a [`ServiceWorker`](serviceworker). It provides a way to run tasks in the service worker with network connectivity.

  
Service Worker Additions
------------------------



The following additions to the [`Service Worker API`](service_worker_api) are specified in the Periodic Background Sync specification to provide an entry point for using Periodic Background Sync.

  
[`ServiceWorkerRegistration.periodicSync`](serviceworkerregistration/periodicsync) Read only 
  Returns a reference to the [`PeriodicSyncManager`](periodicsyncmanager) interface for registering tasks to run at specific intervals.

  [`onperiodicsync`](serviceworkerglobalscope/periodicsync_event)  An event handler fired whenever a [`periodicsync`](serviceworkerglobalscope/periodicsync_event) event occurs. This happens at timed intervals, that are specified when registering a [`PeriodicSyncManager`](periodicsyncmanager).

  

Examples
--------


The following examples show how to use the interface.


### Requesting a Periodic Background Sync



The following asynchronous function registers a periodic background sync at a minimum interval of one day from a browsing context:

 
```
async function registerPeriodicNewsCheck() {
  const registration = await navigator.serviceWorker.ready;
  try {
    await registration.periodicSync.register("get-latest-news", {
      minInterval: 24 \* 60 \* 60 \* 1000,
    });
  } catch {
    console.log("Periodic Sync could not be registered!");
  }
}

```


### Verifying a Background Periodic Sync by Tag



This code checks to see if a Periodic Background Sync task with a given tag is registered.

 
```
navigator.serviceWorker.ready.then((registration) => {
  registration.periodicSync.getTags().then((tags) => {
    if (tags.includes("get-latest-news")) skipDownloadingLatestNewsOnPageLoad();
  });
});

```


### Removing a Periodic Background Sync Task



The following code removes a Periodic Background Sync task to stop articles syncing in the background.

 
```
navigator.serviceWorker.ready.then((registration) => {
  registration.periodicSync.unregister("get-latest-news");
});

```


### Listening for a Periodic Background Sync within a Service Worker



The following example shows how to respond to a periodic sync event in the service worker.

 
```
self.addEventListener("periodicsync", (event) => {
  if (event.tag === "get-latest-news") {
    event.waitUntil(fetchAndCacheLatestNews());
  }
});

```


Specifications
--------------




| Specification |
| --- |
| [Web Periodic Background Synchronization # periodicsyncmanager-interface](https://wicg.github.io/periodic-background-sync/#periodicsyncmanager-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Web_Periodic_Background_Synchronization_API` | 80 | 80 | No | No | 67 | No | No | 80 | No | 57 | No | 13.0 |
| `getTags` | 80 | 80 | No | No | 67 | No | No | 80 | No | 57 | No | 13.0 |
| `register` | 80 | 80 | No | No | 67 | No | No | 80 | No | 57 | No | 13.0 |
| `unregister` | 80 | 80 | No | No | 67 | No | No | 80 | No | 57 | No | 13.0 |


See also
--------


* [An article on using Periodic Background Sync](https://web.dev/periodic-background-sync/)
* [A Periodic Background Sync demo app](https://webplatformapis.com/periodic_sync/periodicSync_improved.html)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Web_Periodic_Background_Synchronization_API>

Permissions API
===============



The **Permissions API** provides a consistent programmatic way to query the status of API permissions attributed to the current context. For example, the Permissions API can be used to determine if permission to access a particular API has been granted or denied.

  **Note:** This feature is available in [Web Workers](web_workers_api) (although not current versions of Firefox, as [WorkerNavigator.permissions](workernavigator/permissions) is not implemented).

 

Concepts and usage
------------------



Historically different APIs handle their own permissions inconsistently — for example the [Notifications API](notifications_api) allows for explicit checking of permission status and requesting permission, whereas the [Geolocation API](geolocation) doesn't (which causes problems if the user denied the initial permission request). The Permissions API provides the tools to allow developers to implement a better user experience as far as permissions are concerned.

 The `permissions` property has been made available on the [`Navigator`](navigator) object, both in the standard browsing context and the worker context ([`WorkerNavigator`](workernavigator) — so permission checks are available inside workers), and returns a [`Permissions`](permissions) object that provides access to the Permissions API functionality.

 Once you have this object you can then perform permission-related tasks, for example querying a permission using the [`Permissions.query()`](permissions/query) method to return a promise that resolves with the [`PermissionStatus`](permissionstatus) for a specific API.

 Not all APIs' permission statuses can be queried using the Permissions API. Notable APIs that are Permissions-aware include:

 * [Clipboard API](clipboard_api)
* [Notifications API](notifications_api)
* [Push API](push_api)
* Web MIDI API

 More APIs will gain Permissions API support over time.



Examples
--------



We have made a simple example available called Location Finder. You can [run the example live](https://chrisdavidmills.github.io/location-finder-permissions-api/), or [view the source code on GitHub](https://github.com/chrisdavidmills/location-finder-permissions-api/tree/gh-pages).

 Read more about how it works in our article [Using the Permissions API](permissions_api/using_the_permissions_api).



Interfaces
----------


 
[`Navigator.permissions`](navigator/permissions) and [`WorkerNavigator.permissions`](workernavigator/permissions) Read only 
  Provides access to the [`Permissions`](permissions) object from the main context and worker context respectively.

  [`Permissions`](permissions)  Provides the core Permission API functionality, such as methods for querying and revoking permissions.

  [`PermissionStatus`](permissionstatus)  Provides access to the current status of a permission, and an event handler to respond to changes in permission status.

  
Specifications
--------------




| Specification |
| --- |
| [Permissions # permissions-interface](https://w3c.github.io/permissions/#permissions-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Permissions_API` | 43 | 79 | 46 | No | 30 | 16 | NoSee [bug 490120](https://crbug.com/490120). | 43 | 46 | 30 | 16 | 4.0 |
| `permission_accelerometer` | 62 | 79 | No | No | 49 | No | No | 62 | No | 46 | No | 8.0 |
| `permission_accessibility-events` | 62 | 79 | No | No | 49 | No | No | 62 | No | 46 | No | 8.0 |
| `permission_ambient-light-sensor` | 62 | 79 | No | No | 49 | No | No | 62 | No | 46 | No | 8.0 |
| `permission_background-sync` | 62 | 79 | No | No | 49 | No | No | 62 | No | 46 | No | 8.0 |
| `permission_camera` | 64 | 79 | No | No | 51 | 16 | No | 64 | No | 47 | 16 | 9.0 |
| `permission_clipboard-read` | 64 | 79 | No | No | 51 | No | No | 64 | No | 47 | No | 9.0 |
| `permission_clipboard-write` | 64 | 79 | No | No | 51 | No | No | 64 | No | 47 | No | 9.0 |
| `permission_geolocation` | 43 | 79 | 46 | No | 30 | 16 | No | 43 | 46 | 30 | 16 | 4.0 |
| `permission_gyroscope` | 51 | 79 | No | No | 38 | No | No | 51 | No | 41 | No | 5.0 |
| `permission_local-fonts` | 103 | 103 | No | No | No | No | No | No | No | No | No | No |
| `permission_magnetometer` | 62 | 79 | No | No | 49 | No | No | 62 | No | 46 | No | 8.0 |
| `permission_microphone` | 64 | 79 | No | No | 51 | 16 | No | 64 | No | 47 | 16 | 9.0 |
| `permission_midi` | 43 | 79 | 110 | No | 30 | No | No | 43 | 110 | 30 | No | 4.0 |
| `permission_notifications` | 43 | 79 | 46 | No | 30 | No | No | 43 | 46 | 30 | No | 4.0 |
| `permission_payment-handler` | 66 | 79 | No | No | 53 | No | No | 66 | No | 47 | No | 9.0 |
| `permission_persistent-storage` | 71 | 79 | 53 | No | 58 | No | No | 71 | 53 | 50 | No | 10.0 |
| `permission_push` | 43 | 79 | 46 | No | 30 | No | No | 43 | 46 | 30 | No | 4.0 |
| `permission_speaker-selection` | No | No | 92 | No | No | No | No | No | 92 | No | No | No |
| `query` | 43 | 79 | 46 | No | 30 | 16 | No | 43 | 46 | 30 | 16 | 4.0 |
| `request` | 46 | 79 | No | No | 33 | No | No | 46 | No | No | No | No |
| `requestAll` | 48 | 79 | No | No | 35 | No | No | 48 | No | No | No | No |
| `revoke` | 46 | 79 | 5147–51 | No | 33 | No | No | 46 | 47–51 | No | No | No |


See also
--------


* [Using the Permissions API](permissions_api/using_the_permissions_api)
* [Using the Permissions API to Detect How Often Users Allow or Deny Camera Access](https://blog.addpipe.com/using-permissions-api-to-detect-getusermedia-responses/)
* [`Notification.permission`](notification/permission)
* [Privacy, permissions, and information security](https://developer.mozilla.org/en-US/docs/Web/Privacy)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API>

Picture-in-Picture API
======================


The **Picture-in-Picture API** allow websites to create a floating video window always on top of other windows so that users may continue consuming media while they interact with other content sites, or applications on their device.


Interfaces
----------


 [`PictureInPictureWindow`](pictureinpicturewindow)  Represents the floating video window; contains [`width`](pictureinpicturewindow/width) and [`height`](pictureinpicturewindow/height) properties, and an [`onresize`](pictureinpicturewindow/resize_event) event handler property.

  
Instance methods
----------------


The Picture-in-Picture API adds methods to the [`HTMLVideoElement`](htmlvideoelement) and [`Document`](document) interfaces to allow toggling of the floating video window.


### Instance methods on the HTMLVideoElement interface


 [`HTMLVideoElement.requestPictureInPicture()`](htmlvideoelement/requestpictureinpicture)  Requests that the user agent enters the video into picture-in-picture mode

  
### Instance methods on the Document interface


 [`Document.exitPictureInPicture()`](document/exitpictureinpicture)  Requests that the user agent returns the element in picture-in-picture mode back into its original box.

  
Instance properties
-------------------


The Picture-in-Picture API augments the [`HTMLVideoElement`](htmlvideoelement), [`Document`](document), and [`ShadowRoot`](shadowroot) interfaces with properties that can be used to determine if the floating video window mode is supported and available, if picture-in-picture mode is currently active, and which video is floating.


### Instance properties on the HTMLVideoElement interface


 [`HTMLVideoElement.disablePictureInPicture`](htmlvideoelement/disablepictureinpicture)  The `disablePictureInPicture` property will provide a hint to the user agent to not suggest the picture-in-picture to users or to request it automatically.

  
### Instance properties on the Document interface


 [`Document.pictureInPictureEnabled`](document/pictureinpictureenabled)  The `pictureInPictureEnabled` property tells you whether or not it is possible to engage picture-in-picture mode. This is `false` if picture-in-picture mode is not available for any reason (e.g. the [`"picture-in-picture"` feature](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy/picture-in-picture) has been disallowed, or picture-in-picture mode is not supported).

  
### Instance properties on the Document or ShadowRoot interfaces


 
[`Document.pictureInPictureElement`](document/pictureinpictureelement) / [`ShadowRoot.pictureInPictureElement`](shadowroot/pictureinpictureelement)
  The `pictureInPictureElement` property tells you which [`Element`](element) is currently being displayed in the floating window (or in the shadow DOM). If this is `null`, the document (or shadow DOM) has no node currently in picture-in-picture mode.

  
Events
------



*The Picture-in-Picture API defines three events, which can be used to detect when picture-in-picture mode is toggled and when the floating video window is resized.*

  [`enterpictureinpicture`](htmlvideoelement/enterpictureinpicture_event)  Sent to a [`HTMLVideoElement`](htmlvideoelement) when it enters picture-in-picture mode.

  [`leavepictureinpicture`](htmlvideoelement/leavepictureinpicture_event)  Sent to a [`HTMLVideoElement`](htmlvideoelement) when it leaves picture-in-picture mode.

  [`resize`](pictureinpicturewindow/resize_event)  Sent to a [`PictureInPictureWindow`](pictureinpicturewindow) when it changes size.

  

Adding Controls
---------------


If media action handlers have been set via the [Media Session API](media_session_api), then appropriate controls for those actions will be added by the browser to the picture-in-picture overlay. For example, if a `"nexttrack"` action has been set, then a skip button might be displayed in the picture-in-picture view. There is no support for adding custom HTML buttons or controls.


Controlling styling
-------------------


The [`:picture-in-picture`](https://developer.mozilla.org/en-US/docs/Web/CSS/:picture-in-picture) [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) [pseudo-class](https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes) matches the video element currently in picture-in-picture mode, allowing you to configure your stylesheets to automatically adjust the size, style, or layout of content when a video switches back and forth between picture-in-picture and traditional presentation modes.


Controlling access
------------------


The availability of picture-in-picture mode can be controlled using [Permissions Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy). The fullscreen mode feature is identified by the string `"picture-in-picture"`, with a default allowlist value of `"self"`, meaning that picture-in-picture mode is permitted in top-level document contexts, as well as to nested browsing contexts loaded from the same origin as the top-most document.


Examples
--------



In this example, a video is presented in a web page. Clicking the button below lets the user toggle the floating video window.




### Toggling picture-in-picture mode



This code is called by a click handler when the user clicks the "Toggle Picture-in-Picture" button:

 
```
function togglePictureInPicture() {
  if (document.pictureInPictureElement) {
    document.exitPictureInPicture();
  } else if (document.pictureInPictureEnabled) {
    video.requestPictureInPicture();
  }
}

```
 This block starts by looking at the value of the [`document`](document)'s `pictureInPictureElement` attribute.

 If the value is not `null`, it's the element that's currently in picture-in-picture mode, that is in a floating window. We call [`document.exitPictureInPicture()`](document/exitpictureinpicture) to bring the video back into its initial box.

 If the value is `null`, no video is in the floating window. So we can request a video to enter the picture-in-picture mode. We do it by calling [`HTMLVideoElement.requestPictureInPicture()`](htmlvideoelement/requestpictureinpicture) on the [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) element.



Specifications
--------------




| Specification |
| --- |
| [Picture-in-Picture # interface-picture-in-picture-window](https://w3c.github.io/picture-in-picture/#interface-picture-in-picture-window) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Picture-in-Picture_API` | 69 | 79 | No | No | 56 | 13.1 | No | 105 | No | 72 | 13.4 | 20.0 |
| `height` | 69 | 79 | No | No | 56 | 13.1 | No | 105 | No | 72 | 13.4 | 20.0 |
| `resize_event` | 69 | 79 | No | No | 56 | 13.1 | No | 105 | No | 72 | 13.4 | 20.0 |
| `width` | 69 | 79 | No | No | 56 | 13.1 | No | 105 | No | 72 | 13.4 | 20.0 |


See also
--------


* [`HTMLVideoElement.requestPictureInPicture()`](htmlvideoelement/requestpictureinpicture)
* [`HTMLVideoElement.disablePictureInPicture`](htmlvideoelement/disablepictureinpicture)
* [`Document.pictureInPictureEnabled`](document/pictureinpictureenabled)
* [`Document.exitPictureInPicture()`](document/exitpictureinpicture)
* [`Document.pictureInPictureElement`](document/pictureinpictureelement)
* [`:picture-in-picture`](https://developer.mozilla.org/en-US/docs/Web/CSS/:picture-in-picture)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Picture-in-Picture_API>

Pointer Lock API
================



The **Pointer Lock API** (formerly called *Mouse Lock API*) provides input methods based on the movement of the mouse over time (i.e., deltas), not just the absolute position of the mouse cursor in the viewport. It gives you access to raw mouse movement, locks the target of mouse events to a single element, eliminates limits on how far mouse movement can go in a single direction, and removes the cursor from view. It is ideal for first-person 3D games, for example.

 More than that, the API is useful for any applications that require significant mouse input to control movements, rotate objects, and change entries, for example allowing users to control the viewing angle by moving the mouse around without any button clicking. The buttons are then freed up for other actions. Other examples include apps for viewing maps or satellite imagery.

 Pointer lock lets you access mouse events even when the cursor goes past the boundary of the browser or screen. For example, your users can continue to rotate or manipulate a 3D model by moving the mouse without end. Without Pointer lock, the rotation or manipulation stops the moment the pointer reaches the edge of the browser or screen. Game players can now click buttons and swipe the mouse cursor back and forth without worrying about leaving the game play area and accidentally clicking another application that would take mouse focus away from the game.



Basic concepts
--------------



Pointer lock is related to [mouse capture](element/setcapture). Mouse capture provides continued delivery of events to a target element while a mouse is being dragged, but it stops when the mouse button is released. Pointer lock is different from mouse capture in the following ways:

 * It is persistent: Pointer lock does not release the mouse until an explicit API call is made or the user uses a specific release gesture.
* It is not limited by browser or screen boundaries.
* It continues to send events regardless of mouse button state.
* It hides the cursor.



Method/properties overview
--------------------------


This section provides a brief description of each property and method related to the pointer lock specification.


### requestPointerLock()



The Pointer lock API, similar to the [Fullscreen API](fullscreen_api), extends DOM elements by adding a new method, [`requestPointerLock()`](element/requestpointerlock). The following example requests pointer lock on a [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element:

 
```
canvas.addEventListener("click", async () => {
  await canvas.requestPointerLock();
});

```
  **Note:** If a user has exited pointer lock via the [default unlock gesture](https://w3c.github.io/pointerlock/#dfn-default-unlock-gesture), or pointer lock has not previously been entered for this document, an event generated as a result of an [engagement gesture](https://w3c.github.io/pointerlock/#dfn-engagement-gesture) must be received by the document before [`requestPointerLock`](https://w3c.github.io/pointerlock/#dom-element-requestpointerlock) will succeed. (from <https://w3c.github.io/pointerlock/#extensions-to-the-element-interface>)

  Operating systems enable mouse acceleration by default, which is useful when you sometimes want slow precise movement (think about you might use a graphics package), but also want to move great distances with a faster mouse movement (think about scrolling, and selecting several files). For some first-person perspective games however, raw mouse input data is preferred for controlling camera rotation — where the same distance movement, fast or slow, results in the same rotation. This results in a better gaming experience and higher accuracy, according to professional gamers.

 To disable OS-level mouse acceleration and access raw mouse input, you can set the `unadjustedMovement` to `true`:

 
```
canvas.addEventListener("click", async () => {
  await canvas.requestPointerLock({
    unadjustedMovement: true,
  });
});

```


Handling promise and non-promise versions of requestPointerLock()
-----------------------------------------------------------------



The above code snippet will still work in browsers that do not support the promise-based version of `requestPointerLock()` or the `unadjustedMovement` option — the [`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) operator is permitted in front of a function that does not return a promise, and the options object will just be ignored in non-supporting browsers.

 However, this could be confusing, and has other potential side-effects (for example, trying to use `requestPointerLock().then()` would throw an error in non-supporting browsers), so you may want to handle this explicitly using code along the following lines:

 
```
function requestPointerLockWithUnadjustedMovement() {
  const promise = myTargetElement.requestPointerLock({
    unadjustedMovement: true,
  });

  if (!promise) {
    console.log("disabling mouse acceleration is not supported");
    return;
  }

  return promise
    .then(() => console.log("pointer is locked"))
    .catch((error) => {
      if (error.name === "NotSupportedError") {
        // Some platforms may not support unadjusted movement.
        // You can request again a regular pointer lock.
        return myTargetElement.requestPointerLock();
      }
    });
}

```


### pointerLockElement and exitPointerLock()



The Pointer lock API also extends the [`Document`](document) interface, adding a new property and a new method:

 * [`pointerLockElement`](document/pointerlockelement) is used for accessing the currently locked element (if any).
* [`exitPointerLock()`](document/exitpointerlock) is used to exit the pointer lock.

 The [`pointerLockElement`](document/pointerlockelement) property is useful for determining if any element is currently pointer locked (e.g., for doing a boolean check) and also for obtaining a reference to the locked element, if any.

 Here is an example of using `pointerLockElement`:

 
```
if (document.pointerLockElement === canvas) {
  console.log("The pointer lock status is now locked");
} else {
  console.log("The pointer lock status is now unlocked");
}

```
 The [`Document.exitPointerLock()`](document/exitpointerlock) method is used to exit pointer lock, and like [`requestPointerLock`](element/requestpointerlock), works asynchronously using the [`pointerlockchange`](document/pointerlockchange_event) and [`pointerlockerror`](document/pointerlockerror_event) events, which you'll see more about below.

 
```
document.exitPointerLock();

```


pointerlockchange event
-----------------------



When the Pointer lock state changes—for example, when calling [`requestPointerLock()`](element/requestpointerlock) or [`exitPointerLock()`](document/exitpointerlock), the user pressing the ESC key, etc.—the [`pointerlockchange`](document/pointerlockchange_event) event is dispatched to the `document`. This is a simple event containing no extra data.

 
```
document.addEventListener("pointerlockchange", lockChangeAlert, false);

function lockChangeAlert() {
  if (document.pointerLockElement === canvas) {
    console.log("The pointer lock status is now locked");
    // Do something useful in response
  } else {
    console.log("The pointer lock status is now unlocked");
    // Do something useful in response
  }
}

```


pointerlockerror event
----------------------



When there is an error caused by calling [`requestPointerLock()`](element/requestpointerlock) or [`exitPointerLock()`](document/exitpointerlock), the [`pointerlockerror`](document/pointerlockerror_event) event is dispatched to the `document`. This is a simple event containing no extra data.

 
```
document.addEventListener("pointerlockerror", lockError, false);

function lockError(e) {
  alert("Pointer lock failed");
}

```


Extensions to mouse events
--------------------------


The Pointer lock API extends the normal [`MouseEvent`](mouseevent) interface with movement attributes. Two new attributes to mouse events—[`movementX`](mouseevent/movementx) and [`movementY`](mouseevent/movementy)—provide the change in mouse positions. The values of the parameters are the same as the difference between the values of [`MouseEvent`](mouseevent) properties, [`screenX`](mouseevent/screenx) and [`screenY`](mouseevent/screeny), which are stored in two subsequent [`mousemove`](element/mousemove_event) events, `eNow` and `ePrevious`. In other words, the Pointer lock parameter `movementX = eNow.screenX - ePrevious.screenX`.


### Locked state


When Pointer lock is enabled, the standard [`MouseEvent`](mouseevent) properties [`clientX`](mouseevent/clientx), [`clientY`](mouseevent/clienty), [`screenX`](mouseevent/screenx), and [`screenY`](mouseevent/screeny) are held constant, as if the mouse is not moving. The [`movementX`](mouseevent/movementx) and [`movementY`](mouseevent/movementy) properties continue to provide the mouse's change in position. There is no limit to [`movementX`](mouseevent/movementx) and [`movementY`](mouseevent/movementy) values if the mouse is continuously moving in a single direction. The concept of the mouse cursor does not exist and the cursor cannot move off the window or be clamped by a screen edge.


### Unlocked state



The parameters [`movementX`](mouseevent/movementx) and [`movementY`](mouseevent/movementy) are valid regardless of the mouse lock state, and are available even when unlocked for convenience.

 When the mouse is unlocked, the system cursor can exit and re-enter the browser window. If that happens, [`movementX`](mouseevent/movementx) and [`movementY`](mouseevent/movementy) could be set to zero.



Simple example walkthrough
--------------------------



We've written a [pointer lock demo](https://mdn.github.io/dom-examples/pointer-lock/) ([see source code](https://github.com/mdn/dom-examples/tree/main/pointer-lock)) to show you how to use it to set up a simple control system. This demo uses JavaScript to draw a ball on top of an [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element. When you click the canvas, pointer lock is then used to remove the mouse pointer and allow you to move the ball directly using the mouse. Let's see how this works.

 We set initial x and y positions on the canvas:

 
```
let x = 50;
let y = 50;

```
 Next we set up an event listener to run the `requestPointerLock()` method on the canvas when it is clicked, which initiates pointer lock. The `document.pointerLockElement` check is to see if there is already an active pointer lock — we don't want to keep calling `requestPointerLock()` on the canvas every time we click inside it if we already have pointer lock.

 
```
canvas.addEventListener("click", async () => {
  if (!document.pointerLockElement) {
    await canvas.requestPointerLock({
      unadjustedMovement: true,
    });
  }
});

```
  **Note:** The above snippet works in browsers that don't support the promise version of `requestPointerLock()`. See [Handling promise and non-promise versions of requestPointerLock()](#handling_promise_and_non-promise_versions_of_requestpointerlock) for an explanation.

  Now for the dedicated pointer lock event listener: `pointerlockchange`. When this occurs, we run a function called `lockChangeAlert()` to handle the change.

 
```
document.addEventListener("pointerlockchange", lockChangeAlert, false);

```
 This function checks the `pointerLockElement` property to see if it is our canvas. If so, it attached an event listener to handle the mouse movements with the `updatePosition()` function. If not, it removes the event listener again.

 
```
function lockChangeAlert() {
  if (document.pointerLockElement === canvas) {
    console.log("The pointer lock status is now locked");
    document.addEventListener("mousemove", updatePosition, false);
  } else {
    console.log("The pointer lock status is now unlocked");
    document.removeEventListener("mousemove", updatePosition, false);
  }
}

```
 The `updatePosition()` function updates the position of the ball on the canvas (`x` and `y`), and also includes `if ()` statements to check whether the ball has gone off the edges of the canvas. If so, it makes the ball wrap around to the opposite edge. It also includes a check whether a [`requestAnimationFrame()`](window/requestanimationframe) call has previously been made, and if so, calls it again as required, and calls the `canvasDraw()` function that updates the canvas scene. A tracker is also set up to write out the X and Y values to the screen, for reference.

 
```
const tracker = document.getElementById("tracker");

let animation;
function updatePosition(e) {
  x += e.movementX;
  y += e.movementY;
  if (x > canvas.width + RADIUS) {
    x = -RADIUS;
  }
  if (y > canvas.height + RADIUS) {
    y = -RADIUS;
  }
  if (x < -RADIUS) {
    x = canvas.width + RADIUS;
  }
  if (y < -RADIUS) {
    y = canvas.height + RADIUS;
  }
  tracker.textContent = `X position: ${x}, Y position: ${y}`;

  if (!animation) {
    animation = requestAnimationFrame(() => {
      animation = null;
      canvasDraw();
    });
  }
}

```
 The `canvasDraw()` function draws the ball in the current `x` and `y` positions:

 
```
function canvasDraw() {
  ctx.fillStyle = "black";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "#f00";
  ctx.beginPath();
  ctx.arc(x, y, RADIUS, 0, degToRad(360), true);
  ctx.fill();
}

```


IFrame limitations
------------------



Pointer lock can only lock one [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe) at a time. If you lock one `<iframe>`, you can't lock another one and transfer the target to it; pointer lock will error out. To avoid this limitation, first unlock the locked `<iframe>`, and then lock the other.

 While `<iframe>` work by default, "sandboxed" `<iframe>`s block Pointer lock. To avoid this limitation, use `<iframe sandbox="allow-pointer-lock">`.



Specifications
--------------




| Specification |
| --- |
| [Pointer Lock 2.0 # dom-element-requestpointerlock](https://w3c.github.io/pointerlock/#dom-element-requestpointerlock) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Pointer_Lock_API` | 37From version 92, returns a promise instead of `undefined`. The behavior reflects [a proposed specification change](https://github.com/w3c/pointerlock/pull/49).22–38 | 13From version 92, returns a promise instead of `undefined`. The behavior reflects [a proposed specification change](https://github.com/w3c/pointerlock/pull/49). | 5014–50 | No | 24From version 78, returns a promise instead of `undefined`. The behavior reflects [a proposed specification change](https://github.com/w3c/pointerlock/pull/49).15–25 | 10.1 | 37From version 92, returns a promise instead of `undefined`. The behavior reflects [a proposed specification change](https://github.com/w3c/pointerlock/pull/49).4.4–38 | 37From version 92, returns a promise instead of `undefined`. The behavior reflects [a proposed specification change](https://github.com/w3c/pointerlock/pull/49).25–38 | 5014–50 | 24From version 65, returns a promise instead of `undefined`. The behavior reflects [a proposed specification change](https://github.com/w3c/pointerlock/pull/49).14–25 | No | 3.0From version 16, returns a promise instead of `undefined`. The behavior reflects [a proposed specification change](https://github.com/w3c/pointerlock/pull/49).1.5–3.0 |
| `options_unadjustedMovement_parameter` | 88Supported on macOS Catalina 10.15.1+, Windows, and ChromeOS. Not yet supported on Linux. | 88Supported on macOS Catalina 10.15.1+, Windows, and EdgeOS. Not yet supported on Linux. | No | No | 74Supported on macOS Catalina 10.15.1+, Windows, and OperaOS. Not yet supported on Linux. | No | 88Supported on macOS Catalina 10.15.1+, Windows, and ChromeOS. Not yet supported on Linux. | 88Supported on macOS Catalina 10.15.1+, Windows, and ChromeOS. Not yet supported on Linux. | No | 63Supported on macOS Catalina 10.15.1+, Windows, and OperaOS. Not yet supported on Linux. | No | 15.0Supported on macOS Catalina 10.15.1+, Windows, and Samsung InternetOS. Not yet supported on Linux. |


See also
--------


* [`MouseEvent`](mouseevent)
* [`Element.requestPointerLock()`](element/requestpointerlock)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API>

Presentation API
================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The Presentation API lets a [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) (such as a Web browser) effectively display web content through large presentation devices such as projectors and network-connected televisions. Supported types of multimedia devices include both displays which are wired using HDMI, DVI, or the like, or wireless, using [DLNA](https://www.dlna.org/), [Chromecast](https://developers.google.com/cast/), [AirPlay](https://developer.apple.com/airplay/), or [Miracast](https://www.wi-fi.org/discover-wi-fi/miracast).

  ![1-UA mode loaded the Controlling and Presenting pages together before outputting to displays. 2-UA mode loaded them separately using the Presentation Control Protocol.] 

 In general, a web page uses the Presentation Controller API to specify the web content to be rendered on presentation device and initiate the presentation session. With Presentation Receiver API, the presenting web content obtains the session status. With providing both the controller page and the receiver one with a messaged-based channel, a Web developer can implement the interaction between these two pages.

 Depending on the connection mechanism provided by the presentation device, any controller- and receiver page can be rendered by the same user agent, or by separated user agents.

 * For 1-UA mode devices, both pages are loaded by the same user agent. However, rendering result of the receiver page will be sent to the presentation device via supported remote rendering protocol.
* For 2-UAs mode device, the receiver page is loaded directly on the presentation device. Controlling user agent communicates with presentation device via supported presentation control protocol, to control the presentation session and to transmit the message between two pages.



Interfaces
----------


 [`Presentation`](presentation)  In controlling browsing context, the `Presentation` interface provides a mechanism to override the browser default behavior of launching presentation to external screen. In receiving browsing context, `Presentation` interface provides the access to the available presentation connections.

  [`PresentationRequest`](presentationrequest)  Initiates or reconnects to a presentation made by a controlling browsing context.

  [`PresentationAvailability`](presentationavailability)  A [PresentationAvailability](presentationavailability) object is associated with available presentation displays and represents the *presentation display availability* for a presentation request.

  [`PresentationConnectionAvailableEvent`](presentationconnectionavailableevent)  The `PresentationConnectionAvailableEvent` is fired on a [`PresentationRequest`](presentationrequest) when a connection associated with the object is created.

  [`PresentationConnection`](presentationconnection)  Each presentation connection is represented by a [PresentationConnection](presentationconnection) object.

  [`PresentationConnectionCloseEvent`](presentationconnectioncloseevent)  A `PresentationConnectionCloseEvent` is fired when a presentation connection enters a `closed` state.

  [`PresentationReceiver`](presentationreceiver)  The [PresentationReceiver](presentationreceiver) allows a receiving browsing context to access the controlling browsing contexts and communicate with them.

  [`PresentationConnectionList`](presentationconnectionlist)  `PresentationConnectionList` represents the collection of non-terminated presentation connections. It is also a monitor for the event of new available presentation connection.

  
Example
-------


Example codes below highlight the usage of main features of the Presentation API: `controller.html` implements the controller and `presentation.html` implements the presentation. Both pages are served from the domain `http://example.org` (`http://example.org/controller.html` and `http://example.org/presentation.html`). These examples assume that the controlling page is managing one presentation at a time. Please refer to the comments in the code examples for further details.


### Monitor availability of presentation displays



In `controller.html`:

 
```
<button id="presentBtn" style="display: none;">Present</button>
<script>
 // The Present button is visible if at least one presentation display is available
 const presentBtn = document.getElementById("presentBtn");

 // It is also possible to use relative presentation URL e.g. "presentation.html"
 const presUrls = [
 "http://example.com/presentation.html",
 "http://example.net/alternate.html",
 ];

 // Show or hide present button depending on display availability
 const handleAvailabilityChange = (available) => {
 presentBtn.style.display = available ? "inline" : "none";
 };

 // Promise is resolved as soon as the presentation display availability is known.
 const request = new PresentationRequest(presUrls);
 request
 .getAvailability()
 .then((availability) => {
 // availability.value may be kept up-to-date by the controlling UA as long
 // as the availability object is alive. It is advised for the web developers
 // to discard the object as soon as it's not needed.
 handleAvailabilityChange(availability.value);
 availability.onchange = () => {
 handleAvailabilityChange(availability.value);
 };
 })
 .catch(() => {
 // Availability monitoring is not supported by the platform, so discovery of
 // presentation displays will happen only after request.start() is called.
 // Pretend the devices are available for simplicity; or, one could implement
 // a third state for the button.
 handleAvailabilityChange(true);
 });
</script>

```


### Starting a new presentation



In `controller.html`:

 
```
<script>
 presentBtn.onclick = () => {
 // Start new presentation.
 request
 .start()
 // The connection to the presentation will be passed to setConnection on success.
 .then(setConnection);
 // Otherwise, the user canceled the selection dialog or no screens were found.
 };
</script>

```


### Reconnect to a presentation



In the `controller.html` file:

 
```
<button id="reconnectBtn" style="display: none;">Reconnect</button>
<script>
 const reconnect = () => {
 // read presId from localStorage if exists
 const presId = localStorage["presId"];
 // presId is mandatory when reconnecting to a presentation.
 if (presId) {
 request
 .reconnect(presId)
 // The new connection to the presentation will be passed to
 // setConnection on success.
 .then(setConnection);
 // No connection found for presUrl and presId, or an error occurred.
 }
 };
 // On navigation of the controller, reconnect automatically.
 document.addEventListener("DOMContentLoaded", reconnect);
 // Or allow manual reconnection.
 reconnectBtn.onclick = reconnect;
</script>

```


### Presentation initiation by the controlling UA



In the `controller.html` file:

 
```
<script>
 navigator.presentation.defaultRequest = new PresentationRequest(presUrls);
 navigator.presentation.defaultRequest.onconnectionavailable = (evt) => {
 setConnection(evt.connection);
 };
</script>

```
 Setting `presentation.defaultRequest` allows the page to specify the `PresentationRequest` to use when the controlling UA initiates a presentation.



### Monitor connection's state and exchange data



In `controller.html`:

 
```
<button id="disconnectBtn" style="display: none;">Disconnect</button>
<button id="stopBtn" style="display: none;">Stop</button>
<button id="reconnectBtn" style="display: none;">Reconnect</button>
<script>
 let connection;

 // The Disconnect and Stop buttons are visible if there is a connected presentation
 const stopBtn = document.querySelector("#stopBtn");
 const reconnectBtn = document.querySelector("#reconnectBtn");
 const disconnectBtn = document.querySelector("#disconnectBtn");

 stopBtn.onclick = () => {
 connection?.terminate();
 };

 disconnectBtn.onclick = () => {
 connection?.close();
 };

 function setConnection(newConnection) {
 // Disconnect from existing presentation, if not attempting to reconnect
 if (
 connection &&
 connection !== newConnection &&
 connection.state !== "closed"
 ) {
 connection.onclose = undefined;
 connection.close();
 }

 // Set the new connection and save the presentation ID
 connection = newConnection;
 localStorage["presId"] = connection.id;

 function showConnectedUI() {
 // Allow the user to disconnect from or terminate the presentation
 stopBtn.style.display = "inline";
 disconnectBtn.style.display = "inline";
 reconnectBtn.style.display = "none";
 }

 function showDisconnectedUI() {
 disconnectBtn.style.display = "none";
 stopBtn.style.display = "none";
 reconnectBtn.style.display = localStorage["presId"] ? "inline" : "none";
 }

 // Monitor the connection state
 connection.onconnect = () => {
 showConnectedUI();

 // Register message handler
 connection.onmessage = (message) => {
 console.log(`Received message: ${message.data}`);
 };

 // Send initial message to presentation page
 connection.send("Say hello");
 };

 connection.onclose = () => {
 connection = null;
 showDisconnectedUI();
 };

 connection.onterminate = () => {
 // Remove presId from localStorage if exists
 delete localStorage["presId"];
 connection = null;
 showDisconnectedUI();
 };
 }
</script>

```


### Monitor available connection(s) and say hello



In `presentation.html`:

 
```
const addConnection = (connection) => {
  connection.onmessage = (message) => {
    if (message.data === "Say hello") connection.send("hello");
  };
};

navigator.presentation.receiver.connectionList.then((list) => {
  list.connections.forEach((connection) => {
    addConnection(connection);
  });
  list.onconnectionavailable = (evt) => {
    addConnection(evt.connection);
  };
});

```


### Passing locale information with a message



In the `controller.html` file:

 
```
<script>
 connection.send('{"string": "你好，世界!", "lang": "zh-CN"}');
 connection.send('{"string": "こんにちは、世界!", "lang": "ja"}');
 connection.send('{"string": "안녕하세요, 세계!", "lang": "ko"}');
 connection.send('{"string": "Hello, world!", "lang": "en-US"}');
</script>

```
 In the `presentation.html` file:

 
```
<script>
 connection.onmessage = (message) => {
 const messageObj = JSON.parse(message.data);
 const spanElt = document.createElement("SPAN");
 spanElt.lang = messageObj.lang;
 spanElt.textContent = messageObj.string;
 document.body.appendChild(spanElt);
 };
</script>

```


Specifications
--------------




| Specification |
| --- |
| [Presentation API # interface-presentation](https://w3c.github.io/presentation-api/#interface-presentation) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Presentation_API` | 47 | 79 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |
| `defaultRequest` | 47 | 79 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |
| `receiver` | 59 | 79 | No | No | 46 | No | No | 59 | No | 43 | No | 7.0 |


See also
--------


[Presentation API polyfill](https://mediascape.github.io/presentation-api-polyfill/) contains a JavaScript polyfill of the [Presentation API](https://w3c.github.io/presentation-api/) specification under standardization within the [Second Screen Working Group](https://www.w3.org/2014/secondscreen/) at W3C. The polyfill is mostly intended for exploring how the Presentation API may be implemented on top of different presentation mechanisms.



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Presentation_API>

Proximity Events
================



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

  **Warning:** The Proximity Events APIs are not supported by any current major browser, and should not be used. This page is provided for historical interest.

  The **proximity events** are a handy way to know when a user is close to a device. These events make it possible to react to such a change, for example by shutting down the screen of a smartphone when the user is having a phone call with the device close to their ear.

 There are two proximity events (see links for documentation.):

 * [`UserProximityEvent`](userproximityevent), handled by `window.onuserproximity`
* [`DeviceProximityEvent`](deviceproximityevent), handled by `window.ondeviceproximity`

 The difference between them is that [`UserProximityEvent`](userproximityevent) simply notifies `true` when the user is considered "close", while [`DeviceProximityEvent`](deviceproximityevent) provides an estimate of the actual distance to a nearby object.

  **Note:** Obviously, the API requires the device to have a proximity sensor, which are mostly available only on mobile devices. Devices without such a sensor may support those events but will never fire them.

 

Specifications
--------------


This feature is no longer on track to become a standard. Its historical specification is still [available](https://w3c.github.io/proximity/).



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Proximity_Events>

Push API
========


The **Push API** gives web applications the ability to receive messages pushed to them from a server, whether or not the web app is in the foreground, or even currently loaded, on a user agent. This lets developers deliver asynchronous notifications and updates to users that opt in, resulting in better engagement with timely new content.


Push concepts and usage
-----------------------



 **Warning:** When implementing PushManager subscriptions, it is vitally important that you protect against CSRF/XSRF issues in your app. See the following articles for more information:

 * [Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html)
* [Preventing CSRF and XSRF Attacks](https://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/)

  For an app to receive push messages, it has to have an active [service worker](service_worker_api). When the service worker is active, it can subscribe to push notifications, using [`PushManager.subscribe()`](pushmanager/subscribe).

 The resulting [`PushSubscription`](pushsubscription) includes all the information that the application needs to send a push message: an endpoint and the encryption key needed for sending data.

 The service worker will be started as necessary to handle incoming push messages, which are delivered to the [`onpush`](serviceworkerglobalscope/push_event) event handler. This allows apps to react to push messages being received, for example, by displaying a notification (using [`ServiceWorkerRegistration.showNotification()`](serviceworkerregistration/shownotification).)

 Each subscription is unique to a service worker. The endpoint for the subscription is a unique [capability URL](https://www.w3.org/TR/capability-urls/): knowledge of the endpoint is all that is necessary to send a message to your application. The endpoint URL therefore needs to be kept secret, or other applications might be able to send push messages to your application.

 Activating a service worker to deliver a push message can result in increased resource usage, particularly of the battery. Different browsers have different schemes for handling this, there is currently no standard mechanism. Firefox allows a limited number (quota) of push messages to be sent to an application, although Push messages that generate notifications are exempt from this limit. The limit is refreshed each time the site is visited. In Chrome there are no limits.



Interfaces
----------


 [`PushEvent`](pushevent)  Represents a push action, sent to the [global scope](serviceworkerglobalscope) of a [`ServiceWorker`](serviceworker). It contains information sent from an application to a [`PushSubscription`](pushsubscription).

  [`PushManager`](pushmanager)  Provides a way to receive notifications from third-party servers, as well as request URLs for push notifications.

  [`PushMessageData`](pushmessagedata)  Provides access to push data sent by a server, and includes methods to manipulate the received data.

  [`PushSubscription`](pushsubscription)  Provides a subscription's URL endpoint, and allows unsubscribing from a push service.

  [`PushSubscriptionOptions`](pushsubscriptionoptions)  Represents the options associated with the push subscription.

  
Service worker additions
------------------------



The following additions to the [Service Worker API](service_worker_api) have been specified in the Push API spec to provide an entry point for using Push messages. They also monitor and respond to push and subscription change events.

  
[`ServiceWorkerRegistration.pushManager`](serviceworkerregistration/pushmanager) Read only 
  Returns a reference to the [`PushManager`](pushmanager) interface for managing push subscriptions including subscribing, getting an active subscription, and accessing push permission status. This is the entry point into using Push messaging.

  [`onpush`](serviceworkerglobalscope/push_event)  An event handler fired whenever a [`push`](serviceworkerglobalscope/push_event) event occurs; that is, whenever a server push message is received.

  [`onpushsubscriptionchange`](serviceworkerglobalscope/pushsubscriptionchange_event)  An event handler fired whenever a [`pushsubscriptionchange`](serviceworkerglobalscope/pushsubscriptionchange_event) event occurs; for example, when a push subscription has been invalidated, or is about to be invalidated (e.g. when a push service sets an expiration time.)

  

Examples
--------


Mozilla's [ServiceWorker Cookbook](https://github.com/mdn/serviceworker-cookbook) contains many useful Push examples.


Specifications
--------------




| Specification |
| --- |
| [Push API # pushevent-interface](https://w3c.github.io/push-api/#pushevent-interface) |
| [Push API # pushmessagedata-interface](https://w3c.github.io/push-api/#pushmessagedata-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Push_API` | 50 | 17 | 44 | No | 37 | 16Supported on macOS 13 and later | NoSee [bug 421921](https://crbug.com/421921). | 50 | 48 | 37 | 16.4 | 5.0 |
| `arrayBuffer` | 50 | 17 | 44 | No | 37 | 16Supported on macOS 13 and later | No | 50 | 48 | 37 | 16.4 | 5.0 |
| `blob` | 50 | 17 | 44 | No | 37 | 16Supported on macOS 13 and later | No | 50 | 48 | 37 | 16.4 | 5.0 |
| `json` | 50 | 17 | 44 | No | 37 | 16Supported on macOS 13 and later | No | 50 | 48 | 37 | 16.4 | 5.0 |
| `text` | 50 | 17 | 44 | No | 37 | 16Supported on macOS 13 and later | No | 50 | 48 | 37 | 16.4 | 5.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PushEvent` | 42 | 17 | 44 | No | 37 | 16Supported on macOS 13 and later | No | 42 | 48 | 37 | 16.4 | 4.0 |
| `Push_API` | 42 | 17 | 44 | No | 37 | 16Supported on macOS 13 and later | NoSee [bug 421921](https://crbug.com/421921). | 42 | 48 | 37 | 16.4 | 4.0 |
| `data` | 50 | 17 | 44 | No | 37 | 16Supported on macOS 13 and later | No | 50 | 48 | 37 | 16.4 | 5.0 |


### api.PushEvent


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.PushMessageData


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


See also
--------


* [Sending VAPID identified WebPush Notifications via Mozilla's Push Service](https://blog.mozilla.org/services/2016/08/23/sending-vapid-identified-webpush-notifications-via-mozillas-push-service/)
* [Push notifications overview](https://web.dev/push-notifications-overview/)
* [Service Worker API](service_worker_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Push_API>

Reporting API
=============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The Reporting API provides a generic reporting mechanism for web applications to use to make reports available based on various platform features (for example [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP), [Permissions-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy), or feature deprecation reports) in a consistent manner.



Concepts and usage
------------------



There are several different features and problems on the web platform that generate information useful to web developers when they are trying to fix bugs or improve their websites in other ways. Such information can include:

 * [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) violations.
* [Permissions-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy) violations.
* Deprecated feature usage (when you are using something that will stop working soon in browsers).
* Occurrence of crashes.
* Occurrence of user-agent interventions (when the browser blocks something your code is trying to do because it is deemed a security risk for example, or just plain annoying, like auto-playing audio).

 The Reporting API's purpose is to provide a consistent reporting mechanism that can be used to make such information available to developers in the form of reports represented by JavaScript objects. There are a few ways to use it, which are detailed in the sections below.



### Origins and endpoints



Each unique origin you want to retrieve reports for can be given a series of endpoints, which are URLs that can receive given reports from a user agent.

 The [`Report-To`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Report-To) HTTP header is used to specify details about the different endpoints that a user-agent has available to it for delivering reports to. You can then retrieve reports by making a request to those URLs.

 The endpoints are arranged into groups; an endpoint group can work together to provide load balancing (each endpoint will receive a specified proportion of report traffic) and safeguarding against failure (fallback endpoints can be specified to use if the primary ones fail).

  **Note:** There is no absolute guarantee of report delivery — a report could still fail to be collected if a serious error occurs.

  Reports sent to endpoints can be retrieved independently of the running of the websites they relate to, which is useful — a crash for example could bring down a web site and stop anything running, but a report could still be obtained to give the developer some clues as to why it happened.



### Reporting observers



Reports can also be obtained via [`ReportingObserver`](reportingobserver) objects created via JavaScript inside the website you are aiming to get reports on. This method is not as failsafe as the `Report-To` method described above — any page crash could stop you retrieving the reports — but it is easier to set up, and more flexible.

 A `ReportingObserver` object is created using the [`ReportingObserver()`](reportingobserver/reportingobserver) constructor, which is passed two parameters:

 * A callback function that has available as parameters the reports available in the observer's report queue, and a copy of the same `ReportingObserver` object, so observation can be controlled directly from inside the callback. The callback runs when observation starts
* An options dictionary that allows you to specify the type of reports to collect, and whether the reports that were generated before the observer was able to be created should be observable (`buffered: true`).

 Methods are then available on the observer to start collecting reports ([`ReportingObserver.observe()`](reportingobserver/observe)), retrieve the reports currently in the report queue ([`ReportingObserver.takeRecords()`](reportingobserver/takerecords)), and disconnect the observer so it can no longer collect records ([`ReportingObserver.disconnect()`](reportingobserver/disconnect)).



### Generating reports via WebDriver


The Reporting API spec also defines a Generate Test Report [WebDriver](https://developer.mozilla.org/en-US/docs/Web/WebDriver) extension, which allows you to simulate report generation during automation. Reports generated via WebDriver are observed by any registered `ReportObserver` objects present in the loaded website. This is not yet documented.


Interfaces
----------


 [`CSPViolationReportBody`](cspviolationreportbody)  Contains details of a [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) violation.

  [`DeprecationReportBody`](deprecationreportbody)  Contains details of deprecated web platform features that a website is using.

  [`InterventionReportBody`](interventionreportbody)  Contains details of an intervention report, which is generated when a request made by the website has been denied by the browser; e.g. for security reasons.

  [`Report`](report)  An object representing a single report.

  [`ReportingObserver`](reportingobserver)  An object that can be used to collect and access reports as they are generated.

  
Examples
--------



In our [deprecation\_report.html](https://mdn.github.io/dom-examples/reporting-api/deprecation_report.html) example, we create a simple reporting observer to observe usage of deprecated features on our web page:

 
```
const options = {
  types: ["deprecation"],
  buffered: true,
};

const observer = new ReportingObserver((reports, observer) => {
  reportBtn.onclick = () => displayReports(reports);
}, options);

```
 We then tell it to start observing reports using [`ReportingObserver.observe()`](reportingobserver/observe); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor:

 
```
observer.observe();

```
 Later on in the example we deliberately use the deprecated version of [`MediaDevices.getUserMedia()`](mediadevices/getusermedia):

 
```
if (navigator.mozGetUserMedia) {
  navigator.mozGetUserMedia(constraints, success, failure);
} else {
  navigator.getUserMedia(constraints, success, failure);
}

```
 This causes a deprecation report to be generated; because of the event handler we set up inside the `ReportingObserver()` constructor, we can now click the button to display the report details.

  ![image of a jolly bearded man with various stats displayed below it about a deprecated feature] 

  **Note:** If you look at the [complete source code](https://github.com/mdn/dom-examples/blob/main/reporting-api/deprecation_report.html), you'll notice that we actually call the deprecated `getUserMedia()` method twice. After the first time we call [`ReportingObserver.takeRecords()`](reportingobserver/takerecords), which returns the first generated report and empties the queue. Because of this, when the button is pressed only the second report is listed.

 

Specifications
--------------




| Specification |
| --- |
| [Reporting API # intro](https://w3c.github.io/reporting/#intro) |


Browser compatibility
---------------------


See also
--------


* [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)
* [`Permissions-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Reporting_API>

Resize Observer API
===================


The Resize Observer API provides a performant mechanism by which code can monitor an element for changes to its size, with notifications being delivered to the observer each time the size changes.


Concepts and usage
------------------



There are a whole raft of use cases for responsive design techniques (and others besides) that respond to changes in an element's size, but previously their implementations have often been hacky and/or brittle.

 For example, [media queries](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries) / [`window.matchMedia`](window/matchmedia) are great for updating layouts at specific points when the viewport changes sizes, but what if you want to change layout in response to a specific element's size changing, which isn't the outer container?

 To achieve this, a limited solution would be to listen to changes to a suitable event that hints at the element you are interested in changing size (e.g. the window [resize event](window/resize_event)), then figure out what the new dimensions or other features of the element after a resize using [`Element.getBoundingClientRect`](element/getboundingclientrect) or [`Window.getComputedStyle`](window/getcomputedstyle), for example.

 Such a solution tends to only work for limited use cases, be bad for performance (continually calling the above methods would result in a big performance hit), and often won't work when the browser window size is not changed.

 The Resize Observer API provides a solution to exactly these kinds of problems, and more besides, allowing you to easily observe and respond to changes in the size of an element's content or border box in a performant way. It provides a JavaScript solution to the often-discussed lack of [element queries](https://www.xanthir.com/b4PR0) in the web platform.

 Usage is simple, and pretty much the same as other observers, such as [Performance Observer](performanceobserver) or [Intersection Observer](intersection_observer_api) — you create a new [`ResizeObserver`](resizeobserver) object using the [`ResizeObserver()`](resizeobserver/resizeobserver) constructor, then use [`ResizeObserver.observe()`](resizeobserver/observe) to make it look for changes to a specific element's size. A callback function set up inside the constructor then runs every time the size changes, providing access to the new dimensions and allowing you to do anything you like in response to those changes.



Interfaces
----------


 [`ResizeObserver`](resizeobserver)  Provides the ability to register new observers and to start and stop observing elements.

  [`ResizeObserverEntry`](resizeobserverentry)  Describes a single element which has been resized, identifying the element and its new size.

  
Examples
--------



You find a couple of simple examples on our GitHub repo:

 * [resize-observer-border-radius.html](https://mdn.github.io/dom-examples/resize-observer/resize-observer-border-radius.html) ([see source](https://github.com/mdn/dom-examples/blob/main/resize-observer/resize-observer-border-radius.html)): A simple example with a green box, sized as a percentage of the viewport size. When the viewport size is changed, the box's rounded corners change in proportion to the size of the box. We could just implement this using [`border-radius`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius) with a percentage, but that quickly leads to ugly-looking elliptical corners, whereas the above solution gives you nice round corners that scale with the box size.
* [resize-observer-text.html](https://mdn.github.io/dom-examples/resize-observer/resize-observer-text.html) ([see source](https://github.com/mdn/dom-examples/blob/main/resize-observer/resize-observer-text.html)): Here we use the resize observer to change the [`font-size`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-size) of a header and paragraph as a slider's value is changed causing the containing `<div>` to change width. This shows that you can respond to changes in an element's size, even if they have nothing to do with the viewport.

 The code will usually follow this kind of pattern (taken from resize-observer-border-radius.html):

 
```
const resizeObserver = new ResizeObserver((entries) => {
  const calcBorderRadius = (size1, size2) =>
    `${Math.min(100, size1 / 10 + size2 / 10)}px`;

  for (const entry of entries) {
    if (entry.borderBoxSize) {
      entry.target.style.borderRadius = calcBorderRadius(
        entry.borderBoxSize[0].inlineSize,
        entry.borderBoxSize[0].blockSize
      );
    } else {
      entry.target.style.borderRadius = calcBorderRadius(
        entry.contentRect.width,
        entry.contentRect.height
      );
    }
  }
});

resizeObserver.observe(document.querySelector("div"));

```


Specifications
--------------




| Specification |
| --- |
| [Resize Observer # resize-observer-interface](https://w3c.github.io/csswg-drafts/resize-observer/#resize-observer-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ResizeObserver` | 64 | 79 | 69 | No | 51 | 13.1 | 64 | 64 | 79 | 47 | 13.4 | 9.0 |
| `Resize_Observer_API` | 64 | 79 | 69 | No | 51 | 13.1 | 64 | 64 | 79 | 47 | 13.4 | 9.0 |
| `disconnect` | 64 | 79 | 69 | No | 51 | 13.1 | 64 | 64 | 79 | 47 | 13.4 | 9.0 |
| `observe` | 64 | 79 | 69 | No | 51 | 13.1 | 64 | 64 | 79 | 47 | 13.4 | 9.0 |
| `unobserve` | 64 | 79 | 69 | No | 51 | 13.1 | 64 | 64 | 79 | 47 | 13.4 | 9.0 |


See also
--------


* [ResizeObserver: It's Like document.onresize for Elements](https://web.dev/resize-observer/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Resize_Observer_API>

Screen Capture API
==================


The Screen Capture API introduces additions to the existing Media Capture and Streams API to let the user select a screen or portion of a screen (such as a window) to capture as a media stream. This stream can then be recorded or shared with others over the network.


Screen Capture API concepts and usage
-------------------------------------



The Screen Capture API is relatively simple to use. Its sole method is [`MediaDevices.getDisplayMedia()`](mediadevices/getdisplaymedia), whose job is to ask the user to select a screen or portion of a screen to capture in the form of a [`MediaStream`](mediastream).

 To start capturing video from the screen, you call `getDisplayMedia()` on `navigator.mediaDevices`:

 
```
captureStream = await navigator.mediaDevices.getDisplayMedia(
  displayMediaOptions
);

```
 The [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) returned by `getDisplayMedia()` resolves to a [`MediaStream`](mediastream) which streams the captured media.

 See the article [Using the Screen Capture API](screen_capture_api/using_screen_capture) for a more in-depth look at how to use the API to capture screen contents as a stream.



Interfaces
----------


 [`CaptureController`](capturecontroller)  Provides methods that can be used to further manipulate a capture session separate from its initiation via [`MediaDevices.getDisplayMedia()`](mediadevices/getdisplaymedia). A `CaptureController` object is associated with a capture session by passing it into a [`getDisplayMedia()`](mediadevices/getdisplaymedia) call as the value of the options object's `controller` property.

  
Additions to the MediaDevices interface
---------------------------------------


 [`MediaDevices.getDisplayMedia()`](mediadevices/getdisplaymedia)  The `getDisplayMedia()` method is added to the `MediaDevices` interface. Similar to [`getUserMedia()`](mediadevices/getusermedia), this method creates a promise that resolves with a [`MediaStream`](mediastream) containing the display area selected by the user, in a format that matches the specified options.

  
Additions to existing dictionaries
----------------------------------


The Screen Capture API adds properties to the following dictionaries defined by other specifications.


### MediaTrackConstraints


 [`MediaTrackConstraints.cursor`](mediatrackconstraints)  A [`ConstrainDOMString`](mediatrackconstraints#constraindomstring) indicating whether or not the cursor should be included in the captured display surface's stream, and if it should always be visible or if it should only be visible while the mouse is in motion.

  [`MediaTrackConstraints.displaySurface`](mediatrackconstraints/displaysurface)  A [`ConstrainDOMString`](mediatrackconstraints#constraindomstring) indicating what type of display surface is to be captured. The value is one of `browser`, `monitor`, or `window`.

  [`MediaTrackConstraints.logicalSurface`](mediatrackconstraints/logicalsurface)  Indicates whether or not the video in the stream represents a logical display surface (that is, one which may not be entirely visible onscreen, or may be completely offscreen). A value of `true` indicates a logical display surface is to be captured.

  [`MediaTrackConstraints.suppressLocalAudioPlayback`](mediatrackconstraints/suppresslocalaudioplayback)  Controls whether the audio playing in a tab will continue to be played out of a user's local speakers when the tab is captured, or whether it will be suppressed. A value of `true` indicates that it will be suppressed.

  
### MediaTrackSettings


 [`MediaTrackSettings.cursor`](mediatracksettings/cursor)  A string which indicates whether or not the display surface currently being captured includes the mouse cursor, and if so, whether it's only visible while the mouse is in motion or if it's always visible. The value is one of `always`, `motion`, or `never`.

  [`MediaTrackSettings.displaySurface`](mediatracksettings/displaysurface)  A string indicating what type of display surface is currently being captured. The value is one of `browser`, `monitor`, or `window`.

  [`MediaTrackSettings.logicalSurface`](mediatracksettings/logicalsurface)  A boolean value, which is `true` if the video being captured doesn't directly correspond to a single onscreen display area.

  [`MediaTrackSettings.suppressLocalAudioPlayback`](mediatracksettings/suppresslocalaudioplayback)  A boolean value, which is `true` if the audio being captured is not played out of the user's local speakers.

  
### MediaTrackSupportedConstraints


 [`MediaTrackSupportedConstraints.cursor`](mediatracksupportedconstraints)  A boolean, which is `true` if the user agent and device support the [`MediaTrackConstraints.cursor`](mediatrackconstraints) constraint.

  [`MediaTrackSupportedConstraints.displaySurface`](mediatracksupportedconstraints/displaysurface)  A boolean, which is `true` if the current environment supports the [`MediaTrackConstraints.displaySurface`](mediatrackconstraints/displaysurface) constraint.

  [`MediaTrackSupportedConstraints.logicalSurface`](mediatracksupportedconstraints/logicalsurface)  A boolean, which is `true` if the current environment supports the constraint [`MediaTrackConstraints.logicalSurface`](mediatrackconstraints/logicalsurface).

  [`MediaTrackSupportedConstraints.suppressLocalAudioPlayback`](mediatracksupportedconstraints/suppresslocalaudioplayback)  A boolean, which is `true` if the current environment supports the constraint [`MediaTrackConstraints.suppressLocalAudioPlayback`](mediatrackconstraints/suppresslocalaudioplayback).

  
Permissions Policy validation
-----------------------------



[User agents](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) that support [Permissions Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy) (either using the HTTP [`Permissions-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy) header or the [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe) attribute [`allow`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#allow)) can specify a desire to use the Screen Capture API using the directive `display-capture`:

 
```
<iframe allow="display-capture" src="/some-other-document.html">…</iframe>

```
 The default allowlist is `self`, which lets any content within the same origin use Screen Capture.



Specifications
--------------




| Specification |
| --- |
| [Screen Capture # dom-mediadevices-getdisplaymedia](https://w3c.github.io/mediacapture-screen-share/#dom-mediadevices-getdisplaymedia) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Screen_Capture_API` | 72 | 7917–79Available as a member of `Navigator` instead of `MediaDevices`. | 6633–66Since Firefox 33 you can capture screen data using `[getUserMedia()](https://developer.mozilla.org/docs/Web/API/MediaDevices/getUserMedia)`, with a `video` constraint called `mediaSource`. Before 52 it relied on a client-configurable list of allowed sites. | No | 60 | 13 | NoFrom Chrome Android 72 to 88, this method was exposed, but always failed with `NotAllowedError`. See [bug 487935](https://crbug.com/487935). | NoFrom Chrome Android 72 to 88, this method was exposed, but always failed with `NotAllowedError`. See [bug 487935](https://crbug.com/487935). | NoFrom Firefox Android 66 to 79, this method was exposed, but always failed with `NotAllowedError`. | NoFrom Opera Android 72 to 88, this method was exposed, but always failed with `NotAllowedError`. See [bug 487935](https://crbug.com/487935). | No | NoFrom Samsung Internet Android 72 to 88, this method was exposed, but always failed with `NotAllowedError`. See [bug 487935](https://crbug.com/487935). |
| `audio_capture_support` | 74On Windows and Chrome OS the entire system audio can be captured, but on Linux and macOS only the audio of a tab can be captured. | ≤79On Windows, the entire system audio can be captured, but on Linux and macOS only the audio of a tab can be captured. | No | No | 62On Windows, the entire system audio can be captured, but on Linux and macOS only the audio of a tab can be captured. | No | No | No | No | No | No | No |
| `controller_option` | 109 | 109 | No | No | 95 | No | No | No | No | No | No | No |
| `preferCurrentTab_option` | 94 | 94 | No | No | 80 | No | No | No | No | No | No | No |
| `selfBrowserSurface_option` | 107 | 107 | No | No | 93 | No | No | No | No | No | No | No |
| `surfaceSwitching_option` | 107 | 107 | No | No | 93 | No | No | No | No | No | No | No |
| `systemAudio_option` | 105 | 105 | No | No | 91 | No | No | No | No | No | No | No |


See also
--------


* [Using the Screen Capture API](screen_capture_api/using_screen_capture)
* [`MediaDevices.getDisplayMedia()`](mediadevices/getdisplaymedia)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Screen_Capture_API>

Screen Orientation API
======================


The **Screen Orientation API** provides information about the orientation of the screen.


Interfaces
----------


* [`ScreenOrientation`](screenorientation)

Specifications
--------------




| Specification |
| --- |
| [Screen Orientation # screenorientation-interface](https://w3c.github.io/screen-orientation/#screenorientation-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Screen_Orientation_API` | 38 | 79 | 43 | No | 25 | 16.4 | 38 | 38 | 43 | 25 | 16.4 | 3.0 |
| `angle` | 38 | 79 | 43 | No | 25 | 16.4 | 38 | 38 | 43 | 25 | 16.4 | 3.0 |
| `change_event` | 38 | 79 | 43 | No | 25 | 16.4 | 38 | 38 | 43 | 25 | 16.4 | 3.0 |
| `lock` | 38Always throws `NotSupportedError`. | 79Always throws `NotSupportedError`. | 43Always throws `NotSupportedError`. | No | 25Always throws `NotSupportedError`. | 16.4 | 38 | 38 | 79–97The API exists but returns `NS_ERROR_UNEXPECTED`.43–79 | 25 | 16.4 | 3.0 |
| `type` | 38 | 79 | 43 | No | 25 | 16.4 | 38 | 38 | 43 | 25 | 16.4 | 3.0 |
| `unlock` | 38Always throws `NotSupportedError`. | 79Always throws `NotSupportedError`. | 43Always throws `NotSupportedError`. | No | 25Always throws `NotSupportedError`. | 16.4 | 38 | 38 | 43 | 25 | 16.4 | 3.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Screen_Orientation_API>

Screen Wake Lock API
====================


The Screen Wake Lock API provides a way to prevent devices from dimming or locking the screen when an application needs to keep running.


Concepts and Usage
------------------



Most devices by default turn off their screen after a specified amount of time to prolong the life of the hardware. Modern devices do this to save on battery power. Whilst this is a useful feature, some applications need the screen to stay awake to be their most useful.

 The Screen Wake Lock API prevents the screen from turning off, dimming or locking. It allows for a simple platform-based solution which up until now could only be achieved via workarounds which were potentially power hungry. Only visible (active) documents can acquire the screen wake lock.

 There are plenty of use cases for keeping a screen on, including reading an ebook, map navigation, following a recipe, presenting to an audience, scanning a QR/barcode or applications that use voice or gesture control, rather than tactile input (the default way to keep a screen awake).

 You acquire a [`WakeLockSentinel`](wakelocksentinel) object by calling the [`navigator.wakeLock.request()`](wakelock/request) [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)-based method that resolves if the platform allows it. A request may be rejected for a number of reasons, including system settings (such as power save mode or low battery level) or if the document is not active or visible.

 The sentinel is attached to the underlying system wake lock. It can be released by the system, again if the battery power is too low or the document is not active or visible. It can also be released manually via the [`WakeLockSentinel.release()`](wakelocksentinel/release) method. It is good practice to store a reference to the sentinel object to control release later and also to reacquire the lock if need be.

 The Screen Wake Lock API should be used to keep the screen on to benefit usability. It's a good idea to show some feedback on the interface to show if wake lock is active and a way for the user to disable it if they wish.



Screen Wake Lock API Interfaces
-------------------------------


 [`WakeLock`](wakelock)  The `WakeLock` interface prevents device screens from dimming or locking when an application needs to keep running.

  [`WakeLockSentinel`](wakelocksentinel)  Provides a handle to the underlying platform wake lock and if referenced can be manually released and reacquired. Get an instance of the object by calling [`WakeLock.request`](wakelock/request).

  [`Navigator.wakelock`](navigator/wakelock)  Returns a [`WakeLock`](wakelock) object instance, from which all other functionality can be accessed.

  
Examples
--------


### Feature Detection



This code checks for wake lock support and updates the UI accordingly.

 
```
if ("wakeLock" in navigator) {
  isSupported = true;
  statusElem.textContent = "Screen Wake Lock API supported!";
} else {
  wakeButton.disabled = true;
  statusElem.textContent = "Wake lock is not supported by this browser.";
}

```


### Requesting a wake lock



The following example demonstrates how to request a [`WakeLockSentinel`](wakelocksentinel) object. The [`WakeLock.request`](wakelock/request) method is [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)-based and so we can create an asynchronous function, which in turn updates the UI to reflect the wake lock is active.

 
```
// Create a reference for the Wake Lock.
let wakeLock = null;

// create an async function to request a wake lock
try {
  wakeLock = await navigator.wakeLock.request("screen");
  statusElem.textContent = "Wake Lock is active!";
} catch (err) {
  // The Wake Lock request has failed - usually system related, such as battery.
  statusElem.textContent = `${err.name}, ${err.message}`;
}

```


### Releasing wake lock



The following example shows how to release the previously acquired wake lock.

 
```
wakeLock.release().then(() => {
  wakeLock = null;
});

```


### Listening for wake lock release



This example updates the UI if the wake lock has been released for any reason (such as navigating away from the active window/tab).

 
```
wakeLock.addEventListener("release", () => {
  // the wake lock has been released
  statusElem.textContent = "Wake Lock has been released";
});

```


### Reacquiring a wake lock



The following code reacquires the wake lock should the visibility of the document change and the wake lock is released.

 
```
document.addEventListener("visibilitychange", async () => {
  if (wakeLock !== null && document.visibilityState === "visible") {
    wakeLock = await navigator.wakeLock.request("screen");
  }
});

```


### Putting it all together


You can find the [complete code on GitHub here](https://github.com/mdn/dom-examples/tree/main/screen-wake-lock-api). The [demo](https://mdn.github.io/dom-examples/screen-wake-lock-api/) uses a button to acquire a wake lock and also release it, which in turn updates the UI. The UI also updates if the wake lock is released automatically for any reason. There's a checkbox which when checked, will automatically reacquire the wake lock if the document's visibility state changes and becomes visible again.


### Performance considerations


* Release the screen wake lock when user ends activity that required always-on screen. For example, a ticketing app which uses QR codes to transmit ticket information, might acquire screen wake lock when the QR code is displayed (so that code is successfully scanned) but release afterwards. A presentation app might hold the lock only while a presentation is active, but not when presentation is being edited.
* If your app is performing long-running downloads, consider using background fetch.
* If your app is synchronizing data from a remote server, consider using background sync.
* Only active documents can acquire screen wake locks and previously acquired locks are automatically released when document becomes inactive. Therefore make sure to re-acquire screen wake lock if necessary when document becomes active (listen for [visibilitychange](document/visibilitychange_event) event).

Permissions Policy integration
------------------------------



Access to the Screen Wake Lock API is controlled by the [Permissions Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy) directive [`screen-wake-lock`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy/screen-wake-lock).

 The default allowlist for `screen-wake-lock` is `self`.



Specifications
--------------




| Specification |
| --- |
| [Screen Wake Lock API # the-wakelock-interface](https://w3c.github.io/screen-wake-lock/#the-wakelock-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Screen_Wake_Lock_API` | 84 | 84 | No | No | 70 | 16.4 | 84 | 84 | No | 60 | 16.4 | 14.0 |
| `request` | 84 | 84 | No | No | 70 | 16.4 | 84 | 84 | No | 60 | 16.4 | 14.0 |


See also
--------


* [An introductory article on the Screen Wake Lock API](https://web.dev/wake-lock/)
* [A Screen Wake Lock API demo on glitch](https://wake-lock-demo.glitch.me/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Screen_Wake_Lock_API>

Selection API
=============



 **Note:** This API is *not available* in [Web Workers](web_workers_api) (not exposed via [`WorkerNavigator`](workernavigator)).

  The **Selection API** enables developers to access and manipulate the portion of a document selected by the user.

 The [`Window.getSelection()`](window/getselection) and [`Document.getSelection()`](document/getselection) methods return a [`Selection`](selection) object representing the portion of the document selected by the user. A `Selection` object provides methods to:

 * access the currently selected nodes
* modify the current selection, expanding or collapsing it or selecting an entirely different part of the document
* delete parts of the current selection from the DOM.

 The Selection API also provides two events, both firing on [`Document`](document):

 * the [`selectstart`](node/selectstart_event) event is fired when the user starts to make a new selection
* the [`selectionchange`](document/selectionchange_event) event is fired when the current selection changes.



Interfaces
----------


 [`Selection`](selection)  An interface which represents the part of the document selected by the user or the current position of the caret.

  [`Document.getSelection()`](document/getselection)  A method returning a `Selection` object representing the current selection or current position of the caret.

  [`Window.getSelection()`](window/getselection)  A method returning a `Selection` object representing the current selection or current position of the caret.

  [`Document.selectionchange`](document/selectionchange_event)  An event which is fired when the current selection is changed.

  [`Node.selectstart`](node/selectstart_event)  An event which is fired when a user starts a new selection.

  
Specifications
--------------




| Specification |
| --- |
| [Selection API # selection-interface](https://w3c.github.io/selection-api/#selection-interface) |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Selection_API>

Sensor APIs
===========


The **Sensor APIs** are a set of interfaces built to a common design that expose device sensors in a consistent way to the web platform.


Sensor APIs concepts and usage
------------------------------



Although the Generic Sensor API specification defines a [`Sensor`](sensor) interface, as a web developer you will never use it. Instead you'll use one of its subclasses to retrieve specific kinds of sensor data. For example, the [`accelerometer`](accelerometer) interface returns the acceleration of the device along all three axes at the time it is read.

 Sensors may or may not correspond exactly to a physical device sensor. For example, the [`Gyroscope`](gyroscope) interface corresponds exactly to a physical device interface. Alternatively, the [`AbsoluteOrientationSensor`](absoluteorientationsensor) interface provides information that is algorithmically aggregated from two or more device sensors. These sensor types are referred to as *low-level* and *high-level* respectively. The latter type of sensor is also called a fusion sensor (alternatively, virtual or synthetic sensors).



### Feature detection



Sensor interfaces are only proxies for the underlying device sensors. Consequently, feature detection is more complicated for sensors than it is for other APIs. The presence of a sensor API does not tell you whether that API is connected to a real hardware sensor, whether that sensor works, if it's still connected, or even whether the user has granted access to it. Making all this information consistently available is costly to performance and battery life.

 Therefore, feature detection for sensor APIs must include both detection of the APIs themselves and [defensive programming strategies (see below)](#defensive_programming).

 The examples below show three methods for detecting sensor APIs. Additionally you can put object instantiation inside a [`try...catch`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) block. Notice that detection through the [`Navigator`](navigator) interface is not one of the available options.

 
```
if (typeof Gyroscope === "function") {
  // run in circles…
}

if ("ProximitySensor" in window) {
  // watch out!
}

if (window.AmbientLightSensor) {
  // go dark…
}

```


### Defensive programming



As stated in Feature Detection, checking for a particular sensor API is insufficient for feature detection. The existence of an actual sensor must be confirmed as well. This is where defensive programming is needed. Defensive programming requires three strategies.

 * Checking for thrown errors when instantiating a sensor object.
* Listening for errors thrown during its use.
* Handling the errors gracefully so that the user experience is enhanced rather than degraded.

 The code example below illustrates these principles. The [`try...catch`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) block catches errors thrown during sensor instantiation. It listens for [`error`](sensor/error_event) events to catch errors thrown during use. The only time anything is shown to the user is when [permissions](permissions_api) need to be requested and when the sensor type isn't supported by the device.

 In addition, this feature may be blocked by a [Permissions Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy) set on your server.

 
```
let accelerometer = null;
try {
  accelerometer = new Accelerometer({ referenceFrame: "device" });
  accelerometer.addEventListener("error", (event) => {
    // Handle runtime errors.
    if (event.error.name === "NotAllowedError") {
      // Branch to code for requesting permission.
    } else if (event.error.name === "NotReadableError") {
      console.log("Cannot connect to the sensor.");
    }
  });
  accelerometer.addEventListener("reading", () => reloadOnShake(accelerometer));
  accelerometer.start();
} catch (error) {
  // Handle construction errors.
  if (error.name === "SecurityError") {
    // See the note above about permissions policy.
    console.log("Sensor construction was blocked by a permissions policy.");
  } else if (error.name === "ReferenceError") {
    console.log("Sensor is not supported by the User Agent.");
  } else {
    throw error;
  }
}

```


### Permissions and Permissions Policy



Sensor readings may not be taken unless the user grants permission to a specific sensor type using the [Permissions API](permissions_api) and/or if access is not blocked by the server [`Permissions-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy).

 The example below shows how to request user-permission before attempting to use the sensor.

 
```
navigator.permissions.query({ name: "accelerometer" }).then((result) => {
  if (result.state === "denied") {
    console.log("Permission to use accelerometer sensor is denied.");
    return;
  }
  // Use the sensor.
});

```
 An alternative approach is to attempt to use the sensor and listen for the `SecurityError`.

 
```
const sensor = new AbsoluteOrientationSensor();
sensor.start();
sensor.addEventListener("error", (error) => {
  if (event.error.name === "SecurityError")
    console.log("No permissions to use AbsoluteOrientationSensor.");
});

```
 The following table describes for each sensor type, the name required for the Permissions API, the [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe) element's `allow` attribute and the [`Permissions-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy) directive.

 

| Sensor | Permission Policy Name |
| --- | --- |
| `AbsoluteOrientationSensor` | `'accelerometer'`, `'gyroscope'`, and `'magnetometer'` |
| `Accelerometer` | `'accelerometer'` |
| `AmbientLightSensor` | `'ambient-light-sensor'` |
| `GravitySensor` | `'accelerometer'` |
| `Gyroscope` | `'gyroscope'` |
| `LinearAccelerationSensor` | `'accelerometer'` |
| `Magnetometer` | `'magnetometer'` |
| `RelativeOrientationSensor` | `'accelerometer'`, and `'gyroscope'` |



### Readings



Sensor readings are received through the [`reading`](sensor/reading_event) event callback which is inherited by all sensor types. Reading frequency is decided by you, accomplished with an option passed to a sensor's constructor. The option is a number that specifies the number of readings per second. A whole number or decimal may be used, the latter for frequencies less than a second. The actual reading frequency depends device hardware and consequently may be less than requested.

 The following example illustrates this using the [`Magnetometer`](magnetometer) sensor.

 
```
let magSensor = new Magnetometer({ frequency: 60 });

magSensor.addEventListener("reading", (e) => {
  console.log(`Magnetic field along the X-axis ${magSensor.x}`);
  console.log(`Magnetic field along the Y-axis ${magSensor.y}`);
  console.log(`Magnetic field along the Z-axis ${magSensor.z}`);
});
magSensor.addEventListener("error", (event) => {
  console.log(event.error.name, event.error.message);
});
magSensor.start();

```


Interfaces
----------


 
[`AbsoluteOrientationSensor`](absoluteorientationsensor) Secure context
  Describes the device's physical orientation in relation to the Earth's reference coordinate system.

  
[`Accelerometer`](accelerometer) Secure context
  Provides the acceleration applied to the device along all three axes.

  
[`AmbientLightSensor`](ambientlightsensor) Secure context
  Returns the current light level or illuminance of the ambient light around the hosting device.

  
[`GravitySensor`](gravitysensor) Secure context
  Provides the gravity applied to the device along all three axes.

  
[`Gyroscope`](gyroscope) Secure context
  Provides the angular velocity of the device along all three axes.

  
[`LinearAccelerationSensor`](linearaccelerationsensor) Secure context
  Provides the acceleration applied to the device along all three axes, but without the contribution of gravity.

  
[`Magnetometer`](magnetometer) Secure context
  Provides information about the magnetic field as detected by the device's primary magnetometer sensor.

  
[`OrientationSensor`](orientationsensor) Secure context
  The base class for the [`AbsoluteOrientationSensor`](absoluteorientationsensor). This interface cannot be used directly, instead it provides properties and methods accessed by interfaces that inherit from it.

  
[`RelativeOrientationSensor`](relativeorientationsensor) Secure context
  Describes the device's physical orientation without regard to the Earth's reference coordinate system.

  
[`Sensor`](sensor) Secure context
  The base class for all the other sensor interfaces. This interface cannot be used directly. Instead it provides properties, event handlers, and methods accessed by interfaces that inherit from it.

  
[`SensorErrorEvent`](sensorerrorevent) Secure context
  Provides information about errors thrown by a [`Sensor`](sensor) or related interface.

  
Specifications
--------------




| Specification |
| --- |
| [Generic Sensor API # the-sensor-interface](https://w3c.github.io/sensors/#the-sensor-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Sensor_APIs` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |
| `activate_event` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |
| `activated` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |
| `error_event` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |
| `hasReading` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |
| `reading_event` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |
| `start` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |
| `stop` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |
| `timestamp` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Sensor_APIs>

Pointer events
==============



Much of today's web content assumes the user's pointing device will be a mouse. However, since many devices support other types of pointing input devices, such as pen/stylus and touch surfaces, extensions to the existing pointing device event models are needed. *[Pointer events](#pointer_event)* address that need.

  **Note:** Pointer events are *not available* in [Web Workers](web_workers_api).

  Pointer events are DOM events that are fired for a pointing device. They are designed to create a single DOM event model to handle pointing input devices such as a mouse, pen/stylus or touch (such as one or more fingers).

 The *[pointer](#pointer)* is a hardware-agnostic device that can target a specific set of screen coordinates. Having a single event model for pointers can simplify creating Web sites and applications and provide a good user experience regardless of the user's hardware. However, for scenarios when device-specific handling is desired, pointer events defines a [`pointerType property`](pointerevent/pointertype) to inspect the device type which produced the event.

 The events needed to handle generic pointer input are analogous to [`mouse events`](mouseevent) (`mousedown`/`pointerdown`, `mousemove`/`pointermove`, etc.). Consequently, pointer event types are intentionally similar to mouse event types.

 Additionally, a pointer event contains the usual properties present in mouse events (client coordinates, target element, button states, etc.) in addition to new properties for other forms of input: pressure, contact geometry, tilt, etc. In fact, the [`PointerEvent`](pointerevent) interface inherits all of the [`MouseEvent`](mouseevent) properties, thus facilitating the migration of content from mouse events to pointer events.



Terminology
-----------


### active buttons state


The condition when a *[pointer](#pointer)* has a non-zero value for the `buttons` property. For example, in the case of a pen, when the pen has physical contact with the digitizer, or at least one button is pressed while hovering.


### active pointer


Any *[pointer](#pointer)* input device that can produce events. A pointer is considered active if it can still produce further events. For example, a pen that is a down state is considered active because it can produce additional events when the pen is lifted or moved.


### digitizer


A sensing device with a surface that can detect contact. Most commonly, the sensing device is a touch-enabled screen that can sense input from an input device such as a pen, stylus, or finger. Some sensing devices can detect the close proximity of the input device, and the state is expressed as a hover following the mouse.


### hit test


The process the browser uses to determine a target element for a pointer event. Typically, this is determined by considering the pointer's location and also the visual layout of elements in a document on screen media.


### pointer


A hardware-agnostic representation of input devices that can target a specific coordinate (or set of coordinates) on a screen. Examples of *pointer* input devices are mouse, pen/stylus, and touch contacts.


### pointer capture


Pointer capture allows the events for a pointer to be retargeted to a particular element other than the normal hit test result of the pointer's location.


### pointer event


A DOM [`event`](pointerevent) fired for a *[pointer](#pointer)*.


Interfaces
----------



The primary interface is the [`PointerEvent`](pointerevent) interface which has a [`constructor`](pointerevent/pointerevent) plus several event types and associated global event handlers.

 The standard also includes some extensions to the [`Element`](element) and [`Navigator`](navigator) interfaces.

 The following sub-sections contain short descriptions of each interface and property.



### PointerEvent interface



The [`PointerEvent`](pointerevent) interface extends the [`MouseEvent`](mouseevent) interface and has the following properties. (All of the following properties are Read only .)

  [`pointerId`](pointerevent/pointerid)  A unique identifier for the pointer causing the event.

  [`width`](pointerevent/width)  The width (magnitude on the X axis), in CSS pixels, of the contact geometry of the pointer.

  [`height`](pointerevent/height)  the height (magnitude on the Y axis), in CSS pixels, of the contact geometry of the pointer.

  [`pressure`](pointerevent/pressure)  the normalized pressure of the pointer input in the range of `0` to `1`, where `0` and `1` represent the minimum and maximum pressure the hardware is capable of detecting, respectively.

  [`tangentialPressure`](pointerevent/tangentialpressure)  The normalized tangential pressure of the pointer input (also known as barrel pressure or cylinder stress) in the range `-1` to `1`, where `0` is the neutral position of the control.

  [`tiltX`](pointerevent/tiltx)  The plane angle (in degrees, in the range of `-90` to `90`) between the Y–Z plane and the plane containing both the pointer (e.g. pen stylus) axis and the Y axis.

  [`tiltY`](pointerevent/tilty)  the plane angle (in degrees, in the range of `-90` to `90`) between the X–Z plane and the plane containing both the pointer (e.g. pen stylus) axis and the X axis.

  [`twist`](pointerevent/twist)  The clockwise rotation of the pointer (e.g. pen stylus) around its major axis in degrees, with a value in the range `0` to `359`.

  [`pointerType`](pointerevent/pointertype)  Indicates the device type that caused the event (mouse, pen, touch, etc.).

  [`isPrimary`](pointerevent/isprimary)  Indicates if the pointer represents the primary pointer of this pointer type.

  

### Event types and Global Event Handlers



Pointer events have ten event types, seven of which have similar semantics to their mouse event counterparts (`down`, `up`, `move`, `over`, `out`, `enter`, and `leave`).

 Below is a short description of each event type.

 

| Event | Description |
| --- | --- |
| [`pointerover`](element/pointerover_event) | Fired when a pointer is moved into an element's [hit test](#hit_test) boundaries. |
| [`pointerenter`](element/pointerenter_event) | Fired when a pointer is moved into the [hit test](#hit_test) boundaries of an element or one of its descendants, including as a result of a pointerdown event from a device that does not support hover (see `pointerdown`). |
| [`pointerdown`](element/pointerdown_event) | Fired when a pointer becomes *active buttons state*. |
| [`pointermove`](element/pointermove_event) | Fired when a pointer changes coordinates. This event is also used if the change in pointer state can not be reported by other events. |
| [`pointerup`](element/pointerup_event) | Fired when a pointer is no longer *active buttons state*. |
| [`pointercancel`](element/pointercancel_event) | A browser fires this event if it concludes the pointer will no longer be able to generate events (for example the related device is deactivated). |
| [`pointerout`](element/pointerout_event) | Fired for several reasons including: pointer is moved out of the [hit test](#hit_test) boundaries of an element; firing the pointerup event for a device that does not support hover (see pointerup); after firing the `pointercancel` event (see `pointercancel`); when a pen stylus leaves the hover range detectable by the digitizer. |
| [`pointerleave`](element/pointerleave_event) | Fired when a pointer is moved out of the [hit test](#hit_test) boundaries of an element. For pen devices, this event is fired when the stylus leaves the hover range detectable by the digitizer. |
| [`gotpointercapture`](element/gotpointercapture_event) | Fired when an element receives pointer capture. |
| [`lostpointercapture`](element/lostpointercapture_event) | Fired after pointer capture is released for a pointer. |



### Element extensions



There are three extensions to the [`Element`](element) interface:

  [`setPointerCapture()`](element/setpointercapture)  Designates a specific element as the *capture target* of future pointer events.

  [`releasePointerCapture()`](element/releasepointercapture)  This method releases (stops) *pointer capture* that was previously set for a specific pointer event.

  

### Navigator extension


The [`Navigator.maxTouchPoints`](navigator/maxtouchpoints) property is used to determine the maximum number of simultaneous touch points that are supported at any single point in time.


Examples
--------


This section contains examples of basic usage of using the pointer events interfaces.


### Registering event handlers



This example registers a handler for every event type for the given element.

 
```
<html lang="en">
  <script>
 function over\_handler(event) {}
 function enter\_handler(event) {}
 function down\_handler(event) {}
 function move\_handler(event) {}
 function up\_handler(event) {}
 function cancel\_handler(event) {}
 function out\_handler(event) {}
 function leave\_handler(event) {}
 function gotcapture\_handler(event) {}
 function lostcapture\_handler(event) {}

 function init() {
 const el = document.getElementById("target");
 // Register pointer event handlers
 el.onpointerover = over\_handler;
 el.onpointerenter = enter\_handler;
 el.onpointerdown = down\_handler;
 el.onpointermove = move\_handler;
 el.onpointerup = up\_handler;
 el.onpointercancel = cancel\_handler;
 el.onpointerout = out\_handler;
 el.onpointerleave = leave\_handler;
 el.gotpointercapture = gotcapture\_handler;
 el.lostpointercapture = lostcapture\_handler;
 }
 </script>
  <body onload="init();">
    <div id="target">Touch me…</div>
  </body>
</html>

```


### Event properties



This example illustrates accessing all of a pointer event's properties.

 
```
<html lang="en">
  <script>
 const id = -1;

 function process\_id(event) {
 // Process this event based on the event's identifier
 }
 function process\_mouse(event) {
 // Process the mouse pointer event
 }
 function process\_pen(event) {
 // Process the pen pointer event
 }
 function process\_touch(event) {
 // Process the touch pointer event
 }
 function process\_tilt(tiltX, tiltY) {
 // Tilt data handler
 }
 function process\_pressure(pressure) {
 // Pressure handler
 }
 function process\_non\_primary(event) {
 // Non primary handler
 }

 function down\_handler(ev) {
 // Calculate the touch point's contact area
 const area = ev.width \* ev.height;

 // Compare cached id with this event's id and process accordingly
 if (id === ev.identifier) process\_id(ev);

 // Call the appropriate pointer type handler
 switch (ev.pointerType) {
 case "mouse":
 process\_mouse(ev);
 break;
 case "pen":
 process\_pen(ev);
 break;
 case "touch":
 process\_touch(ev);
 break;
 default:
 console.log(`pointerType ${ev.pointerType} is not supported`);
 }

 // Call the tilt handler
 if (ev.tiltX !== 0 && ev.tiltY !== 0) process\_tilt(ev.tiltX, ev.tiltY);

 // Call the pressure handler
 process\_pressure(ev.pressure);

 // If this event is not primary, call the non primary handler
 if (!ev.isPrimary) process\_non\_primary(ev);
 }

 function init() {
 const el = document.getElementById("target");
 // Register pointerdown handler
 el.onpointerdown = down\_handler;
 }
 </script>
  <body onload="init();">
    <div id="target">Touch me…</div>
  </body>
</html>

```


Determining the Primary Pointer
-------------------------------



In some scenarios there may be multiple pointers (for example a device with both a touchscreen and a mouse) or a pointer supports multiple contact points (for example a touchscreen that supports multiple finger touches). The application can use the [`isPrimary`](pointerevent/isprimary) property to identify a master pointer among the set of *active pointers* for each pointer type. If an application only wants to support a primary pointer, it can ignore all pointer events that are not primary.

 For mouse there is only one pointer, so it will always be the primary pointer. For touch input, a pointer is considered primary if the user touched the screen when there were no other active touches. For pen and stylus input, a pointer is considered primary if the user's pen initially contacted the screen when there were no other active pens contacting the screen.



Determining button states
-------------------------



Some pointer devices, such as mouse and pen, support multiple buttons and the button presses can be *chorded* i.e. pressing an additional button while another button on the pointer device is already pressed.

 To determine the state of button presses, pointer events uses the [`button`](mouseevent/button) and [`buttons`](mouseevent/buttons) properties of the [`MouseEvent`](mouseevent) interface (that [`PointerEvent`](pointerevent) inherits from).

 The following table provides the values of `button` and `buttons` for the various device button states.

 

| Device Button State | button | buttons |
| --- | --- | --- |
| Neither buttons nor touch/pen contact changed since last event | `-1` | — |
| Mouse move with no buttons pressed, Pen moved while hovering with no buttons pressed | — | `0` |
| Left Mouse, Touch Contact, Pen contact | `0` | `1` |
| Middle Mouse | `1` | `4` |
| Right Mouse, Pen barrel button | `2` | `2` |
| X1 (back) Mouse | `3` | `8` |
| X2 (forward) Mouse | `4` | `16` |
| Pen eraser button | `5` | `32` |

  **Note:** The `button` property indicates a change in the state of the button. However, as in the case of touch, when multiple events occur with one event, all of them have the same value.

 

Capturing the pointer
---------------------



Pointer capture allows events for a particular [`pointer event`](pointerevent) to be re-targeted to a particular element instead of the normal [hit test](#hit_test) at a pointer's location. This can be used to ensure that an element continues to receive pointer events even if the pointer device's contact moves off the element (for example by scrolling).

 The following example shows pointer capture being set on an element.

 
```
<html lang="en">
  <script>
 function downHandler(ev) {
 let el = document.getElementById("target");
 // Element 'target' will receive/capture further events
 el.setPointerCapture(ev.pointerId);
 }

 function init() {
 let el = document.getElementById("target");
 el.onpointerdown = downHandler;
 }
 </script>
  <body onload="init();">
    <div id="target">Touch me…</div>
  </body>
</html>

```
 The following example shows a pointer capture being released (when a [`pointercancel`](element/pointercancel_event) event occurs. The browser does this automatically when a [`pointerup`](element/pointerup_event) or [`pointercancel`](element/pointercancel_event) event occurs.

 
```
<html lang="en">
  <script>
 function downHandler(ev) {
 let el = document.getElementById("target");
 // Element "target" will receive/capture further events
 el.setPointerCapture(ev.pointerId);
 }

 function cancelHandler(ev) {
 let el = document.getElementById("target");
 // Release the pointer capture
 el.releasePointerCapture(ev.pointerId);
 }

 function init() {
 let el = document.getElementById("target");
 // Register pointerdown and pointercancel handlers
 el.onpointerdown = downHandler;
 el.onpointercancel = cancelHandler;
 }
 </script>
  <body onload="init();">
    <div id="target">Touch me…</div>
  </body>
</html>

```


touch-action CSS property
-------------------------



The [`touch-action`](https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action) CSS property is used to specify whether or not the browser should apply its default (*native*) touch behavior (such as zooming or panning) to a region. This property may be applied to all elements except: non-replaced inline elements, table rows, row groups, table columns, and column groups.

 A value of `auto` means the browser is free to apply its default touch behavior (to the specified region) and the value of `none` disables the browser's default touch behavior for the region. The values `pan-x` and `pan-y`, mean that touches that begin on the specified region are only for horizontal and vertical scrolling, respectively. The value `manipulation` means the browser may consider touches that begin on the element are only for scrolling and zooming.

 In the following example, the browser's default touch behavior is disabled for the `div` element.

 
```
<html lang="en">
  <body>
    <div style="touch-action:none;">Can't touch this…</div>
  </body>
</html>

```
 In the following example, default touch behavior is disabled for some `button` elements.

 
```
button#tiny {
  touch-action: none;
}

```
 In the following example, when the `target` element is touched, it will only pan in the horizontal direction.

 
```
#target {
  touch-action: pan-x;
}

```


Compatibility with mouse events
-------------------------------



Although the pointer event interfaces enable applications to create enhanced user experiences on pointer enabled devices, the reality is the vast majority of today's web content is designed to only work with mouse input. Consequently, even if a browser supports pointer events, the browser must still process mouse events so content that assumes mouse-only input will work as is without direct modification. Ideally, a pointer enabled application does not need to explicitly handle mouse input. However, because the browser must process mouse events, there may be some compatibility issues that need to be handled. This section contains information about pointer event and mouse event interaction and the ramifications for application developers.

 The browser *may map generic pointer input to mouse events for compatibility with mouse-based content*. This mapping of events is called *compatibility mouse events*. Authors can prevent the production of certain compatibility mouse events by canceling the pointerdown event but note that:

 * Mouse events can only be prevented when the pointer is down.
* Hovering pointers (e.g. a mouse with no buttons pressed) cannot have their mouse events prevented.
* The `mouseover`, `mouseout`, `mouseenter`, and `mouseleave` events are never prevented (even if the pointer is down).



Best practices
--------------



Here are some *best practices* to consider when using pointer events:

 * Minimize the amount of work performed in event handlers.
* Add the event handlers to a specific target element (rather than the entire document or nodes higher up in the document tree).
* The target element (node) should be large enough to accommodate the largest contact surface area (typically a finger touch). If the target area is too small, touching it could result in firing other events for adjacent elements.



Specifications
--------------




| Specification |
| --- |
| [Pointer Events # pointerevent-interface](https://w3c.github.io/pointerevents/#pointerevent-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PointerEvent` | 55 | 12 | 59 | 1110See [MSDN Pointer events updates](https://msdn.microsoft.com/library/dn304886). | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `Pointer_events` | 55 | 12 | 59 | 1110See [MSDN Pointer events updates](https://msdn.microsoft.com/library/dn304886). | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `altitudeAngle` | 86 | 86 | No | No | 72 | No | 86 | 86 | No | 61 | No | 14.0 |
| `azimuthAngle` | 86 | 86 | No | No | 72 | No | 86 | 86 | No | 61 | No | 14.0 |
| `getCoalescedEvents` | 58 | 79 | 59 | No | 45 | No | 58 | 58 | 79The method always returns an empty array, regardless of the user's actions. | 43 | No | 7.0 |
| `getPredictedEvents` | 77 | 79 | 89 | No | 64 | No | 77 | 77 | 89 | 55 | No | 12.0 |
| `height` | 55 | 12 | 59 | 1110Returns values in screen pixels instead of CSS document pixels. | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `isPrimary` | 55 | 12 | 59 | 10 | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `pointerId` | 55 | 12 | 59 | 10 | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `pointerType` | 55 | 12 | 59 | 1110Returns an integer enumeration instead of a string. | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `pressure` | 55 | 12 | 59 | 1110Returns 0 instead of 0.5 on hardware that doesn't support pressure. | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `tangentialPressure` | 57 | 79 | 59 | No | 44 | 13 | 57 | 57 | 79 | 43 | 13 | 7.0 |
| `tiltX` | 55 | 12 | 59 | 10 | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `tiltY` | 55 | 12 | 59 | 10 | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `twist` | 57 | 18 | 59 | No | 44 | 13 | 57 | 57 | 79 | 43 | 13 | 7.0 |
| `width` | 55 | 12 | 59 | 1110Returns values in screen pixels instead of CSS document pixels. | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |


Some additional values have been defined for the [`CSS touch-action`](https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action) property as part of the [Pointer Events](https://w3c.github.io/pointerevents/) specification, but currently those values have limited implementation support.


Demos and examples
------------------


* [Touch/pointer tests and demos (by Patrick H. Lauke)](https://patrickhlauke.github.io/touch/)

Community
---------


* [Pointer Events Working Group](https://github.com/w3c/pointerevents)
* [Mail list](https://lists.w3.org/Archives/Public/public-pointer-events/)
* [W3C #pointerevents IRC channel](irc://irc.w3.org:6667/)

Related topics and resources
----------------------------


* [Touch Events Standard](https://www.w3.org/TR/touch-events/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events>

Prioritized Task Scheduling API
===============================



 **Note:** This feature is available in [Web Workers](web_workers_api)

  The **Prioritized Task Scheduling API** provides a standardized way to prioritize all tasks belonging to an application, whether they defined in a website developer's code, or in third party libraries and frameworks.

  The [task priorities](#task-priorities) are very coarse-grained, and are based around whether tasks block user interaction, or otherwise impact the user experience, or can run in the background. Developers and frameworks may implement more fine-grained prioritization schemes within the broad categories defined by the API. 

 The API is promise-based and supports the ability to set and change task priorities, to delay tasks being added to the scheduler, to abort tasks, and to monitor for priority change and abort events.



Concepts and Usage
------------------


 The API is available in both window and worker threads using the `scheduler` property on the global object. This property can be tested to feature-check for API support. 


### Overview



The main API method is [`Scheduler.postTask()`](scheduler/posttask), which takes a callback function ("the task") and returns a promise that resolves with the return value of the function, or rejects with an error.

  The simplest form of the API is as shown below. This creates a task with default priority [`user-visible`](#user-visible) that has a fixed priority and cannot be aborted. 

 
```
const promise = scheduler.postTask(myTask);

```
  Because the method returns a promise you can wait on its resolution asynchronously using `then`, and catch errors thrown by the task callback function (or when the task is aborted) using `catch`. The callback function can be any kind of function (below we demonstrate an arrow function). 

 
```
scheduler
  .postTask(() => "Task executing")
  // Promise resolved: log task result when promise resolves
  .then((taskResult) => console.log(`${taskResult}`))
  // Promise rejected: log AbortError or errors thrown by task
  .catch((error) => console.error(`Error: ${error}`));

```
 The same task might be waited on using `await`/`async` as shown below (note, this is run in an [Immediately Invoked Function Expression (IIFE)](https://developer.mozilla.org/en-US/docs/Glossary/IIFE)):

 
```
(async () => {
  try {
    const result = await scheduler.postTask(() => "Task executing");
    console.log(result);
  } catch (error) {
    // Log AbortError or error thrown in task function
    console.error(`Error: ${error}`);
  }
})();

```
  You can also specify an options object to the `postTask()` method if you want to change the default behavior. The options are: 

 * `priority` This allows you to specify a particular immutable priority. Once set, the priority cannot be changed.
* `signal` This allows you to specify a signal, which may be either a [`TaskSignal`](tasksignal) or [`AbortSignal`](abortsignal) The signal is associated with a controller, which can be used to abort the task. A [`TaskSignal`](tasksignal) can also be used to set and change the task priority if the [task is mutable](#mutable_and_immutable_task_priority).
* `delay` This allows you to specify the delay before the task is added for scheduling, in milliseconds.

 The same example as above with a priority option would look like this:

 
```
scheduler
  .postTask(() => "Task executing", { priority: "user-blocking" })
  .then((taskResult) => console.log(`${taskResult}`)) // Log the task result
  .catch((error) => console.error(`Error: ${error}`)); // Log any errors

```


### Task priorities



Scheduled tasks are run in priority order, followed by the order that they were added to the scheduler queue.

 There are just three priorities, which are listed below (ordered from highest to lowest):

  `user-blocking`   Tasks that stop users from interacting with the page. This includes rendering the page to the point where it can be used, or responding to user input. 

  `user-visible`   Tasks that are visible to the user but not necessarily blocking user actions. This might include rendering non-essential parts of the page, such as non-essential images or animations. 

 This is the default priority.

  `background`   Tasks that are not time-critical. This might include log processing or initializing third party libraries that aren't required for rendering. 

  

### Mutable and immutable task priority



 There are many use cases where the task priority never needs to change, while for others it does. For example fetching an image might change from a `background` task to `user-visible` as a carousel is scrolled into the viewing area. 

 Task priorities can be set as static (immutable) or dynamic (modifiable) depending on the arguments passed to [`Scheduler.postTask()`](scheduler/posttask).

  Task priority is immutable if a value is specified in the `options.priority` argument. The given value will be used for the task priority and cannot be changed. 

  The priority is modifiable only if a [`TaskSignal`](tasksignal) is passed to the `options.signal` argument **and** `options.priority` is **not set**. In this case the task will take its initial priority from the `signal` priority, and the priority can subsequently be changed by calling [`TaskController.setPriority()`](taskcontroller/setpriority) on the controller associated with the signal. 

 If the priority is not set with `options.priority` or by passing a [`TaskSignal`](tasksignal) to `options.signal` then it defaults to `user-visible` (and is by definition immutable).

  Note that a task that needs to be aborted must set `options.signal` to either [`TaskSignal`](tasksignal) or [`AbortSignal`](abortsignal). However for a task with an immutable priority, [`AbortSignal`](abortsignal) more clearly indicates that the task priority cannot be changed using the signal. 



Interfaces
----------



 [`Scheduler`](scheduler)   Interface with method for adding prioritized tasks to be scheduled. An object of this interface is available on the [`Window`](window) or [`WorkerGlobalScope`](workerglobalscope) global objects (`this.scheduler`). 

  [`TaskController`](taskcontroller)  Interface that supports both aborting a task and changing its priority.

  [`TaskSignal`](tasksignal)  Interface for a signal object that allows you to abort a task and change its priority, if required, using a [`TaskController`](taskcontroller) object.

  [`TaskPriorityChangeEvent`](taskprioritychangeevent)  The interface for the [`prioritychange`](tasksignal/prioritychange_event) event, sent when the priority for a task is changed.

    **Note:** If the [task priority](#task_priorities) never needs to be changed, you can use an [`AbortController`](abortcontroller) and its associated [`AbortSignal`](abortsignal) instead of [`TaskController`](taskcontroller) and [`TaskSignal`](tasksignal).

 

### Extensions to other interfaces



The Prioritized Task Scheduling API extends the following APIs, adding the listed features:

  [`scheduler`](window/scheduler)   This property is the entry point for using this API. It is implemented on [`Window`](window#scheduler) and [`WorkerGlobalScope`](workerglobalscope#scheduler), making an instance of [`Scheduler`](scheduler) available through `this` in most scopes. 

  

Examples
--------



 Note that the examples below use `mylog()` to write to a text area. The code for the log area and method is generally hidden in order to not to distract from more relevant code. 

 
```
// hidden logger code - simplifies example
let log = document.getElementById("log");
function mylog(text) {
  log.textContent += `${text}\n`;
}

```


### Feature checking



Check whether prioritized task scheduling is supported by testing for the [`scheduler`](window/scheduler) property in the global "`this`" exposed to the current scope.

 The code below prints "Feature: Supported" if the API is supported on this browser.

 
```
// Check that feature is supported
if ("scheduler" in this) {
  mylog("Feature: Supported");
} else {
  mylog("Feature: NOT Supported");
}

```



### Basic usage



 Tasks are posted using [`Scheduler.postTask()`](scheduler/posttask), specifying a callback function (task) in the first argument, and an optional second argument that can be used to specify a task priority, signal, and/or delay. The method returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with the return value of the callback function, or rejects with either an abort error or an error thrown in the function. 

  Because it returns a promise, [`Scheduler.postTask()`](scheduler/posttask) can be [chained with other promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#chained_promises). Below we show how to wait on the promise to resolve using [`then`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then). This uses the default priority (`user-visible`). 

 
```
// A function that defines a task
function myTask() {
  return "Task 1: user-visible";
}

if ("scheduler" in this) {
  // Post task with default priority: 'user-visible' (no other options)
  // When the task resolves, Promise.then() logs the result.
  scheduler.postTask(myTask).then((taskResult) => mylog(`${taskResult}`));
}

```
  The method can also be used with [`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) inside an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). The code below shows how you might use this approach to wait on a `user-blocking` task. 

 
```
function myTask2() {
  return "Task 2: user-blocking";
}

async function runTask2() {
  const result = await scheduler.postTask(myTask2, {
    priority: "user-blocking",
  });
  mylog(result); // Logs 'Task 2: user-blocking'.
}
runTask2();

```
  In some cases you might not need to wait on completion at all. For simplicity many of the examples here simply log the result as the task executes. 

 
```
// A function that defines a task
function myTask3() {
  mylog("Task 3: user-visible");
}

if ("scheduler" in this) {
  // Post task and log result when it runs
  scheduler.postTask(myTask3);
}

```
  The log below shows the output of the three tasks above. Note that the order they are run depends on the priority first, and then the declaration order. 




### Permanent priorities



 [Task priorities](#task_priorities) may be set using `priority` parameter in the optional second argument. Priorities that are set in this way are [immutable](#mutable_and_immutable_task_priority) (cannot be changed). 

  Below we post two groups of three tasks, each member in reverse order of priority. The final task has the default priority. When run, each task simply logs it's expected order (we're not waiting on the result because we don't need to in order to show execution order). 

 
```
if ("scheduler" in this) {
  // three tasks, in reverse order of priority
  scheduler.postTask(() => mylog("bckg 1"), { priority: "background" });
  scheduler.postTask(() => mylog("usr-vis 1"), { priority: "user-visible" });
  scheduler.postTask(() => mylog("usr-blk 1"), { priority: "user-blocking" });

  // three more tasks, in reverse order of priority
  scheduler.postTask(() => mylog("bckg 2"), { priority: "background" });
  scheduler.postTask(() => mylog("usr-vis 2"), { priority: "user-visible" });
  scheduler.postTask(() => mylog("usr-blk 2"), { priority: "user-blocking" });

  // Task with default priority: user-visible
  scheduler.postTask(() => mylog("usr-vis 3 (default)"));
}

```
 The output below shows that the tasks are executed in priority order, and then declaration order.




### Changing task priorities



 [Task priorities](#task_priorities) can also take their initial value from a [`TaskSignal`](tasksignal) passed to `postTask()` in the optional second argument. If set in this way, the priority of the task [can then be changed](#mutable_and_immutable_task_priority) using the controller associated with the signal. 

  **Note:** Setting and changing task priorities using a signal only works when the `options.priority` argument to `postTask()` is not set, and when the `options.signal` is a [`TaskSignal`](tasksignal) (and not an [`AbortSignal`](abortsignal)).

  The code below first shows how to create a [`TaskController`](taskcontroller), setting the initial priority of its signal to `user-blocking` in the [`TaskController()` constructor](taskcontroller/taskcontroller).

  The code then uses `addEventListener()` to add an event listener to the controller's signal (we could alternatively use the `TaskSignal.onprioritychange` property to add an event handler). The event handler uses [`previousPriority`](taskprioritychangeevent/previouspriority) on the event to get the original priority and [`TaskSignal.priority`](tasksignal/priority) on the event target to get the new/current priority. 

 The task is then posted, passing in the signal, and then we immediately change the priority to `background` by calling [`TaskController.setPriority()`](taskcontroller/setpriority) on the controller.

 
```
if ("scheduler" in this) {
  // Create a TaskController, setting its signal priority to 'user-blocking'
  const controller = new TaskController({ priority: "user-blocking" });

  // Listen for 'prioritychange' events on the controller's signal.
  controller.signal.addEventListener("prioritychange", (event) => {
    const previousPriority = event.previousPriority;
    const newPriority = event.target.priority;
    mylog(`Priority changed from ${previousPriority} to ${newPriority}.`);
  });

  // Post task using the controller's signal.
  // The signal priority sets the initial priority of the task
  scheduler.postTask(() => mylog("Task 1"), { signal: controller.signal });

  // Change the priority to 'background' using the controller
  controller.setPriority("background");
}

```
  The output below demonstrates that the priority was successfully changed to `background` from `user-blocking`. Note that in this case the priority is changed before the task is executed, but it could equally have been changed while the task was running. 




### Aborting tasks



 Tasks can be aborted using either [`TaskController`](taskcontroller) and [`AbortController`](abortcontroller), in exactly the same way. The only difference is that you must use [`TaskController`](taskcontroller) if you also want to set the task priority. 

  The code below creates a controller and passes its signal to the task. The task is then immediately aborted. This causes the promise to be rejected with an `AbortError`, which is caught in the `catch` block and logged. Note that we could also have listened for the [`abort` event](abortsignal/abort_event) fired on the [`TaskSignal`](tasksignal) or [`AbortSignal`](abortsignal) and logged the abort there. 

 
```
if ("scheduler" in this) {
  // Declare a TaskController with default priority
  const abortTaskController = new TaskController();
  // Post task passing the controller's signal
  scheduler
    .postTask(() => mylog("Task executing"), {
      signal: abortTaskController.signal,
    })
    .then((taskResult) => mylog(`${taskResult}`)) // This won't run!
    .catch((error) => mylog(`Error: ${error}`)); // Log the error

  // Abort the task
  abortTaskController.abort();
}

```
 The log below shows the aborted task.




### Delaying tasks



 Tasks can be delayed by specifying an integer number of milliseconds in the `options.delay` parameter to `postTask()`. This effectively adds the task to the prioritized queue on a timeout, as might be created using [`setTimeout()`](settimeout). The `delay` is the minimum amount of time before the task is added to the scheduler; it may be longer. 

 The code below shows two tasks added (as arrow functions) with a delay.

 
```
if ("scheduler" in this) {
  // Post task as arrow function with delay of 2 seconds
  scheduler
    .postTask(() => "Task delayed by 2000ms", { delay: 2000 })
    .then((taskResult) => mylog(`${taskResult}`));
  scheduler
    .postTask(() => "Next task should complete in about 2000ms", { delay: 1 })
    .then((taskResult) => mylog(`${taskResult}`));
}

```
  Refresh the page. Note that the second string appears in log after about 2 seconds. 




Specifications
--------------




| Specification |
| --- |
| [Prioritized Task Scheduling # scheduler](https://wicg.github.io/scheduling-apis/#scheduler) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Prioritized_Task_Scheduling_API` | 94 | 94 | 101 | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `postTask` | 94 | 94 | 101 | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |


See also
--------


* [Building a Faster Web Experience with the postTask Scheduler](https://medium.com/airbnb-engineering/building-a-faster-web-experience-with-the-posttask-scheduler-276b83454e91) (Airbnb blog)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Prioritized_Task_Scheduling_API>

Server-sent events
==================



Traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. With server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as *[Events](event) + data* inside the web page.


 **Note:** This feature is available in [Web Workers](web_workers_api)

   **Note:** Firefox does not currently support the use of server-sent events in service workers (it does support them in dedicated and shared workers). See [Firefox bug 1681218](https://bugzil.la/1681218).

 

Concepts and usage
------------------


To learn how to use server-sent events, see our article [Using server-sent events](server-sent_events/using_server-sent_events).


Interfaces
----------


 [`EventSource`](eventsource)  Defines all the features that handle connecting to a server, receiving events/data, errors, closing a connection, etc.

  
Examples
--------


* [Simple SSE demo using PHP](https://github.com/mdn/dom-examples/tree/main/server-sent-events)

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # server-sent-events](https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events) |


See also
--------


### Tools


* [Mercure: a real-time communication protocol (publish-subscribe) built on top of SSE](https://mercure.rocks)
* [EventSource polyfill for Node.js](https://github.com/EventSource/eventsource)
* Remy Sharp's [EventSource polyfill](https://github.com/remy/polyfills/blob/master/EventSource.js)
* Yaffle's [EventSource polyfill](https://github.com/Yaffle/EventSource)
* Rick Waldron's [jquery plugin](https://github.com/rwaldron/jquery.eventsource)
* intercooler.js [declarative SSE support](https://intercoolerjs.org/docs.html#sse)

### Related Topics


* [AJAX](https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX)
* [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript)
* [WebSockets](websockets_api)

### Other resources


* A [Twitter like application](https://hacks.mozilla.org/2011/06/a-wall-powered-by-eventsource-and-server-sent-events/) powered by server-sent events and [its code on GitHub](https://github.com/mozilla/webowonder-demos/tree/master/demos/friends%20timeline).
* [HTML5 and Server-sent events](https://dsheiko.com/weblog/html5-and-server-sent-events/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events>

Service Worker API
==================


Service workers essentially act as proxy servers that sit between web applications, the browser, and the network (when available). They are intended, among other things, to enable the creation of effective offline experiences, intercept network requests and take appropriate action based on whether the network is available, and update assets residing on the server. They will also allow access to push notifications and background sync APIs.


Service worker concepts and usage
---------------------------------



A service worker is an event-driven <worker> registered against an origin and a path. It takes the form of a JavaScript file that can control the web-page/site that it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion to give you complete control over how your app behaves in certain situations (the most obvious one being when the network is not available).

 A service worker is run in a worker context: it therefore has no DOM access, and runs on a different thread to the main JavaScript that powers your app, so it is non-blocking. It is designed to be fully async; as a consequence, APIs such as synchronous [XHR](xmlhttprequest) and [Web Storage](web_storage_api) can't be used inside a service worker.

  Service workers can't import JavaScript module dynamically, and [`import()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import#browser_compatibility) will throw if it is called in a service worker global scope. Static import using the [`import`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) statement is allowed. 

 Service workers only run over HTTPS, for security reasons. Most significantly, HTTP connections are susceptible to malicious code injection by [man in the middle](https://developer.mozilla.org/en-US/docs/Glossary/MitM) attacks, and such attacks could be worse if allowed access to these powerful APIs. In Firefox, service worker APIs are also hidden and cannot be used when the user is in [private browsing mode](https://support.mozilla.org/en-US/kb/private-browsing-use-firefox-without-history).

  **Note:** On Firefox, for testing you can run service workers over HTTP (insecurely); simply check the **Enable Service Workers over HTTP (when toolbox is open)** option in the Firefox Devtools options/gear menu.

   **Note:** Unlike previous attempts in this area such as [AppCache](https://alistapart.com/article/application-cache-is-a-douchebag/), service workers don't make assumptions about what you are trying to do, but then break when those assumptions are not exactly right. Instead, service workers give you much more granular control.

   **Note:** Service workers make heavy use of [promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), as generally they will wait for responses to come through, after which they will respond with a success or failure action. The promises architecture is ideal for this.

 

### Registration


A service worker is first registered using the [`ServiceWorkerContainer.register()`](serviceworkercontainer/register) method. If successful, your service worker will be downloaded to the client and attempt installation/activation (see below) for URLs accessed by the user inside the whole origin, or inside a subset specified by you.


### Download, install and activate



At this point, your service worker will observe the following lifecycle:

 1. Download
2. Install
3. Activate

 The service worker is immediately downloaded when a user first accesses a service worker–controlled site/page.

 After that, it is updated when:

 * A navigation to an in-scope page occurs.
* An event is fired on the service worker and it hasn't been downloaded in the last 24 hours.

 Installation is attempted when the downloaded file is found to be new — either different to an existing service worker (byte-wise compared), or the first service worker encountered for this page/site.

 If this is the first time a service worker has been made available, installation is attempted, then after a successful installation, it is activated.

 If there is an existing service worker available, the new version is installed in the background, but not yet activated — at this point it is called the *worker in waiting*. It is only activated when there are no longer any pages loaded that are still using the old service worker. As soon as there are no more pages to be loaded, the new service worker activates (becoming the *active worker*). Activation can happen sooner using [`ServiceWorkerGlobalScope.skipWaiting()`](serviceworkerglobalscope/skipwaiting) and existing pages can be claimed by the active worker using [`Clients.claim()`](clients/claim).

 You can listen for the [`install`](serviceworkerglobalscope/install_event) event; a standard action is to prepare your service worker for usage when this fires, for example by creating a cache using the built in storage API, and placing assets inside it that you'll want for running your app offline.

 There is also an [`activate`](serviceworkerglobalscope/activate_event) event. The point where this event fires is generally a good time to clean up old caches and other things associated with the previous version of your service worker.

 Your service worker can respond to requests using the [`FetchEvent`](fetchevent) event. You can modify the response to these requests in any way you want, using the [`FetchEvent.respondWith()`](fetchevent/respondwith) method.

  **Note:** Because `install`/`activate` events could take a while to complete, the service worker spec provides a [`waitUntil()`](extendableevent/waituntil) method. Once it is called on `install` or `activate` events with a promise, functional events such as `fetch` and `push` will wait until the promise is successfully resolved.

  For a complete tutorial to show how to build up your first basic example, read [Using Service Workers](service_worker_api/using_service_workers).



Other use case ideas
--------------------



Service workers are also intended to be used for such things as:

 * Background data synchronization.
* Responding to resource requests from other origins.
* Receiving centralized updates to expensive-to-calculate data such as geolocation or gyroscope, so multiple pages can make use of one set of data.
* Client-side compiling and dependency management of CoffeeScript, less, CJS/AMD modules, etc. for development purposes.
* Hooks for background services.
* Custom templating based on certain URL patterns.
* Performance enhancements, for example pre-fetching resources that the user is likely to need in the near future, such as the next few pictures in a photo album.
* API mocking.

 In the future, service workers will be able to do a number of other useful things for the web platform that will bring it closer towards native app viability. Interestingly, other specifications can and will start to make use of the service worker context, for example:

 * [Background synchronization](https://github.com/WICG/background-sync): Start up a service worker even when no users are at the site, so caches can be updated, etc.
* [Reacting to push messages](push_api): Start up a service worker to send users a message to tell them new content is available.
* Reacting to a particular time & date.
* Entering a geo-fence.



Interfaces
----------


 [`Cache`](cache)  Represents the storage for [`Request`](request) / [`Response`](response) object pairs that are cached as part of the [`ServiceWorker`](serviceworker) life cycle.

  [`CacheStorage`](cachestorage)  Represents the storage for [`Cache`](cache) objects. It provides a master directory of all the named caches that a [`ServiceWorker`](serviceworker) can access, and maintains a mapping of string names to corresponding [`Cache`](cache) objects.

  [`Client`](client)  Represents the scope of a service worker client. A service worker client is either a document in a browser context or a [`SharedWorker`](sharedworker), which is controlled by an active worker.

  [`Clients`](clients)  Represents a container for a list of [`Client`](client) objects; the main way to access the active service worker clients at the current origin.

  [`ExtendableEvent`](extendableevent)  Extends the lifetime of the `install` and `activate` events dispatched on the [`ServiceWorkerGlobalScope`](serviceworkerglobalscope), as part of the service worker lifecycle. This ensures that any functional events (like [`FetchEvent`](fetchevent)) are not dispatched to the [`ServiceWorker`](serviceworker), until it upgrades database schemas, and deletes outdated cache entries, etc.

  [`ExtendableMessageEvent`](extendablemessageevent)  The event object of a [`message`](serviceworkerglobalscope/message_event) event fired on a service worker (when a channel message is received on the [`ServiceWorkerGlobalScope`](serviceworkerglobalscope) from another context) — extends the lifetime of such events.

  [`FetchEvent`](fetchevent)  The parameter passed into the [`onfetch`](serviceworkerglobalscope/fetch_event) handler, `FetchEvent` represents a fetch action that is dispatched on the [`ServiceWorkerGlobalScope`](serviceworkerglobalscope) of a [`ServiceWorker`](serviceworker). It contains information about the request and resulting response, and provides the [`FetchEvent.respondWith()`](fetchevent/respondwith) method, which allows us to provide an arbitrary response back to the controlled page.

  
[`InstallEvent`](installevent)  Deprecated   Non-standard 
  The parameter passed into the [`oninstall`](serviceworkerglobalscope/install_event) handler, the `InstallEvent` interface represents an install action that is dispatched on the [`ServiceWorkerGlobalScope`](serviceworkerglobalscope) of a [`ServiceWorker`](serviceworker). As a child of [`ExtendableEvent`](extendableevent), it ensures that functional events such as [`FetchEvent`](fetchevent) are not dispatched during installation.

  [`NavigationPreloadManager`](navigationpreloadmanager)  Provides methods for managing the preloading of resources with a service worker.

  [`Navigator.serviceWorker`](navigator/serviceworker)  Returns a [`ServiceWorkerContainer`](serviceworkercontainer) object, which provides access to registration, removal, upgrade, and communication with the [`ServiceWorker`](serviceworker) objects for the [associated document](https://html.spec.whatwg.org/multipage/browsers.html#concept-document-window).

  [`NotificationEvent`](notificationevent)  The parameter passed into the [`onnotificationclick`](serviceworkerglobalscope/notificationclick_event) handler, the `NotificationEvent` interface represents a notification click event that is dispatched on the [`ServiceWorkerGlobalScope`](serviceworkerglobalscope) of a [`ServiceWorker`](serviceworker).

  [`ServiceWorker`](serviceworker)  Represents a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same `ServiceWorker` object.

  [`ServiceWorkerContainer`](serviceworkercontainer)  Provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister, and update service workers, and access the state of service workers and their registrations.

  [`ServiceWorkerGlobalScope`](serviceworkerglobalscope)  Represents the global execution context of a service worker.

  [`MessageEvent`](messageevent)  Represents a message sent to a [`ServiceWorkerGlobalScope`](serviceworkerglobalscope).

  [`ServiceWorkerRegistration`](serviceworkerregistration)  Represents a service worker registration.

  
[`SyncEvent`](syncevent)  Experimental 
  The SyncEvent interface represents a sync action that is dispatched on the [`ServiceWorkerGlobalScope`](serviceworkerglobalscope) of a ServiceWorker.

  
[`SyncManager`](syncmanager)  Experimental 
  Provides an interface for registering and listing sync registrations.

  [`WindowClient`](windowclient)  Represents the scope of a service worker client that is a document in a browser context, controlled by an active worker. This is a special type of [`Client`](client) object, with some additional methods and properties available.

  
Specifications
--------------




| Specification |
| --- |
| [Service Workers](https://w3c.github.io/ServiceWorker/)  |


See also
--------


* [ServiceWorker Cookbook](https://github.com/mdn/serviceworker-cookbook)
* [Using Service Workers](service_worker_api/using_service_workers)
* [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker)
* [Is ServiceWorker ready?](https://jakearchibald.github.io/isserviceworkerready/)
* [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API>

Streams API
===========



The Streams API allows JavaScript to programmatically access streams of data received over the network and process them as desired by the developer.


 **Note:** This feature is available in [Web Workers](web_workers_api)

 

Concepts and usage
------------------



Streaming involves breaking a resource that you want to receive over a network down into small chunks, then processing it bit by bit. This is something browsers do anyway when receiving assets to be shown on webpages — videos buffer and more is gradually available to play, and sometimes you'll see images display gradually as more is loaded.

 But this has never been available to JavaScript before. Previously, if we wanted to process a resource of some kind (be it a video, or a text file, etc.), we'd have to download the entire file, wait for it to be deserialized into a suitable format, then process the whole lot after it is fully received.

 With Streams being available to JavaScript, this all changes — you can now start processing raw data with JavaScript bit by bit as soon as it is available on the client-side, without needing to generate a buffer, string, or blob.

  ![The basic concept of the stream API is data is fetched from the network in several data packets. The data is processed, and then sent to the browser in a stream of data packets.] 

 There are more advantages too — you can detect when streams start or end, chain streams together, handle errors and cancel streams as required, and react to the speed the stream is being read at.

 The basic usage of Streams hinges around making responses available as streams. For example, the response body returned by a successful [fetch request](fetch) can be exposed as a [`ReadableStream`](readablestream), and you can then read it using a reader created with [`ReadableStream.getReader()`](readablestream/getreader), cancel it with [`ReadableStream.cancel()`](readablestream/cancel), etc.

 More complicated uses involve creating your own stream using the [`ReadableStream()`](readablestream/readablestream) constructor, for example to process data inside a [service worker](service_worker_api).

 You can also write data to streams using [`WritableStream`](writablestream).

  **Note:** You can find a lot more details about the theory and practice of streams in our articles — [Streams API concepts](streams_api/concepts), [Using readable streams](streams_api/using_readable_streams), [Using readable byte streams](streams_api/using_readable_byte_streams), and [Using writable streams](streams_api/using_writable_streams).

 

Stream interfaces
-----------------


### Readable streams


 [`ReadableStream`](readablestream)  Represents a readable stream of data. It can be used to handle response streams of the [Fetch API](fetch_api), or developer-defined streams (e.g. a custom [`ReadableStream()`](readablestream/readablestream) constructor).

  [`ReadableStreamDefaultReader`](readablestreamdefaultreader)  Represents a default reader that can be used to read stream data supplied from a network (e.g. a fetch request).

  [`ReadableStreamDefaultController`](readablestreamdefaultcontroller)  Represents a controller allowing control of a [`ReadableStream`](readablestream)'s state and internal queue. Default controllers are for streams that are not byte streams.

  
### Writable streams


 [`WritableStream`](writablestream)  Provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing.

  [`WritableStreamDefaultWriter`](writablestreamdefaultwriter)  Represents a default writable stream writer that can be used to write chunks of data to a writable stream.

  [`WritableStreamDefaultController`](writablestreamdefaultcontroller)  Represents a controller allowing control of a [`WritableStream`](writablestream)'s state. When constructing a `WritableStream`, the underlying sink is given a corresponding `WritableStreamDefaultController` instance to manipulate.

  
### Transform Streams


 [`TransformStream`](transformstream)  Represents a set of transformable data.

  [`TransformStreamDefaultController`](transformstreamdefaultcontroller)  Provides methods to manipulate the [`ReadableStream`](readablestream) and [`WritableStream`](writablestream) associated with a transform stream.

  
### Related stream APIs and operations


 [`ByteLengthQueuingStrategy`](bytelengthqueuingstrategy)  Provides a built-in byte length queuing strategy that can be used when constructing streams.

  [`CountQueuingStrategy`](countqueuingstrategy)  Provides a built-in chunk counting queuing strategy that can be used when constructing streams.

  
### Extensions to other APIs


 [`Request`](request)  When a new `Request` object is constructed, you can pass it a [`ReadableStream`](readablestream) in the `body` property of its `RequestInit` dictionary. This `Request` could then be passed to a [`fetch()`](fetch) to commence fetching the stream.

  [`Response.body`](response/body)  The response body returned by a successful [fetch request](fetch) is exposed by default as a [`ReadableStream`](readablestream), and can have a reader attached to it, etc.

  
### ByteStream-related interfaces


 [`ReadableStreamBYOBReader`](readablestreambyobreader)  Represents a BYOB ("bring your own buffer") reader that can be used to read stream data supplied by the developer (e.g. a custom [`ReadableStream()`](readablestream/readablestream) constructor).

  [`ReadableByteStreamController`](readablebytestreamcontroller)  Represents a controller allowing control of a [`ReadableStream`](readablestream)'s state and internal queue. Byte stream controllers are for byte streams.

  [`ReadableStreamBYOBRequest`](readablestreambyobrequest)  Represents a pull into request in a [`ReadableByteStreamController`](readablebytestreamcontroller).

  
Examples
--------



We have created a directory of examples to go along with the Streams API documentation — see [mdn/dom-examples/streams](https://github.com/mdn/dom-examples/tree/main/streams). The examples are as follows:

 * [Simple stream pump](https://mdn.github.io/dom-examples/streams/simple-pump/): This example shows how to consume a ReadableStream and pass its data to another.
* [Grayscale a PNG](https://mdn.github.io/dom-examples/streams/grayscale-png/): This example shows how a ReadableStream of a PNG can be turned into grayscale.
* [Simple random stream](https://mdn.github.io/dom-examples/streams/simple-random-stream/): This example shows how to use a custom stream to generate random strings, enqueue them as chunks, and then read them back out again.
* [Simple tee example](https://mdn.github.io/dom-examples/streams/simple-tee-example/): This example extends the Simple random stream example, showing how a stream can be teed and both resulting streams can be read independently.
* [Simple writer](https://mdn.github.io/dom-examples/streams/simple-writer/): This example shows how to write to a writable stream, then decode the stream and write the contents to the UI.
* [Unpack chunks of a PNG](https://mdn.github.io/dom-examples/streams/png-transform-stream/): This example shows how [`pipeThrough()`](readablestream/pipethrough) can be used to transform a ReadableStream into a stream of other data types by transforming a data of a PNG file into a stream of PNG chunks.

 Examples from other developers:

 * [Progress Indicators with Streams, Service Workers, & Fetch](https://fetch-progress.anthum.com/).



Specifications
--------------




| Specification |
| --- |
| [Streams Standard # rs-class](https://streams.spec.whatwg.org/#rs-class) |
| [Streams Standard # ws-class](https://streams.spec.whatwg.org/#ws-class) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `WritableStream` | 59 | 16 | 100 | No | 47 | 14.1 | 59 | 59 | 100 | 44 | 14.5 | 7.0 |
| `Streams_API` | 59 | 16 | 100 | No | 47 | 14.1 | 59 | 59 | 100 | 44 | 14.5 | 7.0 |
| `abort` | 59 | 16 | 100 | No | 47 | 14.1 | 59 | 59 | 100 | 44 | 14.5 | 7.0 |
| `close` | 81 | 81 | 100 | No | 68 | 14.1 | 81 | 81 | 100 | 58 | 14.5 | 13.0 |
| `getWriter` | 59 | 16 | 100 | No | 47 | 14.1 | 59 | 59 | 100 | 44 | 14.5 | 7.0 |
| `locked` | 59 | 16 | 100 | No | 47 | 14.1 | 59 | 59 | 100 | 44 | 14.5 | 7.0 |
| `transferable` | 87 | 87 | 103 | No | 73 | No | 87 | 87 | 103 | 62 | No | 14.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@asyncIterator` | No | No | 110 | No | No | No | No | No | 110 | No | No | No |
| `ReadableStream` | 52 | 79 | 65 | No | 39 | 10.1 | 52 | 52 | 65 | 41 | 10.3 | 6.0 |
| `Streams_API` | 43 | 14 | 65 | No | 30 | 10.1 | 43 | 43 | 65 | 30 | 10.3 | 4.0 |
| `cancel` | 43 | 14 | 65 | No | 30 | 10.1 | 43 | 43 | 65 | 30 | 10.3 | 4.0 |
| `getReader` | 43 | 14 | 65 | No | 30 | 10.1 | 43 | 43 | 65 | 30 | 10.3 | 4.0 |
| `locked` | 52 | 14 | 65 | No | 39 | 10.1 | 52 | 52 | 65 | 41 | 10.3 | 6.0 |
| `pipeThrough` | 59 | 79 | 102 | No | 46 | 10.1 | 59 | 59 | 102 | 43 | 10.3 | 7.0 |
| `pipeTo` | 59 | 79 | 100 | No | 46 | 10.1 | 59 | 59 | 100 | 43 | 10.3 | 7.0 |
| `tee` | 52 | 79 | 65 | No | 39 | 10.1 | 52 | 52 | 65 | 41 | 10.3 | 6.0 |
| `transferable` | 87 | 87 | 103 | No | 73 | No | 87 | 87 | 103 | 62 | No | 14.0 |
| `values` | No | No | 110 | No | No | No | No | No | 110 | No | No | No |


### api.ReadableStream


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.WritableStream


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


See also
--------


* [Streams API concepts](streams_api/concepts)
* [Using readable streams](streams_api/using_readable_streams)
* [Using readable byte streams](streams_api/using_readable_byte_streams)
* [Using writable streams](streams_api/using_writable_streams)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Streams_API>

Storage API
===========



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

  **Note:** This feature is available in [Web Workers](web_workers_api)

  The [Storage Standard](https://storage.spec.whatwg.org) defines a shared storage system designed to be used by all APIs and technologies that websites can use to store data in a user's browser.

 The data stored for a website which is managed by the Storage Standard usually includes [IndexedDB databases](indexeddb_api) and [Cache API data](cache), but may include other kind of site-accessible data such as [Web Storage API data](web_storage_api).

 The Storage API gives websites the ability to find out how much space they can use, how much they are already using, and even control whether or not they need to be alerted before the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) disposes of data in order to make room for other things.

 This article gives an overview of the way user agents store and maintain websites' data. For more information about storage limits and eviction, see [Browser storage quotas and eviction criteria](storage_api/storage_quotas_and_eviction_criteria).

 This article also gives an overview of the [`StorageManager`](storagemanager) interface used to estimate available storage for a site.



Storage buckets
---------------



The storage system described by the Storage Standard, where site data is stored, usually consists of a single *bucket* for each [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin).

 In essence, every website has its own storage space into which its data gets placed. In some cases however, user agents may decide to store a single origin's data in multiple different buckets, for example when this origin is embedded in different third-party origins.

 To learn more, see [How browsers separate data from different websites?](storage_api/storage_quotas_and_eviction_criteria#how_browsers_separate_data_from_different_websites)



Bucket modes
------------



Each site storage bucket has a *mode* that describes the data retention policy for that bucket. There are two modes:

  `"best-effort"`  The user agent will try to retain the data contained in the bucket for as long as it can, *but will not warn users* if storage space runs low and it becomes necessary to clear the bucket in order to relieve the storage pressure.

  `"persistent"`  The user agent will retain the data as long as possible, clearing all `"best-effort"` buckets before considering clearing a bucket marked `"persistent"`. If it becomes necessary to consider clearing persistent buckets, the user agent will notify the user and provide a way to clear one or more persistent buckets as needed.

   You can change an origin's storage bucket mode by using the [`navigator.storage.persist()`](storagemanager/persist) method, which requires the `"persistent-storage"` [user permission](permissions_api).

 
```
if (navigator.storage && navigator.storage.persist) {
  navigator.storage.persist().then((persistent) => {
    if (persistent) {
      console.log("Storage will not be cleared except by explicit user action");
    } else {
      console.log("Storage may be cleared by the UA under storage pressure.");
    }
  });
}

```
 You can also use the [`navigator.storage.persisted()`](storagemanager/persisted) method to know whether an origin's storage is persistent or not:

 
```
if (navigator.storage && navigator.storage.persist) {
  navigator.storage.persisted().then((persistent) => {
    if (persistent) {
      console.log("Storage will not be cleared except by explicit user action");
    } else {
      console.log("Storage may be cleared by the UA under storage pressure.");
    }
  });
}

```
 To learn more, see [Does browser-stored data persist?](storage_api/storage_quotas_and_eviction_criteria#does_browser-stored_data_persist).



Quotas and usage estimates
--------------------------



The user agent determines, using whatever mechanism it chooses, the maximum amount of storage a given site can use. This maximum is the origin's **quota**. The amount of this space which is in use by the site is called its **usage**. Both of these values are estimates; there are several reasons why they're not precise:

 * User agents are encouraged to obscure the exact size of the data used by a given origin, to prevent these values from being used for [fingerprinting](https://developer.mozilla.org/en-US/docs/Glossary/Fingerprinting) purposes.
* De-duplication, compression, and other methods to reduce the physical size of the stored data may be used.
* Quotas are conservative estimates of the space available for the origin's use, and should be less than the available space on the device to help prevent overruns.

 To determine the estimated quota and usage values for a given origin, use the [`navigator.storage.estimate()`](storagemanager/estimate) method, which returns a promise that, when resolved, receives an object that contains these figures. For example:

 
```
navigator.storage.estimate().then((estimate) => {
  // estimate.quota is the estimated quota
  // estimate.usage is the estimated number of bytes used
});

```
 For more information about how much data an origin can store, see [How much data can be stored?](storage_api/storage_quotas_and_eviction_criteria#how_much_data_can_be_stored).



Data eviction
-------------



Data eviction is the process by which a user agent deletes an origin's stored data. This can happen, for example, when the device used to store the data is running low on storage space.

 When clearing the data stored by an origin, the origin's bucket is treated as a single entity. The entire data stored by this origin is cleared.

 If a bucket is marked as `"persistent"`, the contents won't be cleared by the user agent without either the data's origin itself or the user specifically doing so. This includes scenarios such as the user selecting a "Clear Caches" or "Clear Recent History" option. The user will be asked specifically for permission to remove persistent site storage buckets.

 To learn more, see [When is data evicted?](storage_api/storage_quotas_and_eviction_criteria#when_is_data_evicted).



Specifications
--------------




| Specification |
| --- |
| [Storage Standard # storagemanager](https://storage.spec.whatwg.org/#storagemanager) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Storage_API` | 55 | 79 | 57 | No | 42 | 15.2 | 55 | 55 | 57 | 42 | 15.2 | 6.0 |
| `estimate` | 61 | 79 | 57 | No | 48 | No | 61 | 61 | 57 | 45 | No | 8.0 |
| `getDirectory` | 86 | 86 | 111 | No | 72 | 15.2 | 109 | 109 | 111 | 74 | 15.2 | No |
| `persist` | 55 | 79 | 57 | No | 42 | 15.2 | 55 | 55 | 57 | 42 | 15.2 | 6.0 |
| `persisted` | 55 | 79 | 57 | No | 42 | 15.2 | 55 | 55 | 57 | 42 | 15.2 | 6.0 |


See also
--------


* [Using the Permissions API](permissions_api/using_the_permissions_api)
* [Storage for the web on web.dev](https://web.dev/storage-for-the-web/)
* [Persistent storage on web.dev](https://web.dev/persistent-storage/)
* [Chrome Web Storage and Quota Concepts](https://docs.google.com/document/d/19QemRTdIxYaJ4gkHYf2WWBNPbpuZQDNMpUVf8dQxj4U/edit)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Storage_API>

Storage Access API
==================



The Storage Access API provides a way for embedded, cross-origin content to gain unrestricted access to storage that it would normally only have access to in a first-party context (we refer to this as an origin's *first-party* storage).

 The API provides methods that allow embedded resources to check whether they currently have access to their first-party storage, and to request access to their first-party storage from the user agent.



Concepts and usage
------------------



Most browsers implement a number of storage access policies that restrict access to cookies and site data for embedded, cross-origin resources. These restrictions range from giving embedded resources under each top-level origin a unique storage space to outright blocking of storage access when resources are loaded in a third-party context.

 The semantics around third-party cookie blocking policies in particular differ from browser to browser, but the core functionality is similar: cross-origin resources embedded in a third-party context are not given access to the same cookies and site storage that they would have access to when loaded in a first-party context.

 These cookie blocking policies are known to break embedded cross-origin content that requires access to its first-party storage. As an example, federated logins often require access to authentication cookies stored in first-party storage, and will require the user to sign in on each site separately (or completely break) if those cookies are not available. In the case of breakage, site owners have often encouraged users to add their site as an exception or to disable the policy entirely. As a consequence, users who wish to continue to interact with embedded content are forced to greatly relax their blocking policy for resources loaded from all embedded origins and possibly across all websites.

 The Storage Access API is intended to solve this problem; embedded cross-origin content can request unrestricted access to its first-party storage on a site-by-site basis via the [`Document.requestStorageAccess()`](document/requeststorageaccess) method, and check whether it already has access via the [`Document.hasStorageAccess()`](document/hasstorageaccess) method.

 In addition, sandboxed [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe)s cannot be granted storage access by default for security reasons. The API therefore also adds the `allow-storage-access-by-user-activation` [sandbox token](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#sandbox). The embedding website needs to add this to allow storage access requests to be successful, along with `allow-scripts` and `allow-same-origin` to allow it to call the API, and execute in an origin that can have cookies:

 
```
<iframe
 sandbox="allow-storage-access-by-user-activation
 allow-scripts
 allow-same-origin">
  …
</iframe>

```
 The API is designed to limit the potential storage exceptions to origins for which the user has shown an intent to interact. This is enforced through the following constraints:

 * Access requests are automatically denied unless the embedded content is currently processing a user gesture such as a tap or click. This also prevents embedded content on the page from spamming the browser or user with excessive access requests.
* Origins that have never been interacted with as a first party do not have a notion of first-party storage. From the user's perspective, they only have a third-party relationship with that origin. Access requests are automatically denied if the browser detects that the user hasn't interacted with the embedded content in a first-party context recently (in Firefox, "recently" is "within 30 days").

 The browser may decide to involve the user in the decision of whether to grant an incoming storage access request. Specifics regarding the lifetime of a storage grant and the circumstances under which the browser may decide to inform the user are currently being worked through and will be announced once ready.



User prompts
------------


When `requestStorageAccess()` is called by an embedded, cross-origin document, the user agent may choose to involve the user in the decision of whether to grant storage access to the requesting origin. Prompting heuristics currently vary across the two implementers of the Storage Access API — Safari shows prompts for all embedded tracking content that has not previously received storage access, while Firefox only prompts users after a tracking origin has requested storage access on more than a threshold number of sites. See [`Document.requestStorageAccess()`](document/requeststorageaccess) for more details.


Safari implementation differences
---------------------------------



Although the API surface is the same, websites using the Storage Access API should expect differences in the level and extent of storage access they receive between Firefox and Safari. This is caused by differences in the storage access policies implemented in the two browsers. Design properties unique to Firefox are summarized here:

 * If the embedded origin `tracker.example` has already obtained first-party storage access on the top-level origin `foo.example`, and the user visits a page from `foo.example` embedding a page from `tracker.example` again in less than 30 days, the embedded origin will have storage access immediately when loading.
* If an embedded page from `tracker.example` has previously successfully obtained storage access on top-level origin `foo.example`, all embedded subresources from `tracker.example` on `foo.example` (e.g. scripts, images, stylesheets, etc.) will load with access to their first-party storage, which means they may send Cookie headers and honor incoming [`Set-Cookie`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie) headers.
* In Firefox, when the promise returned from `requestStorageAccess()` is resolved, the embedded page will gain access to its entire first-party storage, not just cookies. This includes access to APIs such as [Web Storage](web_storage_api), [IndexedDB](indexeddb_api), [DOM Cache](cache), and so on.
* In Firefox, the storage access grants are phased out after 30 calendar days passing, whereas in Safari the storage access grants are phased out after 30 days of browser usage passed without user interaction. This is currently a limitation of the Firefox implementation, which we may address in a future version. In Safari, successful use of the storage access API resets this counter.

 Documentation for Firefox's new storage access policy for blocking tracking cookies includes [a detailed description](https://developer.mozilla.org/en-US/docs/Web/Privacy/Storage_Access_Policy#storage_access_grants) of the scope of storage access grants.



Storage Access API methods
--------------------------



The storage API methods are implemented on the [`Document`](document) interface:

  [`Document.hasStorageAccess()`](document/hasstorageaccess)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with a boolean value indicating whether the document has access to its first-party storage.

  [`Document.requestStorageAccess()`](document/requeststorageaccess)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves if the access to first-party storage was granted, and rejects if access was denied.

    **Note:** User interaction propagates to the Promise returned by both of these methods, allowing the callers to take actions that require user interaction without requiring a second click from the user. For example, a caller could open a pop-up window from the resolved Promise without triggering Firefox's pop-up blocker.

 

Extensions to <iframe> sandbox
------------------------------


The [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe) element's `sandbox` attribute has a new token, `allow-storage-access-by-user-activation`, which permits sandboxed `<iframe>`s to use the Storage Access API to request storage access.


Specifications
--------------




| Specification |
| --- |
| [The Storage Access API # dom-document-hasstorageaccess](https://privacycg.github.io/storage-access/#dom-document-hasstorageaccess) |
| [The Storage Access API # dom-document-requeststorageaccess](https://privacycg.github.io/storage-access/#dom-document-requeststorageaccess) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Storage_Access_API` | 78See [bug 989663](https://crbug.com/989663). | 85 | 65 | No | 65 | 11.1 | No | 78See [bug 989663](https://crbug.com/989663). | 65 | No | 11.3 | No |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Storage_Access_API` | 78See [bug 989663](https://crbug.com/989663). | 85 | 65 | No | 65 | 11.1 | No | 78See [bug 989663](https://crbug.com/989663). | 65 | No | 11.3 | No |


### api.Document.hasStorageAccess


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.Document.requestStorageAccess


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


See also
--------


* [Using the Storage Access API](storage_access_api/using)
* [Introducing Storage Access API](https://webkit.org/blog/8124/introducing-storage-access-api/) (WebKit blog)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Storage_Access_API>

Trusted Types API
=================


The **Trusted Types API** gives web developers a way to lock down the insecure parts of the [`DOM API`](document_object_model) to prevent client-side [Cross-site scripting](https://developer.mozilla.org/en-US/docs/Glossary/Cross-site_scripting) (XSS) attacks.


Concepts and Usage
------------------



Client-side, or DOM-based, XSS attacks happen when data controlled by a user (such as that input into a form field) reaches a function that can execute that data. These functions are known as *injection sinks*. DOM-based XSS attacks happen when a user is able to write arbitrary JavaScript code and have it executed by one of these functions.

 The Trusted Types API locks down risky injection sinks, requiring you to process the data before passing it to one of these functions. If you use a string, then the browser will throw a [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) and prevent the use of the function.

 Trusted Types works alongside [Content-Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) with the [trusted-types](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/trusted-types) and [require-trusted-types-for](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/require-trusted-types-for) directives.



### Injection Sinks



The Trusted Types API locks down injection sinks that can act as a vector for DOM-XSS attacks. An injection sink is any Web API function that should only be called with trusted, validated or sanitized input. Examples of injection sinks include:

 * Functions that insert HTML into the document such as [`Element.innerHTML`](element/innerhtml), [`Element.outerHTML`](element/outerhtml), or [`Document.write`](document/write).
* Functions that create a new same-origin [`Document`](document) with caller-controlled markup such as [`DOMParser.parseFromString`](domparser/parsefromstring).
* Functions that execute code such as [`Global_Objects/eval`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval).
* Setters for [`Element`](element) attributes that accept a URL of code to load or execute.

 Trusted Types will force you to process the data before passing it to any injection sink rather than use a string. This ensures that the data is trustworthy.



### Trusted Type Policies


A policy is a factory for Trusted Types. Web developers can specify a set of policies used for the creation of typed objects which form the trusted codebase for valid Trusted Type objects.


Interfaces
----------


 [`TrustedHTML`](trustedhtml)  Represents a string to insert into an injection sink that will render it as HTML.

  [`TrustedScript`](trustedscript)  Represents a string to insert into an injection sink that could lead to the script being executed.

  [`TrustedScriptURL`](trustedscripturl)  Represents a string to insert into an injection sink that will parse it as a URL of an external script resource.

  [`TrustedTypePolicy`](trustedtypepolicy)  Defines the functions used to create the above Trusted Type objects.

  [`TrustedTypePolicyFactory`](trustedtypepolicyfactory)  Creates policies and verifies that Trusted Type object instances were created via one of the policies.

  
Examples
--------



In the below example we create a policy that will create [`TrustedHTML`](trustedhtml) objects using [`TrustedTypePolicyFactory.createPolicy()`](trustedtypepolicyfactory/createpolicy). We can then use [`TrustedTypePolicy.createHTML`](trustedtypepolicy/createhtml) to create a sanitized HTML string to be inserted into the document.

 The sanitized value can then be used with [`Element.innerHTML`](element/innerhtml) to ensure that no new HTML elements can be injected.

 
```
<div id="myDiv"></div>

```
 
```
const escapeHTMLPolicy = trustedTypes.createPolicy("myEscapePolicy", {
  createHTML: (string) => string.replace(/>/g, "<"),
});

let el = document.getElementById("myDiv");
const escaped = escapeHTMLPolicy.createHTML("<img src=x onerror=alert(1)>");
console.log(escaped instanceof TrustedHTML); // true
el.innerHTML = escaped;

```
 Read more about this example, and discover other ways to sanitize input in the article [Prevent DOM-based cross-site scripting vulnerabilities with Trusted Types](https://web.dev/trusted-types/).



Specifications
--------------




| Specification |
| --- |
| [Trusted Types](https://w3c.github.io/trusted-types/dist/spec/)  |


Browser compatibility
---------------------


See also
--------


* [Prevent DOM-based cross-site scripting vulnerabilities with Trusted Types](https://web.dev/trusted-types/)
* [Trusted Types polyfill](https://github.com/w3c/trusted-types#polyfill) (also available as an [npm package](https://www.npmjs.com/package/trusted-types))


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API>

UI Events
=========


Concepts and Usage
------------------



The UI Events API defines a system for handling user interactions such as mouse and keyboard input. This includes:

 * events that are fired on specific user actions such keypresses or mouse clicks. Most of these events fire on the [`Element`](element) interface, but the events relating to loading and unloading resources fire on the [`Window`](window) interface.
* event interfaces, which are passed into handlers for these events. These interfaces inherit from [`Event`](event) and provide extra information specific to the type of user interaction: for example, the [`KeyboardEvent`](keyboardevent) is passed into a [`keydown`](element/keydown_event) event handler and provides information about the key that was pressed.



Interfaces
----------


 [`CompositionEvent`](compositionevent)  Passed into handlers for composition events. Composition events enable a user to enter characters that might not be available on the physical keyboard.

  [`FocusEvent`](focusevent)  Passed into handlers for focus events, which are associated with elements receiving or losing focus.

  [`InputEvent`](inputevent)  Passed into handlers for input events, which are associated with the user entering some input; for example, using an [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) element.

  [`KeyboardEvent`](keyboardevent)  Passed into handlers for keyboard up/down events.

  [`MouseEvent`](mouseevent)  Passed into event handlers for mouse events, including mouse move, mousing over and out, and mouse button up or down. Note that [`auxclick`](element/auxclick_event), [`click`](element/click_event), and [`dblclick`](element/dblclick_event) events are passed [`PointerEvent`](pointerevent) objects.

  
[`MouseScrollEvent`](mousescrollevent)  Deprecated 
  Deprecated, Firefox-only, non-standard interface for scroll events. Use [`WheelEvent`](wheelevent) instead.

  
[`MutationEvent`](mutationevent)  Deprecated 
  Passed into mutation event handlers, which were designed to allow notifications of changes to the DOM. Now deprecated: use [`MutationObserver`](mutationobserver) instead.

  [`UIEvent`](uievent)  A base from which other UI events inherit, and also the event interface passed into some events such as [`load`](window/load_event) and [`unload`](window/unload_event).

  [`WheelEvent`](wheelevent)  Passed into the handler for the [`wheel`](element/wheel_event) event, which fires when the user rotates a mouse wheel or similar user interface component such as a touchpad.

  
Events
------


 `abort`  Fired when loading a resource has been aborted (for example, because the user canceled it).

  [`auxclick`](element/auxclick_event)  Fired when the user clicks the non-primary pointer button.

  `beforeinput`  Fired just before the DOM is about to be updated with some user input.

  [`blur`](element/blur_event)  Fired when an element has lost focus.

  [`click`](element/click_event)  Fired when the user clicks the primary pointer button.

  [`compositionend`](element/compositionend_event)  Fired when a text composition system (such as a speech-to-text processor) has finished its session; for example, because the user has closed it.

  [`compositionstart`](element/compositionstart_event)  Fired when the user has started a new session with a text composition system.

  [`compositionupdate`](element/compositionupdate_event)  Fired when a text composition system updates its text with a new character, reflected in an update to the `data` property of the [`CompositionEvent`](compositionevent).

  [`contextmenu`](element/contextmenu_event)  Fired just before a context menu is invoked.

  [`dblclick`](element/dblclick_event)  Fired when the user double-clicks the primary pointer button.

  [`error`](element/error_event)  Fired when a resource fails to load or can't be processed (for example, if an image is invalid or a script has an error).

  [`focus`](element/focus_event)  Fired when an element has received focus.

  [`focusin`](element/focusin_event)  Fired when an element is just about to receive focus.

  [`focusout`](element/focusout_event)  Fired when an element is just about to lose focus.

  `input`  Fired just after the DOM has been updated with some user input (for example, some text input).

  [`keydown`](element/keydown_event)  Fired when the user has pressed a key.

  
[`keypress`](element/keypress_event)  Deprecated 
  Fired when the user has pressed a key, only if the key produces a character value. Use [`keydown`](element/keydown_event) instead.

  [`keyup`](element/keyup_event)  Fired when the user has released a key.

  [`load`](window/load_event)  Fired when the whole page has loaded, including all dependent resources such as stylesheets and images.

  [`mousedown`](element/mousedown_event)  Fired when the user presses a button on a mouse or other pointing device, while the pointer is over the element.

  [`mouseenter`](element/mouseenter_event)  Fired when a mouse or other pointing device is moved inside the boundary of the element or one of its descendants.

  [`mouseleave`](element/mouseleave_event)  Fired when a mouse or other pointing device is moved outside the boundary of the element and all of its descendants.

  [`mousemove`](element/mousemove_event)  Fired when a mouse or other pointing device is moved while over an element.

  [`mouseout`](element/mouseout_event)  Fired when a mouse or other pointing device is moved outside the boundary of the element.

  [`mouseover`](element/mouseover_event)  Fired when a mouse or other pointing device is moved outside the element.

  [`mouseup`](element/mouseup_event)  Fired when the user releases a button on a mouse or other pointing device, while the pointer is over the element.

  [`unload`](window/unload_event)  Fired when the document or a child resource are being unloaded.

  [`wheel`](element/wheel_event)  Fired when the user rotates a mouse wheel or similar user interface component such as a touchpad.

  
Examples
--------


### Mouse events



This example logs mouse events along with the X and Y coordinates at which the event was generated. Try moving the mouse into the yellow and red squares, and clicking or double-clicking.

 #### HTML

 
```
<div id="outer">
  <div id="inner"></div>
</div>

<div id="log">
  <pre id="contents"></pre>
  <button id="clear">Clear log</button>
</div>

```
 #### CSS

 
```
body {
  display: flex;
  gap: 1rem;
}

#outer {
  height: 200px;
  width: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: yellow;
}

#inner {
  height: 100px;
  width: 100px;
  background-color: red;
}

#contents {
  height: 150px;
  width: 250px;
  border: 1px solid black;
  padding: 0.5rem;
  overflow: scroll;
}

```
 #### JavaScript

 
```
const outer = document.querySelector("#outer");
const inner = document.querySelector("#inner");
const contents = document.querySelector("#contents");
const clear = document.querySelector("#clear");
let lines = 0;

outer.addEventListener("click", (event) => {
  log(event);
});

outer.addEventListener("dblclick", (event) => {
  log(event);
});

outer.addEventListener("mouseover", (event) => {
  log(event);
});

outer.addEventListener("mouseout", (event) => {
  log(event);
});

outer.addEventListener("mouseenter", (event) => {
  log(event);
});

outer.addEventListener("mouseleave", (event) => {
  log(event);
});

function log(event) {
  const prefix = `${String(lines++).padStart(3, "0")}: `;
  const line = `${event.type}(${event.clientX}, ${event.clientY})`;
  contents.textContent = `${contents.textContent}${prefix}${line}\n`;
  contents.scrollTop = contents.scrollHeight;
}

clear.addEventListener("click", () => {
  contents.textContent = "";
  lines = 0;
});

```
 #### Result




### Keyboard and input events



This example logs [`keydown`](element/keydown_event), `beforeinput` and, `input` events. Try typing into the text area. Note that keys like `Shift` produce `keydown` events but not `input` events.

 #### HTML

 
```
<textarea id="story" rows="5" cols="33"></textarea>

<div id="log">
  <pre id="contents"></pre>
  <button id="clear">Clear log</button>
</div>

```
 #### CSS

 
```
body {
  display: flex;
  gap: 1rem;
}

#story {
  padding: 0.5rem;
}

#contents {
  height: 150px;
  width: 250px;
  border: 1px solid black;
  padding: 0.5rem;
  overflow: scroll;
}

```
 #### JavaScript

 
```
const story = document.querySelector("#story");
const contents = document.querySelector("#contents");
const clear = document.querySelector("#clear");
let lines = 0;

story.addEventListener("keydown", (event) => {
  log(`${event.type}(${event.key})`);
});

story.addEventListener("beforeinput", (event) => {
  log(`${event.type}(${event.data})`);
});

story.addEventListener("input", (event) => {
  log(`${event.type}(${event.data})`);
});

function log(line) {
  const prefix = `${String(lines++).padStart(3, "0")}: `;
  contents.textContent = `${contents.textContent}${prefix}${line}\n`;
  contents.scrollTop = contents.scrollHeight;
}

clear.addEventListener("click", () => {
  contents.textContent = "";
  lines = 0;
});

```
 #### Result




Specifications
--------------




| Specification |
| --- |
| [UI Events](https://w3c.github.io/uievents/)  |


See also
--------


* [Pointer Events API](pointer_events)
* [Touch Events](touch_events)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/UI_Events>

URL API
=======



The URL API is a component of the URL standard, which defines what constitutes a valid [Uniform Resource Locator](https://developer.mozilla.org/en-US/docs/Glossary/URL) and the API that accesses and manipulates URLs. The URL standard also defines concepts such as domains, hosts, and IP addresses, and also attempts to describe in a standard way the legacy `application/x-www-form-urlencoded` [MIME type](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type) used to submit web forms' contents as a set of key/value pairs.


 **Note:** This feature is available in [Web Workers](web_workers_api)

 

URL concepts and usage
----------------------


The majority of the URL standard is taken up by the [definition of a URL](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL) and how it is structured and parsed. Also covered are definitions of various terms related to addressing of computers on a network, and the algorithms for parsing IP addresses and DOM addresses are specified. More interesting to most developers is the API itself.


### Accessing URL components



Creating an [`URL`](url) object for a given URL parses the URL and provides quick access to its constituent parts through its properties.

 
```
let addr = new URL("https://developer.mozilla.org/en-US/docs/Web/API/URL\_API");
let host = addr.host;
let path = addr.pathname;

```
 The snippet above creates a `URL` object for the article you're reading right now, then fetches the [`host`](url/host) and [`pathname`](url/pathname) properties. In this case, those strings are `developer.mozilla.org` and `/en-US/docs/Web/API/URL_API`, respectively.



### Changing the URL



Most of the properties of `URL` are settable; you can write new values to them to alter the URL represented by the object. For example, to create a URL and set its username:

 
```
let myUsername = "someguy";
let addr = new URL("https://example.com/login");
addr.username = myUsername;

```
 Setting the value of [`username`](url/username) not only sets that property's value, but it updates the overall URL. After executing the code snippet above, the value returned by [`addr.href`](url/href) is `https://someguy@example.com/login`. This is true for any of the writable properties.



### Queries



The [`search`](url/search) property on a `URL` contains the query string portion of the URL. For example, if the URL is `https://example.com/login?user=someguy&page=news`, then the value of the `search` property is `?user=someguy&page=news`. You can also look up the values of individual parameters with the [`URLSearchParams`](urlsearchparams) object's [`get()`](urlsearchparams/get) method:

 
```
let addr = new URL("https://example.com/login?user=someguy&page=news");
try {
  loginUser(addr.searchParams.get("user"));
  gotoPage(addr.searchParams.get("page"));
} catch (err) {
  showErrorMessage(err);
}

```
 For example, in the above snippet, the username and target page are taken from the query and passed to appropriate functions that are used by the site's code to log in and route the user to their desired destination within the site.

 Other functions within `URLSearchParams` let you change the value of keys, add and delete keys and their values, and even sort the list of parameters.



URL API interfaces
------------------



The URL API is a simple one, with only a couple of interfaces to its name:

 * [`URL`](url)
* [`URLSearchParams`](urlsearchparams)



Examples
--------



If you want to process the parameters included in a URL, you could do it manually, but it's much easier to create a `URL` object to do it for you. The `fillTableWithParameters()` function below takes as input a [`HTMLTableElement`](htmltableelement) object representing a [`<table>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table). Rows are added to the table, one for each key found in the parameters, with the first column containing the key's name, and the second column having the value.

 Note the call to [`URLSearchParams.sort()`](urlsearchparams/sort) to sort the parameter list before generating the table.

 
```
function fillTableWithParameters(tbl) {
  const url = new URL(document.location.href);
  url.searchParams.sort();
  const keys = url.searchParams.keys();

  for (const key of keys) {
    const val = url.searchParams.get(key);
    const row = document.createElement("tr");
    const cell1 = document.createElement("td");
    cell1.innerText = key;
    row.appendChild(cell1);
    const cell2 = document.createElement("td");
    cell2.innerText = val;
    row.appendChild(cell2);
    tbl.appendChild(row);
  }
}

```
 A working version of this example can be [found on Glitch](https://url-api.glitch.me). Just add parameters to the URL when loading the page to see them in the table. For instance, try [`https://url-api.glitch.me?from=mdn&excitement=high&likelihood=inconceivable`](https://url-api.glitch.me?from=mdn&excitement=high&likelihood=inconceivable).



Specifications
--------------




| Specification |
| --- |
| [URL Standard # api](https://url.spec.whatwg.org/#api) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `URL` | 19 | 12Before Edge 79, query arguments in the base URL argument are removed when calling the `URL` constructor. | 26 | No | 15 | 14.16In Safari 14 and earlier, calling the `URL` constructor with a base URL whose value is `undefined` causes Safari to throw a `TypeError`; see [WebKit bug 216841](https://webkit.org/b/216841). | 4.4 | 25 | 26 | 14 | 14.56In Safari 14 and earlier, calling the `URL` constructor with a base URL whose value is `undefined` causes Safari to throw a `TypeError`; see [WebKit bug 216841](https://webkit.org/b/216841). | 1.5 |
| `URL_API` | 3219 | 12 | 19Before version 57, Firefox had a bug whereby single quotes contained in URLs are escaped when accessed via URL APIs (see [bug 1386683](https://bugzil.la/1386683)). | 10 | 1915 | 76 | 4.44 | 3225 | 19Before version 57, Firefox had a bug whereby single quotes contained in URLs are escaped when accessed via URL APIs (see [bug 1386683](https://bugzil.la/1386683)). | 1914 | 76 | 2.01.5 |
| `createObjectURL` | 19 | 12 | 19`createObjectURL()` is no longer available within the context of a `ServiceWorker`. | 10If the underlying object does not have a content type set, using this URL as the `src` of an `img` tag fails intermittently with error DOM7009. | 15 | 6 | 4.4 | 25 | 19`createObjectURL()` is no longer available within the context of a `ServiceWorker`. | 14 | 6 | 1.5 |
| `hash` | 32 | 13 | 22 | No | 19 | 7 | 4.4.3 | 32 | 22 | 19 | 7 | 2.0 |
| `host` | 32 | 13 | 22 | No | 19 | 7 | 4.4.3 | 32 | 22 | 19 | 7 | 2.0 |
| `hostname` | 32 | 13 | 22 | No | 19 | 10 | 4.4.3 | 32 | 22 | 19 | 10 | 2.0 |
| `href` | 32 | 13 | 22 | No | 19 | 10 | 4.4.3 | 32 | 22 | 19 | 10 | 2.0 |
| `origin` | 32 | 12 | 2626–49Results for `URL` using the `blob` scheme incorrectly returned `null`. | No | 19 | 10 | 4.4.3 | 32 | 2626–49Results for `URL` using the `blob` scheme incorrectly returned `null`. | 19 | 10 | 6.0 |
| `password` | 32 | 12 | 26 | No | 19 | 10 | 4.4.3 | 32 | 26 | 19 | 10 | 6.0 |
| `pathname` | 32 | 13 | 22Before Firefox 53, `pathname` and `search` returned wrong values for custom protocols. Given `protocol:host/x?a=true&b=false`, `pathname` would return "/x?a=true&b=false" and `search` would return "", rather than "/x" and "?a=true&b=false" respectively. See [bug 1310483](https://bugzil.la/1310483). | No | 19 | 10 | 4.4.3 | 32 | 22Before Firefox 53, `pathname` and `search` returned wrong values for custom protocols. Given `protocol:host/x?a=true&b=false`, `pathname` would return "/x?a=true&b=false" and `search` would return "", rather than "/x" and "?a=true&b=false" respectively. See [bug 1310483](https://bugzil.la/1310483). | 19 | 10 | 2.0 |
| `port` | 32 | 13 | 22 | No | 19 | 10 | 4.4.3 | 32 | 22 | 19 | 10 | 2.0 |
| `protocol` | 32 | 13 | 22 | No | 19 | 10 | 4.4.3 | 32 | 22 | 19 | 10 | 2.0 |
| `revokeObjectURL` | 19 | 12 | 19`revokeObjectURL()` is no longer available within the context of a `ServiceWorker`. | 10 | 15 | 6 | 4.4 | 25 | 19`revokeObjectURL()` is no longer available within the context of a `ServiceWorker`. | 14 | 6 | 1.5 |
| `search` | 32 | 13 | 22Before Firefox 53, `pathname` and `search` returned wrong values for custom protocols. Given `protocol:host/x?a=true&b=false`, `pathname` would return "/x?a=true&b=false" and `search` would return "", rather than "/x" and "?a=true&b=false" respectively. See [bug 1310483](https://bugzil.la/1310483). | No | 19 | 10 | 4.4.3 | 32 | 22Before Firefox 53, `pathname` and `search` returned wrong values for custom protocols. Given `protocol:host/x?a=true&b=false`, `pathname` would return "/x?a=true&b=false" and `search` would return "", rather than "/x" and "?a=true&b=false" respectively. See [bug 1310483](https://bugzil.la/1310483). | 19 | 10 | 2.0 |
| `searchParams` | 51 | 17 | 29 | No | 38 | 10 | 51 | 51 | 29 | 41 | 10 | 5.0 |
| `toJSON` | 71 | 17 | 54 | No | 58 | 11 | 71 | 71 | 54 | 50 | 11 | 10.0 |
| `toString` | 19 | 17 | 54 | No | 15 | 7 | 4.4 | 25 | 54 | 14 | 7 | 6.0 |
| `username` | 32 | 12 | 26 | No | 19 | 10 | 4.4.3 | 32 | 26 | 19 | 10 | 6.0 |


See also
--------


* [Fetch API](fetch_api)
* CSS [`<url>()`](https://developer.mozilla.org/en-US/docs/Web/CSS/url) type
* [`encodeURI()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI)
* [`encodeURIComponent()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/URL_API>

User-Agent Client Hints API
===========================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The User-Agent Client Hints API extends [Client Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Client_hints) to provide a way of exposing browser and platform information via User-Agent response and request headers, and a JavaScript API.



Concepts and Usage
------------------



Parsing the User-Agent string has historically been the way to get information about the user's browser or device. A typical user agent string looks like the following example, identifying Chrome 92 on Windows:

 
```
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36

```
 User agent Client Hints aims to provide this information in a more privacy-preserving way by enforcing a model where the server requests a set of information. The browser decides what to return. This approach means that a user-agent could provide settings that allow a user to hide some of the information that could fingerprint them from such requests.

 In order to decide what to return, the information accessed via this API is split into two groups—**low entropy** and **high entropy** hints. Low entropy hints are those that do not give away much information, the API makes these easily accessible with every request. High entropy hints have the potential to give away more information and therefore are gated in such a way that the browser can make a decision as to whether to provide them. This decision could potentially be based on user preferences, or behind a permission request.



### Use cases for User-Agent Client Hints



Potential use cases include:

 * Providing custom-tailored polyfills to users on identifying that their browser lacked some web platform feature.
* Working around browser bugs.
* Recording browser analytics.
* Adapting content based on user-agent information. This includes serving different content to mobile devices, in particular devices identified as low-powered. It might also include adapting the design to tailor the interfaces to the user's OS, or providing links to OS-specific ones.
* Providing a notification when a user logs in from a different browser or device, as a security feature.
* Providing the correct binary executable, on a site offering a download.
* Collecting information about the browser and device to identify application errors.
* Blocking spammers, bots, and crawlers.



Interfaces
----------


 [`NavigatorUAData`](navigatoruadata)  Provides properties and methods to access data about the user's browser and operating system.

  
Examples
--------


### Getting the brands



The following example prints the value of [`NavigatorUAData.brands`](navigatoruadata/brands) to the console.

 
```
console.log(navigator.userAgentData.brands);

```


### Returning high entropy values



In the following example a number of hints are requested using the [`NavigatorUAData.getHighEntropyValues()`](navigatoruadata/gethighentropyvalues) method. When the promise resolves, this information is printed to the console.

 
```
navigator.userAgentData
  .getHighEntropyValues([
    "architecture",
    "model",
    "platform",
    "platformVersion",
    "fullVersionList",
  ])
  .then((ua) => {
    console.log(ua);
  });

```


Specifications
--------------




| Specification |
| --- |
| [User-Agent Client Hints # navigatoruadata](https://wicg.github.io/ua-client-hints/#navigatoruadata) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `User-Agent_Client_Hints_API` | 90 | 90 | No | No | 76 | No | NoSee [bug 921655](https://crbug.com/921655). | 90 | No | 64 | No | No |
| `brands` | 90 | 90 | No | No | 76 | No | No | 90 | No | 64 | No | No |
| `getHighEntropyValues` | 90 | 90 | No | No | 76 | No | No | 90 | No | 64 | No | No |
| `mobile` | 90 | 90 | No | No | 76 | No | No | 90 | No | 64 | No | No |
| `platform` | 93 | 93 | No | No | 79 | No | No | 93 | No | 66 | No | No |
| `toJSON` | 93 | 93 | No | No | 79 | No | No | 93 | No | 66 | No | No |


See also
--------


* [Improving user privacy and developer experience with User-Agent Client Hints](https://web.dev/user-agent-client-hints/)
* [Migrate to User-Agent Client Hints](https://web.dev/migrate-to-ua-ch/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/User-Agent_Client_Hints_API>

Vibration API
=============


Most modern mobile devices include vibration hardware, which lets software code provide physical feedback to the user by causing the device to shake. The **Vibration API** offers Web apps the ability to access this hardware, if it exists, and does nothing if the device doesn't support it.


Describing vibrations
---------------------


Vibration is described as a pattern of on-off pulses, which may be of varying lengths. The pattern may consist of either a single integer, describing the number of milliseconds to vibrate, or an array of integers describing a pattern of vibrations and pauses. Vibration is controlled with a single method: [`Navigator.vibrate()`](navigator/vibrate).


### A single vibration



You may pulse the vibration hardware one time by specifying either a single value or an array consisting of only one value:

 
```
window.navigator.vibrate(200);
window.navigator.vibrate([200]);

```
 Both of these examples vibrate the device for 200 ms.



### Vibration patterns



An array of values describes alternating periods in which the device is vibrating and not vibrating. Each value in the array is converted to an integer, then interpreted alternately as the number of milliseconds the device should vibrate and the number of milliseconds it should not be vibrating. For example:

 
```
window.navigator.vibrate([200, 100, 200]);

```
 This vibrates the device for 200 ms, then pauses for 100 ms before vibrating the device again for another 200 ms.

 You may specify as many vibration/pause pairs as you like, and you may provide either an even or odd number of entries; it's worth noting that you don't have to provide a pause as your last entry since the vibration automatically stops at the end of each vibration period.



### Canceling existing vibrations


Calling [`Navigator.vibrate()`](navigator/vibrate) with a value of `0`, an empty array, or an array containing all zeros will cancel any currently ongoing vibration pattern.


### Continued vibrations



Some basic `setInterval` and `clearInterval` action will allow you to create persistent vibration:

 
```
let vibrateInterval;

// Starts vibration at passed in level
function startVibrate(duration) {
  navigator.vibrate(duration);
}

// Stops vibration
function stopVibrate() {
  // Clear interval and stop persistent vibrating
  if (vibrateInterval) clearInterval(vibrateInterval);
  navigator.vibrate(0);
}

// Start persistent vibration at given duration and interval
// Assumes a number value is given
function startPersistentVibrate(duration, interval) {
  vibrateInterval = setInterval(() => {
    startVibrate(duration);
  }, interval);
}

```
 Of course, the snippet above doesn't take into account the array method of vibration; persistent array-based vibration will require calculating the sum of the array items and creating an interval based on that number (with an additional delay, probably).



Specifications
--------------




| Specification |
| --- |
| [Vibration API (Second Edition) # dom-navigator-vibrate](https://w3c.github.io/vibration/#dom-navigator-vibrate) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Vibration_API` | 32 | 79 | 16["Until Firefox 26 included, when the vibration pattern was too long or any of its elements too large, Firefox threw an exception instead of returning `false` ([bug 884935](https://bugzil.la/884935)).", "From Firefox 32 onwards, when the vibration pattern is too long or any of its elements too large, it returns `true` but truncates the pattern ([bug 1014581](https://bugzil.la/1014581)).", "Beginning in Firefox 72, this is not supported in cross-origin iframes."]11–16 | No | 19 | No | 4.4.3["Beginning in version 55, this is not supported in cross-origin iframes.", "Beginning in version 60, this method requires a user gesture. Otherwise it returns `false`."] | 32["Beginning in Chrome 55, this is not supported in cross-origin iframes.", "Beginning in Chrome 60, this method requires a user gesture. Otherwise it returns `false`."] | 79Vibration is disabled. If the window is visible, then `navigator.vibrate()` returns `true`, but no vibration takes place (regardless of hardware support). Originally, the intent was to disable it for cross-origin frames only ([bug 1591113](https://bugzil.la/1591113)), but the feature was not re-enabled due to abuse concerns ([bug 1653318](https://bugzil.la/1653318)).16–79["Until Firefox 26 included, when the vibration pattern was too long or any of its elements too large, Firefox threw an exception instead of returning `false` ([bug 884935](https://bugzil.la/884935)).", "From Firefox 32 onwards, when the vibration pattern is too long or any of its elements too large, it returns `true` but truncates the pattern ([bug 1014581](https://bugzil.la/1014581))."]14–16 | 19["Beginning in Opera 42, this is not supported in cross-origin iframes.", "Beginning in Opera 47, this method requires a user gesture. Otherwise it returns `false`."] | No | 2.0["Beginning in Samsung Internet 6.0, this is not supported in cross-origin iframes.", "Beginning in Samsung Internet 8.0, this method requires a user gesture. Otherwise it returns `false`."] |


See also
--------


* [`Navigator.vibrate()`](navigator/vibrate)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Vibration_API>

View Transitions API
====================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The **View Transitions API** provides a mechanism for easily creating animated transitions between different DOM states, while also updating the DOM contents in a single step.



Concepts and usage
------------------



View transitions are a popular design choice for reducing users' cognitive load, helping them stay in context, and reducing perceived loading latency as they move between states or views of an application.

 However, creating view transitions on the web has historically been difficult. Transitions between states in single-page apps (SPAs) tends to involve writing significant CSS and JavaScript to:

 * Handle the loading and positioning of the old and new content.
* Animate the old and new states to create the transition.
* Stop accidental user interactions with the old content from causing problems.
* Remove the old content once the transition is complete.

 There is also the major issue of accessibility issues caused by having the new and old content both present in the DOM at once, such as loss of reading position, focus confusion, and strange live region announcement behavior. And cross-document view transitions (i.e. across different pages in regular web sites) are impossible.

 The View Transitions API provides a much easier way of handling the required DOM changes and transition animations.

  **Note:** The View Transitions API doesn't currently enable cross-document view transitions, but this is planned for a future level of the spec and is actively being worked on.

 

### Creating a basic view transition



An SPA will include functionality to fetch new content and update the DOM in response to an event of some kind, such as a navigation link being clicked or an update being pushed from the server. In our [Basic View Transitions demo](https://mdn.github.io/dom-examples/view-transitions/) we've simplified this to a `displayNewImage()` function that shows a new full-size image based on the thumbnail that was clicked. We've encapsulated this inside an `updateView()` function that handles both browsers that do and don't support the View Transitions API:

 
```
function updateView(event) {
  // Handle the difference in whether the event is fired on the <a> or the <img>
  const targetIdentifier = event.target.firstChild || event.target;

  const displayNewImage = () => {
    const mainSrc = `${targetIdentifier.src.split("\_th.jpg")[0]}.jpg`;
    galleryImg.src = mainSrc;
    galleryCaption.textContent = targetIdentifier.alt;
  };

  // Fallback for browsers that don't support View Transitions:
  if (!document.startViewTransition) {
    displayNewImage();
    return;
  }

  // With View Transitions:
  const transition = document.startViewTransition(() => displayNewImage());
}

```
 And that's it. This code is enough to handle the transition between displayed images. Supporting browsers will show the change from old to new images and captions as a smooth cross-fade (the default view transition), and it will still work in non-supporting browsers but without the nice animation.

 It is also worth mentioning that `startViewTransition()` returns a [`ViewTransition`](viewtransition) instance, which includes several promises, allowing you to run code in response to different parts of the view transition process being reached.



### The view transition process



Let's walk through how this works:

 1. When [`document.startViewTransition()`](document/startviewtransition) is called, the API takes a screenshot of the current page.
2. Next, the callback passed to `startViewTransition()` is invoked, in this case `displayNewImage`, which causes the DOM to change. When the callback has run successfully, the [`ViewTransition.updateCallbackDone`](viewtransition/updatecallbackdone) promise fulfills, allowing you to respond to the DOM updating.
3. The API captures the new state of the page as a live representation.
4. The API constructs a pseudo-element tree with the following structure: 
```
::view-transition
└─ ::view-transition-group(root)
   └─ ::view-transition-image-pair(root)
      ├─ ::view-transition-old(root)
      └─ ::view-transition-new(root)

```

	* [`::view-transition`](https://developer.mozilla.org/en-US/docs/Web/CSS/::view-transition) is the root of view transitions overlay, which contains all view transitions and sits over the top of all other page content.
	* [`::view-transition-old`](https://developer.mozilla.org/en-US/docs/Web/CSS/::view-transition-old) is the screenshot of the old page view, and [`::view-transition-new`](https://developer.mozilla.org/en-US/docs/Web/CSS/::view-transition-new) is the live representation of the new page view. Both of these render as replaced content, in the same manner as an [`<img>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img) or [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video), meaning that they can be styled with handy properties like [`object-fit`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) and [`object-position`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position).When the transition animation is about to run, the [`ViewTransition.ready`](viewtransition/ready) promise fulfills, allowing you to respond by running a custom JavaScript animation instead of the default, for example.
5. The old page view animates from [`opacity`](https://developer.mozilla.org/en-US/docs/Web/CSS/opacity) 1 to 0, while the new view animates from `opacity` 0 to 1, which is what creates the default cross-fade.
6. When the transition animation has reached its end state, the [`ViewTransition.finished`](viewtransition/finished) promise fulfills, allowing you to respond.



### Different transitions for different elements



At the moment, all of the different elements that change when then DOM updates are transitioned using the same animation. If you want different elements to animate differently from the default "root" animation, you can separate them out using the [`view-transition-name`](https://developer.mozilla.org/en-US/docs/Web/CSS/view-transition-name) property. For example:

 
```
figcaption {
  view-transition-name: figure-caption;
}

```
 We've given the [`<figcaption>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/figcaption) element a `view-transition-name` of `figure-caption` to separate it from the rest of the page in terms of view transitions.

 With this CSS applied, the pseudo-element tree will now look like this:

 
```
::view-transition
├─ ::view-transition-group(root)
│ └─ ::view-transition-image-pair(root)
│     ├─ ::view-transition-old(root)
│     └─ ::view-transition-new(root)
└─ ::view-transition-group(figure-caption)
  └─ ::view-transition-image-pair(figure-caption)
      ├─ ::view-transition-old(figure-caption)
      └─ ::view-transition-new(figure-caption)

```
 The existence of the second set of pseudo-elements allows separate view transition styling to be applied just to the `<figcaption>`. The different old and new page view captures are handled completely separate from one another.

 The value of `view-transition-name` can be anything you want except for `none` — the `none` value specifically means that the element will not participate in a view transition.

  **Note:** `view-transition-name` must be unique. If two rendered elements have the same `view-transition-name` at the same time, [`ViewTransition.ready`](viewtransition/ready) will reject and the transition will be skipped.

 

### Customizing your animations



The View Transitions pseudo-elements have default [CSS Animations](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Animations) applied (which are detailed in their [reference pages](#css_additions)). You can modify the default cross-fade in any way you want using regular CSS.

 For example, to change the speed of it:

 
```
::view-transition-old(root),
::view-transition-new(root) {
  animation-duration: 0.5s;
}

```
 Let's look at something more interesting — a custom animation for the `<figcaption>`:

 
```
@keyframes grow-x {
  from {
    transform: scaleX(0);
  }
  to {
    transform: scaleX(1);
  }
}

@keyframes shrink-x {
  from {
    transform: scaleX(1);
  }
  to {
    transform: scaleX(0);
  }
}

::view-transition-old(figure-caption),
::view-transition-new(figure-caption) {
  height: auto;
  right: 0;
  left: auto;
  transform-origin: right center;
}

::view-transition-old(figure-caption) {
  animation: 0.25s linear both shrink-x;
}

::view-transition-new(figure-caption) {
  animation: 0.25s 0.25s linear both grow-x;
}

```
 Here we've created a custom CSS animation and applied it to the `::view-transition-old(figure-caption)` and `::view-transition-new(figure-caption)` pseudo-elements, plus we've also added a number of other styles to both to keep them in the same place and stop the default styling from interfering with our custom animations.

 Note that we also discovered another transition option that is simpler and produced a nicer result than the above. Our final `<figcaption>` view transition ended up looking like this:

 
```
figcaption {
  view-transition-name: figure-caption;
}

::view-transition-old(figure-caption),
::view-transition-new(figure-caption) {
  height: 100%;
}

```
 This works because by default, `::view-transition-group` transitions width and height between the old and new views. We just needed to set a fixed `height` on both states to make it work.

  **Note:** [Smooth and simple transitions with the View Transitions API](https://developer.chrome.com/docs/web-platform/view-transitions/) contains several other customization examples.

 

### Controlling animations with JavaScript



The [`document.startViewTransition()`](document/startviewtransition) method returns a [`ViewTransition`](viewtransition) object instance, which contains several promise members allowing you to run JavaScript in response to different states of the transition being reached. For example, [`ViewTransition.ready`](viewtransition/ready) fulfills once the pseudo-element tree is created and the animation is about to start, whereas [`ViewTransition.finished`](viewtransition/finished) fulfills once the the animation is finished, and the new page view is visible and interactive to the user.

 For example, the following JavaScript could be used to create a circular reveal view transition emanating from the position of the user's cursor on click, with animation provided by the [Web Animations API](web_animations_api).

 
```
// Store the last click event
let lastClick;
addEventListener("click", (event) => (lastClick = event));

function spaNavigate(data) {
  // Fallback for browsers that don’t support this API:
  if (!document.startViewTransition) {
    updateTheDOMSomehow(data);
    return;
  }

  // Get the click position, or fallback to the middle of the screen
  const x = lastClick?.clientX ?? innerWidth / 2;
  const y = lastClick?.clientY ?? innerHeight / 2;
  // Get the distance to the furthest corner
  const endRadius = Math.hypot(
    Math.max(x, innerWidth - x),
    Math.max(y, innerHeight - y)
  );

  // Create a transition:
  const transition = document.startViewTransition(() => {
    updateTheDOMSomehow(data);
  });

  // Wait for the pseudo-elements to be created:
  transition.ready.then(() => {
    // Animate the root’s new view
    document.documentElement.animate(
      {
        clipPath: [
          `circle(0 at ${x}px ${y}px)`,
          `circle(${endRadius}px at ${x}px ${y}px)`,
        ],
      },
      {
        duration: 500,
        easing: "ease-in",
        // Specify which pseudo-element to animate
        pseudoElement: "::view-transition-new(root)",
      }
    );
  });
}

```
 This animation also requires the following CSS, to turn off the default CSS animation and stop the old and new view states from blending in any way (the new state "wipes" right over the top of the old state, rather than transitioning in):

 
```
::view-transition-image-pair(root) {
  isolation: auto;
}

::view-transition-old(root),
::view-transition-new(root) {
  animation: none;
  mix-blend-mode: normal;
  display: block;
}

```


Interfaces
----------


 [`ViewTransition`](viewtransition)  Represents a view transition, and provides functionality to react to the transition reaching different states (e.g. ready to run the animation, or animation finished) or skip the transition altogether.

  
Extensions to other interfaces
------------------------------


 [`Document.startViewTransition()`](document/startviewtransition)  Starts a new view transition and returns a [`ViewTransition`](viewtransition) object to represent it.

  
CSS additions
-------------


### Properties


 [`view-transition-name`](https://developer.mozilla.org/en-US/docs/Web/CSS/view-transition-name)  Provides the selected element with a separate identifying name and causes it to participate in a separate view transition from the root view transition — or no view transition if the `none` value is specified.

  
### Pseudo-elements


 [`::view-transition`](https://developer.mozilla.org/en-US/docs/Web/CSS/::view-transition)  The root of the view transitions overlay, which contains all view transitions and sits over the top of all other page content.

  [`::view-transition-group()`](https://developer.mozilla.org/en-US/docs/Web/CSS/::view-transition-group)  The root of a single view transition.

  [`::view-transition-image-pair()`](https://developer.mozilla.org/en-US/docs/Web/CSS/::view-transition-image-pair)  The container for a view transition's old and new views — before and after the transition.

  [`::view-transition-old()`](https://developer.mozilla.org/en-US/docs/Web/CSS/::view-transition-old)  A static screenshot of the old view, before the transition.

  [`::view-transition-new()`](https://developer.mozilla.org/en-US/docs/Web/CSS/::view-transition-new)  A live representation of the new view, after the transition.

  
Examples
--------


* [Basic View Transitions demo](https://mdn.github.io/dom-examples/view-transitions/): A basic image gallery demo with separate transitions between old and new images, and old and new captions.
* [HTTP 203 playlist](https://http203-playlist.netlify.app/): A more sophisticated video player demo app that features a number of different view transitions, many of which are explained in [Smooth and simple transitions with the View Transitions API](https://developer.chrome.com/docs/web-platform/view-transitions/).

Specifications
--------------




| Specification |
| --- |
| [CSS View Transitions Module Level 1 # dom-document-startviewtransition](https://w3c.github.io/csswg-drafts/css-view-transitions/#dom-document-startviewtransition) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `View_Transitions_API` | 111 | 111 | No | No | 97 | No | 111 | 111 | No | No | No | No |


See also
--------


* [Smooth and simple transitions with the View Transitions API](https://developer.chrome.com/docs/web-platform/view-transitions/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API>

VirtualKeyboard API
===================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The VirtualKeyboard API provides developers control over the layout of their applications when the on-screen virtual keyboard appears and disappears on devices such as tablets, mobile phones, or other devices where a hardware keyboard may not be available.

 Web browsers usually deal with virtual keyboards on their own, by adjusting the viewport height and scrolling to input fields when focused.

 The figure below illustrates the difference in viewport height and scroll position on a web page when the device has its on-screen virtual keyboard hidden, and when it is shown.

  ![Two devices, one without a virtual keyboard, showing that the webpage can use most of the device's vertical space, and one with a virtual keyboard, showing that the webpage can only be displayed in the remaining space] 

 More complex applications or specific devices such as multi-screen mobile phones may require more control of the layout when the virtual keyboard appears.

 The figure below shows what happens on a dual-screen device when the virtual keyboard appears on just one of the two screens. The viewport becomes smaller on both screens to accommodate for the virtual keyboard, leaving wasted space on the screen where the virtual keyboard is not displayed.

  ![A dual-screen device, with its virtual keyboard displayed on one screen, showing that the webpage can only use the vertical space that remains after the keyboard was displayed, even if that leaves empty space on the other screen] 

 The VirtualKeyboard API can be used to opt out of the way the browser automatically handles the virtual keyboard, and take full control of it instead. With the VirtualKeyboard API, the keyboard still appears and disappears as necessary when form controls are focused, but the viewport does not change, and you can use JavaScript and CSS to adapt your layout.



Concept
-------



The VirtualKeyboard API consists of three parts:

 * The [`VirtualKeyboard`](virtualkeyboard) interface, accessed through [`navigator.virtualKeyboard`](navigator/virtualkeyboard), is used to opt out of the automatic virtual keyboard behavior, show or hide the virtual keyboard programmatically, as well as get the current position and size of the virtual keyboard.
* The `keyboard-inset-*` CSS environment variables provide information about the virtual keyboard's position and size.
* The [`virtualkeyboardpolicy`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#virtualkeyboardpolicy) attribute specifies whether the virtual keyboard should appear on `contenteditable` elements.



### Opt out of the automatic virtual keyboard behavior


To opt out of the automatic virtual keyboard behavior of the browser, use `navigator.virtualKeyboard.overlaysContent = true`. The browser will no longer automatically resize the viewport to make space for the virtual keyboard, which will overlay your content instead.


### Detect the virtual keyboard geometry using JavaScript



Once you've opted out of the default browser behavior, you can get the current geometry of the virtual keyboard using `navigator.virtualKeyboard.boundingRect`, and adapt the layout as appropriate using CSS and JavaScript. In addition, you can listen to geometry changes, such as when the keyboard is shown or hidden, by using the `geometrychange` event.

 This is useful for positioning important UI elements in the area that's not covered by the virtual keyboard.

 The code snippet below uses the `geometrychange` event to detect when the virtual keyboard geometry changes; it then accesses the `boundingRect` property to query the size and position of the virtual keyboard:

 
```
if ("virtualKeyboard" in navigator) {
  navigator.virtualKeyboard.overlaysContent = true;

  navigator.virtualKeyboard.addEventListener("geometrychange", (event) => {
    const { x, y, width, height } = event.target.boundingRect;
  });
}

```


### Detect the virtual keyboard geometry using CSS environment variables



The VirtualKeyboard API also exposes the following [`CSS environment variables`](https://developer.mozilla.org/en-US/docs/Web/CSS/env): `keyboard-inset-top`, `keyboard-inset-right`, `keyboard-inset-bottom`, `keyboard-inset-left`, `keyboard-inset-width`, and `keyboard-inset-height`.

 The `keyboard-inset-*` CSS environment variables are useful to adapt your layout to the virtual keyboard appearance using CSS. They define a rectangle by its top, right, bottom, and left insets from the edge of the viewport. The `width` and `height` variables are also available if needed.

 The code snippet below uses the `keyboard-inset-height` CSS variable to reserve space for the virtual keyboard to appear below the list of messages and input field in a chat-like application. When the virtual keyboard is hidden, the `env()` function returns `0px` and the `keyboard` grid area is hidden. The messages and input elements can occupy the full height of the viewport. When the virtual keyboard appears, the `keyboard` grid area gets the height of the virtual keyboard.

 
```
<style>
 body {
 display: grid;
 margin: 0;
 height: 100vh;
 grid-template:
 "messages" 1fr
 "input" auto
 "keyboard" env(keyboard-inset-height, 0px);
 }
</style>
<ul id="messages"></ul>
<input type="text" />
<script>
 if ("virtualKeyboard" in navigator) {
 navigator.virtualKeyboard.overlaysContent = true;
 }
</script>

```


### Control the virtual keyboard on `contenteditable` elements



By default, elements using the [`contenteditable`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#contenteditable) attribute also trigger the virtual keyboard when tapped or clicked. In certain situations, it may be desirable to prevent this behavior and instead show the virtual keyboard after a different event.

 Set the [`virtualkeyboardpolicy`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#virtualkeyboardpolicy) attribute to `manual` to prevent the default handling of the virtual keyboard in the browser, and instead handle it yourself by using the [`VirtualKeyboard`](virtualkeyboard) interface's `show()` and `hide()` methods.

 The code snippet below shows how to use the `virtualkeyboardpolicy` attribute and the `navigator.virtualKeyboard.show()` method to show the virtual keyboard on double-click instead:

 
```
<div contenteditable virtualkeyboardpolicy="manual" id="editor"></div>
<script>
 if ("virtualKeyboard" in navigator) {
 navigator.virtualKeyboard.overlaysContent = true;

 const editor = document.getElementById("editor");
 editor.addEventListener("dblclick", () => {
 navigator.virtualKeyboard.show();
 });
 }
</script>

```


Interfaces
----------


 
[`VirtualKeyboard`](virtualkeyboard)  Experimental 
  Provides functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard.

  
Specifications
--------------




| Specification |
| --- |
| [VirtualKeyboard API # the-virtualkeyboard-interface](https://w3c.github.io/virtual-keyboard/#the-virtualkeyboard-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `VirtualKeyboard_API` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `boundingRect` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `geometrychange_event` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `hide` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `overlaysContent` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `show` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |


See also
--------


* [Full control with the VirtualKeyboard API](https://developer.chrome.com/docs/web-platform/virtual-keyboard/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/VirtualKeyboard_API>

Visual Viewport API
===================


The **Visual Viewport API** provides an explicit mechanism for querying and modifying the properties of the window's [visual viewport](https://developer.mozilla.org/en-US/docs/Glossary/Visual_Viewport). The visual viewport is the visual portion of a screen excluding on-screen keyboards, areas outside of a pinch-zoom area, or any other on-screen artifact that doesn't scale with the dimensions of a page.


Visual Viewport concepts and usage
----------------------------------



The mobile web contains two viewports, the layout viewport and the visual viewport. The layout viewport covers all the elements on a page and the visual viewport is what is actually visible on the screen. When the user pinch-zooms into the page, the visual viewport shrinks but the layout viewport is unchanged. User-interface features like the on-screen keyboard (OSK) can shrink the visual viewport without affecting the layout viewport.

 What happens when a web page element needs to be visible on screen regardless of the visible portion of a web page? For example, what if you need a set of image controls to remain on screen regardless of the pinch zoom level of the device? Current browsers vary in how they handle this. The visual viewport lets web developers solve this by positioning elements relative to what's shown on screen.

 To access a window's visual viewport, you can obtain a [`VisualViewport`](visualviewport) object from the [`window.visualViewport`](window/visualviewport) property. The object includes a set of properties describing the viewport. It also adds two events, `onresize` and `onscroll`, that fire whenever the visual viewport changes. These events allow you to position elements relative to the visual viewport that would normally be anchored to the layout viewport.



Accessing the API
-----------------


 
[`window.visualViewport`](window/visualviewport) Read only 
  A read-only reference to the window's [`VisualViewport`](visualviewport) object. If this property doesn't exist, the API is unsupported.

  
Interfaces
----------


 [`VisualViewport`](visualviewport)  Represents the visual viewport for a given window. A window's `VisualViewport` object provides information about the viewport's position and size, and receives the [`resize`](visualviewport/resize_event) and [`scroll`](visualviewport/scroll_event) events you can monitor to know when changes occur to the window's viewport.

  
Example
-------



The code below is based on [the sample in the specification](https://github.com/WICG/visual-viewport/blob/gh-pages/examples/fixed-to-viewport.html), though it adds a few things that make it function better. It shows a function called `viewportHandler()`. When called it queries the `offsetLeft` and `height` properties for values it uses in a CSS `translate()` method. You invoke this function by passing it to *both* event calls.

 One thing that may not be clear in this example is the use of the `pendingUpdate` flag and the call to `requestAnimationFrame()`. The `pendingUpdate` flag serves to prevent multiple invocations of the transform that can occur when `onresize` and `onscroll` fire at the same time. Using `requestAnimationFrame()` ensures that the transform occurs before the next render.

 
```
let pendingUpdate = false;

function viewportHandler(event) {
  if (pendingUpdate) return;
  pendingUpdate = true;

  requestAnimationFrame(() => {
    pendingUpdate = false;
    const layoutViewport = document.getElementById("layoutViewport");

    // Since the bar is position: fixed we need to offset it by the
    // visual viewport's offset from the layout viewport origin.
    const viewport = event.target;
    const offsetLeft = viewport.offsetLeft;
    const offsetTop =
      viewport.height -
      layoutViewport.getBoundingClientRect().height +
      viewport.offsetTop;

    // You could also do this by setting style.left and style.top if you
    // use width: 100% instead.
    bottomBar.style.transform = `translate(${offsetLeft}px, ${offsetTop}px) scale(${
 1 / viewport.scale
 })`;
  });
}

window.visualViewport.addEventListener("scroll", viewportHandler);
window.visualViewport.addEventListener("resize", viewportHandler);

```


Specifications
--------------




| Specification |
| --- |
| [CSSOM View Module # the-visualviewport-interface](https://w3c.github.io/csswg-drafts/cssom-view/#the-visualviewport-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Visual_Viewport_API` | 61 | 79 | 91 | No | 48 | 13 | 61 | 61 | 68 | 45 | 13 | 8.0 |
| `height` | 61 | 79 | 91 | No | 48 | 13 | 61 | 61 | 68 | 45 | 13 | 8.0 |
| `offsetLeft` | 61 | 79 | 91 | No | 48 | 13 | 61 | 61 | 68 | 45 | 13 | 8.0 |
| `offsetTop` | 61 | 79 | 91 | No | 48 | 13 | 61 | 61 | 68 | 45 | 13 | 8.0 |
| `pageLeft` | 61 | 79 | 91 | No | 48 | 13 | 61 | 61 | 68 | 45 | 13 | 8.0 |
| `pageTop` | 61 | 79 | 91 | No | 48 | 13 | 61 | 61 | 68 | 45 | 13 | 8.0 |
| `resize_event` | 6261The `onresize` event handler property is not supported. | 79 | 91 | No | 4948The `onresize` event handler property is not supported. | 13 | 6261The `onresize` event handler property is not supported. | 6261The `onresize` event handler property is not supported. | 68 | 4645The `onresize` event handler property is not supported. | 13 | 8.0 |
| `scale` | 61 | 79 | 91 | No | 48 | 13 | 61 | 61 | 68 | 45 | 13 | 8.0 |
| `scroll_event` | 6261The `onscroll` event handler property is not supported. | 79 | 91 | No | 4948The `onscroll` event handler property is not supported. | 13 | 6261The `onscroll` event handler property is not supported. | 6261The `onscroll` event handler property is not supported. | 68 | 4645The `onscroll` event handler property is not supported. | 13 | 8.0 |
| `width` | 61 | 79 | 91 | No | 48 | 13 | 61 | 61 | 68 | 45 | 13 | 8.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Visual_Viewport_API>

Web Animations API
==================


The **Web Animations API** allows for synchronizing and timing changes to the presentation of a Web page, i.e. animation of DOM elements. It does so by combining two models: the Timing Model and the Animation Model.


Concepts and usage
------------------


The Web Animations API provides a common language for browsers and developers to describe animations on DOM elements. To get more information on the concepts behind the API and how to use it, read [Using the Web Animations API](web_animations_api/using_the_web_animations_api).


Web Animations interfaces
-------------------------


 [`Animation`](animation)  Provides playback controls and a timeline for an animation node or source. Can take an object created with the [`KeyframeEffect()`](keyframeeffect/keyframeeffect) constructor.

  [`KeyframeEffect`](keyframeeffect)  Describes sets of animatable properties and values, called **keyframes** and their timing options. These can then be played using the [`Animation()`](animation/animation) constructor.

  [`AnimationTimeline`](animationtimeline)  Represents the timeline of animation. This interface exists to define timeline features (inherited by [`DocumentTimeline`](documenttimeline) and future timeline objects) and is not itself accessed by developers.

  [`AnimationEvent`](animationevent)  Actually part of CSS Animations.

  [`DocumentTimeline`](documenttimeline)  Represents animation timelines, including the default document timeline (accessed using the [`Document.timeline`](document/timeline) property).

  
Extensions to other interfaces
------------------------------


The Web Animations API adds some new features to [`document`](document) and [`element`](element).


### Extensions to the `Document` interface


 [`document.timeline`](document/timeline)  The `DocumentTimeline` object representing the default document timeline.

  [`document.getAnimations()`](document/getanimations)  Returns an Array of [`Animation`](animation) objects currently in effect on elements in the `document`.

  
### Extensions to the `Element` interface


 [`Element.animate()`](element/animate)  A shortcut method for creating and playing an animation on an element. It returns the created [`Animation`](animation) object instance.

  [`Element.getAnimations()`](element/getanimations)  Returns an Array of [`Animation`](animation) objects currently affecting an element or which are scheduled to do so in future.

  
Specifications
--------------




| Specification |
| --- |
| [Web Animations](https://drafts.csswg.org/web-animations/)  |


See also
--------


* [Using the Web Animations API](web_animations_api/using_the_web_animations_api)
* [Web Animations demos](https://mozdevs.github.io/Animation-examples/)
* [Polyfill](https://github.com/web-animations/web-animations-js)
* Firefox's current implementation: [AreWeAnimatedYet](https://birtles.github.io/areweanimatedyet/)
* [Browser support test](https://codepen.io/danwilson/pen/xGBKVq)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API>

Web Audio API
=============


The Web Audio API provides a powerful and versatile system for controlling audio on the Web, allowing developers to choose audio sources, add effects to audio, create audio visualizations, apply spatial effects (such as panning) and much more.


Web audio concepts and usage
----------------------------



The Web Audio API involves handling audio operations inside an **audio context**, and has been designed to allow **modular routing**. Basic audio operations are performed with **audio nodes**, which are linked together to form an **audio routing graph**. Several sources — with different types of channel layout — are supported even within a single context. This modular design provides the flexibility to create complex audio functions with dynamic effects.

 Audio nodes are linked into chains and simple webs by their inputs and outputs. They typically start with one or more sources. Sources provide arrays of sound intensities (samples) at very small timeslices, often tens of thousands of them per second. These could be either computed mathematically (such as [`OscillatorNode`](oscillatornode)), or they can be recordings from sound/video files (like [`AudioBufferSourceNode`](audiobuffersourcenode) and [`MediaElementAudioSourceNode`](mediaelementaudiosourcenode)) and audio streams ([`MediaStreamAudioSourceNode`](mediastreamaudiosourcenode)). In fact, sound files are just recordings of sound intensities themselves, which come in from microphones or electric instruments, and get mixed down into a single, complicated wave.

 Outputs of these nodes could be linked to inputs of others, which mix or modify these streams of sound samples into different streams. A common modification is multiplying the samples by a value to make them louder or quieter (as is the case with [`GainNode`](gainnode)). Once the sound has been sufficiently processed for the intended effect, it can be linked to the input of a destination ([`BaseAudioContext.destination`](baseaudiocontext/destination)), which sends the sound to the speakers or headphones. This last connection is only necessary if the user is supposed to hear the audio.

 A simple, typical workflow for web audio would look something like this:

 1. Create audio context
2. Inside the context, create sources — such as `<audio>`, oscillator, stream
3. Create effects nodes, such as reverb, biquad filter, panner, compressor
4. Choose final destination of audio, for example your system speakers
5. Connect the sources up to the effects, and the effects to the destination.

  ![A simple box diagram with an outer box labeled Audio context, and three inner boxes labeled Sources, Effects and Destination. The three inner boxes have arrows between them pointing from left to right, indicating the flow of audio information.] 

 Timing is controlled with high precision and low latency, allowing developers to write code that responds accurately to events and is able to target specific samples, even at a high sample rate. So applications such as drum machines and sequencers are well within reach.

 The Web Audio API also allows us to control how audio is *spatialized*. Using a system based on a *source-listener model*, it allows control of the *panning model* and deals with *distance-induced attenuation* induced by a moving source (or moving listener).

  **Note:** You can read about the theory of the Web Audio API in a lot more detail in our article [Basic concepts behind Web Audio API](web_audio_api/basic_concepts_behind_web_audio_api).

 

Web Audio API target audience
-----------------------------



The Web Audio API can seem intimidating to those that aren't familiar with audio or music terms, and as it incorporates a great deal of functionality it can prove difficult to get started if you are a developer.

 It can be used to incorporate audio into your website or application, by [providing atmosphere like futurelibrary.no](https://www.futurelibrary.no/), or [auditory feedback on forms](https://css-tricks.com/form-validation-web-audio/). However, it can also be used to create *advanced* interactive instruments. With that in mind, it is suitable for both developers and musicians alike.

 We have a [simple introductory tutorial](web_audio_api/using_web_audio_api) for those that are familiar with programming but need a good introduction to some of the terms and structure of the API.

 There's also a [Basic Concepts Behind Web Audio API](web_audio_api/basic_concepts_behind_web_audio_api) article, to help you understand the way digital audio works, specifically in the realm of the API. This also includes a good introduction to some of the concepts the API is built upon.

 Learning coding is like playing cards — you learn the rules, then you play, then you go back and learn the rules again, then you play again. So if some of the theory doesn't quite fit after the first tutorial and article, there's an [advanced tutorial](web_audio_api/advanced_techniques) which extends the first one to help you practice what you've learnt, and apply some more advanced techniques to build up a step sequencer.

 We also have other tutorials and comprehensive reference material available that covers all features of the API. See the sidebar on this page for more.

 If you are more familiar with the musical side of things, are familiar with music theory concepts, want to start building instruments, then you can go ahead and start building things with the advanced tutorial and others as a guide (the above-linked tutorial covers scheduling notes, creating bespoke oscillators and envelopes, as well as an LFO among other things.)

 If you aren't familiar with the programming basics, you might want to consult some beginner's JavaScript tutorials first and then come back here — see our [Beginner's JavaScript learning module](https://developer.mozilla.org/en-US/docs/Learn/JavaScript) for a great place to begin.



Web Audio API interfaces
------------------------


The Web Audio API has a number of interfaces and associated events, which we have split up into nine categories of functionality.


### General audio graph definition



General containers and definitions that shape audio graphs in Web Audio API usage.

  [`AudioContext`](audiocontext)  The `AudioContext` interface represents an audio-processing graph built from audio modules linked together, each represented by an [`AudioNode`](audionode). An audio context controls the creation of the nodes it contains and the execution of the audio processing, or decoding. You need to create an `AudioContext` before you do anything else, as everything happens inside a context.

  [`AudioNode`](audionode)  The `AudioNode` interface represents an audio-processing module like an *audio source* (e.g. an HTML [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) or [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) element), *audio destination*, *intermediate processing module* (e.g. a filter like [`BiquadFilterNode`](biquadfilternode), or *volume control* like [`GainNode`](gainnode)).

  [`AudioParam`](audioparam)  The `AudioParam` interface represents an audio-related parameter, like one of an [`AudioNode`](audionode). It can be set to a specific value or a change in value, and can be scheduled to happen at a specific time and following a specific pattern.

  [`AudioParamMap`](audioparammap)  Provides a map-like interface to a group of [`AudioParam`](audioparam) interfaces, which means it provides the methods `forEach()`, `get()`, `has()`, `keys()`, and `values()`, as well as a `size` property.

  [`BaseAudioContext`](baseaudiocontext)  The `BaseAudioContext` interface acts as a base definition for online and offline audio-processing graphs, as represented by [`AudioContext`](audiocontext) and [`OfflineAudioContext`](offlineaudiocontext) respectively. You wouldn't use `BaseAudioContext` directly — you'd use its features via one of these two inheriting interfaces.

  The [`ended`](audioscheduledsourcenode/ended_event) event  The `ended` event is fired when playback has stopped because the end of the media was reached.

  

### Defining audio sources



Interfaces that define audio sources for use in the Web Audio API.

  [`AudioScheduledSourceNode`](audioscheduledsourcenode)  The `AudioScheduledSourceNode` is a parent interface for several types of audio source node interfaces. It is an [`AudioNode`](audionode).

  [`OscillatorNode`](oscillatornode)  The `OscillatorNode` interface represents a periodic waveform, such as a sine or triangle wave. It is an [`AudioNode`](audionode) audio-processing module that causes a given *frequency* of wave to be created.

  [`AudioBuffer`](audiobuffer)  The `AudioBuffer` interface represents a short audio asset residing in memory, created from an audio file using the [`BaseAudioContext.decodeAudioData`](baseaudiocontext/decodeaudiodata) method, or created with raw data using [`BaseAudioContext.createBuffer`](baseaudiocontext/createbuffer). Once decoded into this form, the audio can then be put into an [`AudioBufferSourceNode`](audiobuffersourcenode).

  [`AudioBufferSourceNode`](audiobuffersourcenode)  The `AudioBufferSourceNode` interface represents an audio source consisting of in-memory audio data, stored in an [`AudioBuffer`](audiobuffer). It is an [`AudioNode`](audionode) that acts as an audio source.

  [`MediaElementAudioSourceNode`](mediaelementaudiosourcenode)  The `MediaElementAudioSourceNode` interface represents an audio source consisting of an HTML [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) or [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) element. It is an [`AudioNode`](audionode) that acts as an audio source.

  [`MediaStreamAudioSourceNode`](mediastreamaudiosourcenode)  The `MediaStreamAudioSourceNode` interface represents an audio source consisting of a [`MediaStream`](mediastream) (such as a webcam, microphone, or a stream being sent from a remote computer). If multiple audio tracks are present on the stream, the track whose [`id`](mediastreamtrack/id) comes first lexicographically (alphabetically) is used. It is an [`AudioNode`](audionode) that acts as an audio source.

  [`MediaStreamTrackAudioSourceNode`](mediastreamtrackaudiosourcenode)  A node of type [`MediaStreamTrackAudioSourceNode`](mediastreamtrackaudiosourcenode) represents an audio source whose data comes from a [`MediaStreamTrack`](mediastreamtrack). When creating the node using the [`createMediaStreamTrackSource()`](audiocontext/createmediastreamtracksource) method to create the node, you specify which track to use. This provides more control than `MediaStreamAudioSourceNode`.

  

### Defining audio effects filters



Interfaces for defining effects that you want to apply to your audio sources.

  [`BiquadFilterNode`](biquadfilternode)  The `BiquadFilterNode` interface represents a simple low-order filter. It is an [`AudioNode`](audionode) that can represent different kinds of filters, tone control devices, or graphic equalizers. A `BiquadFilterNode` always has exactly one input and one output.

  [`ConvolverNode`](convolvernode)  The `ConvolverNode` interface is an [`AudioNode`](audionode) that performs a Linear Convolution on a given [`AudioBuffer`](audiobuffer), and is often used to achieve a reverb effect.

  [`DelayNode`](delaynode)  The `DelayNode` interface represents a [delay-line](https://en.wikipedia.org/wiki/Digital_delay_line); an [`AudioNode`](audionode) audio-processing module that causes a delay between the arrival of an input data and its propagation to the output.

  [`DynamicsCompressorNode`](dynamicscompressornode)  The `DynamicsCompressorNode` interface provides a compression effect, which lowers the volume of the loudest parts of the signal in order to help prevent clipping and distortion that can occur when multiple sounds are played and multiplexed together at once.

  [`GainNode`](gainnode)  The `GainNode` interface represents a change in volume. It is an [`AudioNode`](audionode) audio-processing module that causes a given *gain* to be applied to the input data before its propagation to the output.

  [`WaveShaperNode`](waveshapernode)  The `WaveShaperNode` interface represents a non-linear distorter. It is an [`AudioNode`](audionode) that use a curve to apply a waveshaping distortion to the signal. Beside obvious distortion effects, it is often used to add a warm feeling to the signal.

  [`PeriodicWave`](periodicwave)  Describes a periodic waveform that can be used to shape the output of an [`OscillatorNode`](oscillatornode).

  [`IIRFilterNode`](iirfilternode)  Implements a general [infinite impulse response](https://en.wikipedia.org/wiki/Infinite_impulse_response) (IIR) filter; this type of filter can be used to implement tone-control devices and graphic equalizers as well.

  

### Defining audio destinations



Once you are done processing your audio, these interfaces define where to output it.

  [`AudioDestinationNode`](audiodestinationnode)  The `AudioDestinationNode` interface represents the end destination of an audio source in a given context — usually the speakers of your device.

  [`MediaStreamAudioDestinationNode`](mediastreamaudiodestinationnode)  The `MediaStreamAudioDestinationNode` interface represents an audio destination consisting of a [WebRTC](webrtc_api) [`MediaStream`](mediastream) with a single `AudioMediaStreamTrack`, which can be used in a similar way to a [`MediaStream`](mediastream) obtained from [`getUserMedia()`](mediadevices/getusermedia). It is an [`AudioNode`](audionode) that acts as an audio destination.

  

### Data analysis and visualization



If you want to extract time, frequency, and other data from your audio, the `AnalyserNode` is what you need.

  [`AnalyserNode`](analysernode)  The `AnalyserNode` interface represents a node able to provide real-time frequency and time-domain analysis information, for the purposes of data analysis and visualization.

  

### Splitting and merging audio channels



To split and merge audio channels, you'll use these interfaces.

  [`ChannelSplitterNode`](channelsplitternode)  The `ChannelSplitterNode` interface separates the different channels of an audio source out into a set of *mono* outputs.

  [`ChannelMergerNode`](channelmergernode)  The `ChannelMergerNode` interface reunites different mono inputs into a single output. Each input will be used to fill a channel of the output.

  

### Audio spatialization



These interfaces allow you to add audio spatialization panning effects to your audio sources.

  [`AudioListener`](audiolistener)  The `AudioListener` interface represents the position and orientation of the unique person listening to the audio scene used in audio spatialization.

  [`PannerNode`](pannernode)  The `PannerNode` interface represents the position and behavior of an audio source signal in 3D space, allowing you to create complex panning effects.

  [`StereoPannerNode`](stereopannernode)  The `StereoPannerNode` interface represents a simple stereo panner node that can be used to pan an audio stream left or right.

  

### Audio processing in JavaScript



Using audio worklets, you can define custom audio nodes written in JavaScript or [WebAssembly](https://developer.mozilla.org/en-US/docs/WebAssembly). Audio worklets implement the [`Worklet`](worklet) interface, a lightweight version of the [`Worker`](worker) interface.

  [`AudioWorklet`](audioworklet)  The `AudioWorklet` interface is available through the [`AudioContext`](audiocontext) object's [`audioWorklet`](baseaudiocontext/audioworklet), and lets you add modules to the audio worklet to be executed off the main thread.

  [`AudioWorkletNode`](audioworkletnode)  The `AudioWorkletNode` interface represents an [`AudioNode`](audionode) that is embedded into an audio graph and can pass messages to the corresponding `AudioWorkletProcessor`.

  [`AudioWorkletProcessor`](audioworkletprocessor)  The `AudioWorkletProcessor` interface represents audio processing code running in a `AudioWorkletGlobalScope` that generates, processes, or analyzes audio directly, and can pass messages to the corresponding `AudioWorkletNode`.

  [`AudioWorkletGlobalScope`](audioworkletglobalscope)  The `AudioWorkletGlobalScope` interface is a `WorkletGlobalScope`-derived object representing a worker context in which an audio processing script is run; it is designed to enable the generation, processing, and analysis of audio data directly using JavaScript in a worklet thread rather than on the main thread.

   #### Obsolete: script processor nodes

 Before audio worklets were defined, the Web Audio API used the `ScriptProcessorNode` for JavaScript-based audio processing. Because the code runs in the main thread, they have bad performance. The `ScriptProcessorNode` is kept for historic reasons but is marked as deprecated.

  
[`ScriptProcessorNode`](scriptprocessornode)  Deprecated 
  The `ScriptProcessorNode` interface allows the generation, processing, or analyzing of audio using JavaScript. It is an [`AudioNode`](audionode) audio-processing module that is linked to two buffers, one containing the current input, one containing the output. An event, implementing the [`AudioProcessingEvent`](audioprocessingevent) interface, is sent to the object each time the input buffer contains new data, and the event handler terminates when it has filled the output buffer with data.

  
[`audioprocess`](scriptprocessornode/audioprocess_event) (event)  Deprecated 
  The `audioprocess` event is fired when an input buffer of a Web Audio API [`ScriptProcessorNode`](scriptprocessornode) is ready to be processed.

  
[`AudioProcessingEvent`](audioprocessingevent)  Deprecated 
  The `AudioProcessingEvent` represents events that occur when a [`ScriptProcessorNode`](scriptprocessornode) input buffer is ready to be processed.

  

### Offline/background audio processing



It is possible to process/render an audio graph very quickly in the background — rendering it to an [`AudioBuffer`](audiobuffer) rather than to the device's speakers — with the following.

  [`OfflineAudioContext`](offlineaudiocontext)  The `OfflineAudioContext` interface is an [`AudioContext`](audiocontext) interface representing an audio-processing graph built from linked together [`AudioNode`](audionode)s. In contrast with a standard `AudioContext`, an `OfflineAudioContext` doesn't really render the audio but rather generates it, *as fast as it can*, in a buffer.

  
[`complete`](offlineaudiocontext/complete_event) (event)  The `complete` event is fired when the rendering of an [`OfflineAudioContext`](offlineaudiocontext) is terminated.

  [`OfflineAudioCompletionEvent`](offlineaudiocompletionevent)  The `OfflineAudioCompletionEvent` represents events that occur when the processing of an [`OfflineAudioContext`](offlineaudiocontext) is terminated. The [`complete`](offlineaudiocontext/complete_event) event uses this interface.

  

Guides and tutorials
--------------------



[Advanced techniques: Creating and sequencing audio](web_audio_api/advanced_techniques)
In this tutorial, we're going to cover sound creation and modification, as well as timing and scheduling. We will introduce sample loading, envelopes, filters, wavetables, and frequency modulation. If you're familiar with these terms and looking for an introduction to their application with the Web Audio API, you've come to the right place.


[Background audio processing using AudioWorklet](web_audio_api/using_audioworklet)
This article explains how to create an audio worklet processor and use it in a Web Audio application.


[Basic concepts behind Web Audio API](web_audio_api/basic_concepts_behind_web_audio_api)
This article explains some of the audio theory behind how the features of the Web Audio API work to help you make informed decisions while designing how your app routes audio. If you are not already a sound engineer, it will give you enough background to understand why the Web Audio API works as it does.


[Controlling multiple parameters with ConstantSourceNode](web_audio_api/controlling_multiple_parameters_with_constantsourcenode)
This article demonstrates how to use a `ConstantSourceNode` to link multiple parameters together so they share the same value, which can be changed by setting the value of the `ConstantSourceNode.offset` parameter.


[Example and tutorial: Simple synth keyboard](web_audio_api/simple_synth)
This article presents the code and working demo of a video keyboard you can play using the mouse. The keyboard allows you to switch among the standard waveforms as well as one custom waveform, and you can control the main gain using a volume slider beneath the keyboard. This example makes use of the following Web API interfaces: `AudioContext`, `OscillatorNode`, `PeriodicWave`, and `GainNode`.


[Migrating from webkitAudioContext](web_audio_api/migrating_from_webkitaudiocontext)
In this article, we cover the differences in Web Audio API since it was first implemented in WebKit and how to update your code to use the modern Web Audio API.


[Tools for analyzing Web Audio usage](web_audio_api/tools)
While working on your Web Audio API code, you may find that you need tools to analyze the graph of nodes you create or to otherwise debug your work. This article discusses tools available to help you do that.


[Using IIR filters](web_audio_api/using_iir_filters)
The `IIRFilterNode` interface of the [Web Audio API](web_audio_api) is an `AudioNode` processor that implements a general [infinite impulse response](https://en.wikipedia.org/wiki/Infinite_impulse_response) (IIR) filter; this type of filter can be used to implement tone control devices and graphic equalizers, and the filter response parameters can be specified, so that it can be tuned as needed. This article looks at how to implement one, and use it in a simple example.


[Using the Web Audio API](web_audio_api/using_web_audio_api)
Let's take a look at getting started with the [Web Audio API](web_audio_api). We'll briefly look at some concepts, then study a simple boombox example that allows us to load an audio track, play and pause it, and change its volume and stereo panning.


[Visualizations with Web Audio API](web_audio_api/visualizations_with_web_audio_api)
One of the most interesting features of the Web Audio API is the ability to extract frequency, waveform, and other data from your audio source, which can then be used to create visualizations. This article explains how, and provides a couple of basic use cases.


[Web Audio API best practices](web_audio_api/best_practices)
There's no strict right or wrong way when writing creative code. As long as you consider security, performance, and accessibility, you can adapt to your own style. In this article, we'll share a number of *best practices* — guidelines, tips, and tricks for working with the Web Audio API.


[Web audio spatialization basics](web_audio_api/web_audio_spatialization_basics)
As if its extensive variety of sound processing (and other) options wasn't enough, the Web Audio API also includes facilities to allow you to emulate the difference in sound as a listener moves around a sound source, for example panning as you move around a sound source inside a 3D game. The official term for this is **spatialization**, and this article will cover the basics of how to implement such a system.



Examples
--------


You can find a number of examples at our [webaudio-example repo](https://github.com/mdn/webaudio-examples/) on GitHub.


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # AudioContext](https://webaudio.github.io/web-audio-api/#AudioContext) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AudioContext` | 35["Before Chrome 66, each tab is limited to 6 audio contexts in Chrome; attempting to create more will throw a `DOMException`. For details see [Per-tab audio context limitation in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Per-tab_audio_context_limitation_in_Chrome).", "If `latencyHint` isn't valid, Chrome throws a `TypeError` exception. See [Non-standard exceptions in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Non-standard_exceptions_in_Chrome) for details."]14–57 | 12 | 25 | No | 22["Before Opera 53, each tab is limited to 6 audio contexts in Opera; attempting to create more will throw a `DOMException`. For details see [Per-tab audio context limitation in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Per-tab_audio_context_limitation_in_Chrome).", "If `latencyHint` isn't valid, Opera throws a `TypeError` exception. See [Non-standard exceptions in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Non-standard_exceptions_in_Chrome) for details."]15–44 | 14.16 | 37["Before WebView 66, each tab is limited to 6 audio contexts in WebView; attempting to create more will throw a `DOMException`. For details see [Per-tab audio context limitation in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Per-tab_audio_context_limitation_in_Chrome).", "If `latencyHint` isn't valid, WebView throws a `TypeError` exception. See [Non-standard exceptions in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Non-standard_exceptions_in_Chrome) for details."]≤37–57 | 35["Before Chrome 66, each tab is limited to 6 audio contexts in Chrome; attempting to create more will throw a `DOMException`. For details see [Per-tab audio context limitation in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Per-tab_audio_context_limitation_in_Chrome).", "If `latencyHint` isn't valid, Chrome throws a `TypeError` exception. See [Non-standard exceptions in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Non-standard_exceptions_in_Chrome) for details."]18–57 | 25 | 22["Before Opera Android 47, each tab is limited to 6 audio contexts in Opera; attempting to create more will throw a `DOMException`. For details see [Per-tab audio context limitation in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Per-tab_audio_context_limitation_in_Chrome).", "If `latencyHint` isn't valid, Opera throws a `TypeError` exception. See [Non-standard exceptions in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Non-standard_exceptions_in_Chrome) for details."]14–43 | 14.56 | 3.0["Before Samsung Internet 9.0, each tab is limited to 6 audio contexts in Samsung Internet; attempting to create more will throw a `DOMException`. For details see [Per-tab audio context limitation in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Per-tab_audio_context_limitation_in_Chrome).", "If `latencyHint` isn't valid, Samsung Internet throws a `TypeError` exception. See [Non-standard exceptions in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Non-standard_exceptions_in_Chrome) for details."]1.0–7.0 |
| `Web_Audio_API` | 3514–57 | 12 | 25 | No | 2215–44 | 14.16–14.1 | 374.4–57 | 3518–57 | 25 | 2214–43 | 14.56–14.5 | 3.01.0–7.0 |
| `baseLatency` | 58 | 79 | 70 | No | 45 | 14.1 | 58 | 58 | 79 | 43 | 14.5 | 7.0 |
| `close` | 42 | 14 | 40 | No | 29 | 9 | 42 | 42 | 40 | 29 | 9 | 4.0 |
| `createMediaElementSource` | 15 | 12 | 25 | No | 15 | 6 | ≤37 | 18 | 25 | 14 | 6 | 1.0 |
| `createMediaStreamDestination` | 25 | 79 | 25 | No | 15 | 11 | ≤37 | 25 | 25 | 14 | 11 | 1.5 |
| `createMediaStreamSource` | 22 | 12 | 25 | No | 15 | 11 | ≤37 | 25 | 25 | 14 | 11 | 1.5 |
| `createMediaStreamTrackSource` | No | No | 68Firefox 68 implements the updated standard's definition of the "first" audio track; now the first track is the one whose ID comes first lexicographically. | No | No | No | No | No | 68Firefox 68 implements the updated standard's definition of the "first" audio track; now the first track is the one whose ID comes first lexicographically. | No | No | No |
| `getOutputTimestamp` | 57 | 79 | 70 | No | 44 | 14.1 | 57 | 57 | 79 | 43 | 14.5 | 7.0 |
| `outputLatency` | 102 | 102 | 70 | No | 88 | No | 102 | 102 | 79 | 70 | No | 19.0 |
| `resume` | 41 | 14 | 40 | No | 28 | 9 | 41 | 41 | 40 | 28 | 9 | 4.0 |
| `setSinkId` | 110 | 110 | No | No | 96 | No | 110 | 110 | No | 74 | No | No |
| `sinkId` | 110 | 110 | No | No | 96 | No | 110 | 110 | No | 74 | No | No |
| `sinkchange_event` | 110 | 110 | No | No | 96 | No | 110 | 110 | No | 74 | No | No |
| `suspend` | 41 | 14 | 40 | No | 28 | 9 | 41 | 41 | 40 | 28 | 9 | 4.0 |


### AudioContext


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


See also
--------


### Tutorials/guides


* [Basic concepts behind Web Audio API](web_audio_api/basic_concepts_behind_web_audio_api)
* [Using the Web Audio API](web_audio_api/using_web_audio_api)
* [Advanced techniques: creating sound, sequencing, timing, scheduling](web_audio_api/advanced_techniques)
* [Autoplay guide for media and Web Audio APIs](https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide)
* [Using IIR filters](web_audio_api/using_iir_filters)
* [Visualizations with Web Audio API](web_audio_api/visualizations_with_web_audio_api)
* [Web audio spatialization basics](web_audio_api/web_audio_spatialization_basics)
* [Controlling multiple parameters with ConstantSourceNode](web_audio_api/controlling_multiple_parameters_with_constantsourcenode)
* [Mixing Positional Audio and WebGL (2012)](https://web.dev/webaudio-positional-audio/)
* [Developing Game Audio with the Web Audio API (2012)](https://auth.web.dev/webaudio-games/)
* [Porting webkitAudioContext code to standards based AudioContext](web_audio_api/migrating_from_webkitaudiocontext)

### Libraries


* [Tones](https://github.com/bit101/tones): a simple library for playing specific tones/notes using the Web Audio API.
* [Tone.js](https://tonejs.github.io/): a framework for creating interactive music in the browser.
* [howler.js](https://github.com/goldfire/howler.js/): a JS audio library that defaults to [Web Audio API](https://webaudio.github.io/web-audio-api/) and falls back to [HTML Audio](https://html.spec.whatwg.org/multipage/media.html#the-audio-element), as well as providing other useful features.
* [Mooog](https://github.com/mattlima/mooog): jQuery-style chaining of AudioNodes, mixer-style sends/returns, and more.
* [XSound](https://xsound.jp/): Web Audio API Library for Synthesizer, Effects, Visualization, Recording, etc.
* [OpenLang](https://github.com/chrisjohndigital/OpenLang): HTML video language lab web application using the Web Audio API to record and combine video and audio from different sources into a single file ([source on GitHub](https://github.com/chrisjohndigital/OpenLang))
* [Pts.js](https://ptsjs.org/): Simplifies web audio visualization ([guide](https://ptsjs.org/guide/sound-0800))

### Related topics


* [Web media technologies](https://developer.mozilla.org/en-US/docs/Web/Media)
* [Guide to media types and formats on the web](https://developer.mozilla.org/en-US/docs/Web/Media/Formats)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API>

Web Authentication API
======================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The Web Authentication API is an extension of the [Credential Management API](credential_management_api) that enables strong authentication with public key cryptography, enabling passwordless authentication and/or secure second-factor authentication without SMS texts.



Web authentication concepts and usage
-------------------------------------



The Web Authentication API (also referred to as WebAuthn) uses [asymmetric (public-key)](https://en.wikipedia.org/wiki/Public-key_cryptography) instead of passwords or SMS texts for registering, authenticating, and [second-factor authentication](https://en.wikipedia.org/wiki/Multi-factor_authentication) with websites. This has some benefits:

 * **Protection against phishing:** An attacker who creates a fake login website can't login as the user because the signature changes with the [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin) of the website.
* **Reduced impact of data breaches:** Developers don't need to hash the public key, and if an attacker gets access to the public key used to verify the authentication, it can't authenticate because it needs the private key.
* **Invulnerable to password attacks:** Some users might reuse passwords, and an attacker may obtain the user's password for another website (e.g. via a data breach). Also, text passwords are much easier to brute-force than a digital signature.

 Many websites already have pages that allow users to register new accounts or sign in to an existing account, and the Web Authentication API acts as a replacement or supplement to those on those existing webpages. Similar to the other forms of the [Credential Management API](credential_management_api), the Web Authentication API has two basic methods that correspond to register and login:

 * [`navigator.credentials.create()`](credentialscontainer/create) - when used with the publicKey option, creates new credentials, either for registering a new account or for associating a new asymmetric key pair credentials with an existing account.
* [`navigator.credentials.get()`](credentialscontainer/get) - when used with the publicKey option, uses an existing set of credentials to authenticate to a service, either logging a user in or as a form of second-factor authentication.

  **Note:** Both `create()` and `get()` require a [secure context](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (i.e. the server is connected by HTTPS or is the localhost), and will not be available for use if the browser is not operating in a secure context.

  In their most basic forms, both `create()` and `get()` receive a very large random number called the "challenge" from the server and they return the challenge signed by the private key back to the server. This proves to the server that a user is in possession of the private key required for authentication without revealing any secrets over the network.

 In order to understand how the create() and get() methods fit into the bigger picture, it is important to understand that they sit between two components that are outside the browser:

 1. **Server** - the Web Authentication API is intended to register new credentials on a server (also referred to as a service or a [relying party](https://en.wikipedia.org/wiki/Relying_party)) and later use those same credentials on that same server to authenticate a user.
2. **Authenticator** - the credentials are created and stored in a device called an authenticator. This is a new concept in authentication: when authenticating using passwords, the password is stored in a user's brain and no other device is needed; when authenticating using web authentication, the password is replaced with a key pair that is stored in an authenticator. The authenticator may be embedded into the user agent, into an operating system, such as Windows Hello, or it may be a physical token, such as a USB or Bluetooth Security Key.



### Registration



A typical registration process has six steps, as illustrated in Figure 1 and described further below. This is a simplification of the data required for the registration process that is only intended to provide an overview. The full set of required fields, optional fields, and their meanings for creating a registration request can be found in the [`PublicKeyCredentialCreationOptions`](credentialscontainer/create) dictionary. Likewise, the full set of response fields can be found in the [`PublicKeyCredential`](publickeycredential) interface (where [`PublicKeyCredential.response`](publickeycredential/response) is the [`AuthenticatorAttestationResponse`](authenticatorattestationresponse) interface). Note most JavaScript programmers that are creating an application will only really care about steps 1 and 5 where the create() function is called and subsequently returns; however, steps 2, 3, and 4 are essential to understanding the processing that takes place in the browser and authenticator and what the resulting data means.

  ![Web Authentication API registration component and dataflow diagram] 

 *Figure 1 - a diagram showing the sequence of actions for a web authentication registration and the essential data associated with each action.*

 First (labeled step 0 in the diagram), the application makes the initial registration request. The protocol and format of this request are outside the scope of the Web Authentication API.

 After this, the registration steps are:

 1. **Server Sends Challenge, User Info, and Relying Party Info** - The server sends a challenge, user information, and relying party information to the JavaScript program. The protocol for communicating with the server is not specified and is outside of the scope of the Web Authentication API. Typically, server communications would be [REST](https://developer.mozilla.org/en-US/docs/Glossary/REST) over https (probably using [XMLHttpRequest](xmlhttprequest) or [Fetch](fetch_api)), but they could also be [SOAP](https://developer.mozilla.org/en-US/docs/Glossary/SOAP), [RFC 2549](https://datatracker.ietf.org/doc/html/rfc2549) or nearly any other protocol provided that the protocol is secure. The parameters received from the server will be passed to the [create()](credentialscontainer/create) call, typically with little or no modification and returns a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will resolve to a [`PublicKeyCredential`](publickeycredential) containing an [`AuthenticatorAttestationResponse`](authenticatorattestationresponse). **Note that it is absolutely critical that the challenge be a buffer of random information (at least 16 bytes) and it MUST be generated on the server in order to ensure the security of the registration process.**
2. **Browser Calls authenticatorMakeCredential() on Authenticator** - Internally, the browser will validate the parameters and fill in any defaults, which become the [`AuthenticatorResponse.clientDataJSON`](authenticatorresponse/clientdatajson). One of the most important parameters is the origin, which is recorded as part of the clientData so that the origin can be verified by the server later. The parameters to the create() call are passed to the authenticator, along with a SHA-256 hash of the clientDataJSON (only a hash is sent because the link to the authenticator may be a low-bandwidth NFC or Bluetooth link and the authenticator is just going to sign over the hash to ensure that it isn't tampered with).
3. **Authenticator Creates New Key Pair and Attestation** - Before doing anything, the authenticator will typically ask for some form of user verification. This could be entering a PIN, using a fingerprint, doing an iris scan, etc. to prove that the user is present and consenting to the registration. After the user verification, the authenticator will create a new asymmetric key pair and safely store the private key for future reference. The public key will become part of the attestation, which the authenticator will sign over with a private key that was burned into the authenticator during its manufacturing process and that has a certificate chain that can be validated back to a root of trust.
4. **Authenticator Returns Data to Browser** - The new public key, a globally unique credential id, and other attestation data are returned to the browser where they become the attestationObject.
5. **Browser Creates Final Data, Application sends response to Server** - The create() Promise resolves to an [`PublicKeyCredential`](publickeycredential), which has a [`PublicKeyCredential.rawId`](publickeycredential/rawid) that is the globally unique credential id along with a response that is the [`AuthenticatorAttestationResponse`](authenticatorattestationresponse) containing the [`AuthenticatorResponse.clientDataJSON`](authenticatorresponse/clientdatajson) and [`AuthenticatorAttestationResponse.attestationObject`](authenticatorattestationresponse/attestationobject). The [`PublicKeyCredential`](publickeycredential) is sent back to the server using any desired formatting and protocol (note that the ArrayBuffer properties need to be base64 encoded or similar).
6. **Server Validates and Finalizes Registration** - Finally, the server is required to perform a series of checks to ensure that the registration was complete and not tampered with. These include:
	1. Verifying that the challenge is the same as the challenge that was sent
	2. Ensuring that the origin was the origin expected
	3. Validating that the signature over the clientDataHash and the attestation using the certificate chain for that specific model of the authenticatorA complete list of validation steps [can be found in the Web Authentication API specification](https://w3c.github.io/webauthn/#registering-a-new-credential). Assuming that the checks pan out, the server will store the new public key associated with the user's account for future use — that is, whenever the user desires to use the public key for authentication.



### Authentication



After a user has registered with web authentication, they can subsequently authenticate (a.k.a. - login or sign-in) with the service. The authentication flow looks similar to the registration flow, and the illustration of actions in Figure 2 may be recognizable as being similar to the illustration of registration actions in Figure 1. The primary differences between registration and authentication are that: 1) authentication doesn't require user or relying party information; and 2) authentication creates an assertion using the previously generated key pair for the service rather than creating an attestation with the key pair that was burned into the authenticator during manufacturing. Again, the description of authentication below is a broad overview rather than getting into all the options and features of the Web Authentication API. The specific options for authenticating can be found in the [`PublicKeyCredentialRequestOptions`](publickeycredentialrequestoptions) dictionary, and the resulting data can be found in the [`PublicKeyCredential`](publickeycredential) interface (where [`PublicKeyCredential.response`](publickeycredential/response) is the [`AuthenticatorAssertionResponse`](authenticatorassertionresponse) interface) .

  ![WebAuthn authentication component and dataflow diagram] 

 *Figure 2 - similar to Figure 1, a diagram showing the sequence of actions for a web authentication and the essential data associated with each action.*

 First (labeled step 0 in the diagram), the application makes the initial authentication request. The protocol and format of this request are outside the scope of the Web Authentication API.

 After this, the authentication steps are:

 1. **Server Sends Challenge** - The server sends a challenge to the JavaScript program. The protocol for communicating with the server is not specified and is outside of the scope of the Web Authentication API. Typically, server communications would be [REST](https://developer.mozilla.org/en-US/docs/Glossary/REST) over https (probably using [XMLHttpRequest](xmlhttprequest) or [Fetch](fetch_api)), but they could also be [SOAP](https://developer.mozilla.org/en-US/docs/Glossary/SOAP), [RFC 2549](https://datatracker.ietf.org/doc/html/rfc2549) or nearly any other protocol provided that the protocol is secure. The parameters received from the server will be passed to the [get()](credentialscontainer/get) call, typically with little or no modification. **Note that it is absolutely critical that the challenge be a buffer of random information (at least 16 bytes) and it MUST be generated on the server in order to ensure the security of the authentication process.**
2. **Browser Calls authenticatorGetCredential() on Authenticator** - Internally, the browser will validate the parameters and fill in any defaults, which become the [`AuthenticatorResponse.clientDataJSON`](authenticatorresponse/clientdatajson). One of the most important parameters is the origin, which recorded as part of the clientData so that the origin can be verified by the server later. The parameters to the get() call are passed to the authenticator, along with a SHA-256 hash of the clientDataJSON (only a hash is sent because the link to the authenticator may be a low-bandwidth NFC or Bluetooth link and the authenticator is just going to sign over the hash to ensure that it isn't tampered with).
3. **Authenticator Creates an Assertion** - The authenticator finds a credential for this service that matches the Relying Party ID and prompts a user to consent to the authentication. Assuming both of those steps are successful, the authenticator will create a new assertion by signing over the clientDataHash and authenticatorData with the private key generated for this account during the registration call.
4. **Authenticator Returns Data to Browser** - The authenticator returns the authenticatorData and assertion signature back to the browser.
5. **Browser Creates Final Data, Application sends response to Server** - The browser resolves the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) to a [`PublicKeyCredential`](publickeycredential) with a [`PublicKeyCredential.response`](publickeycredential/response) that contains the [`AuthenticatorAssertionResponse`](authenticatorassertionresponse). It is up to the JavaScript application to transmit this data back to the server using any protocol and format of its choice.
6. **Server Validates and Finalizes Authentication** - Upon receiving the result of the authentication request, the server performs validation of the response such as:
	1. Using the public key that was stored during the registration request to validate the signature by the authenticator.
	2. Ensuring that the challenge that was signed by the authenticator matches the challenge that was generated by the server.
	3. Checking that the Relying Party ID is the one expected for this service.A full list of the [steps for validating an assertion can be found in the Web Authentication API specification](https://w3c.github.io/webauthn/#verifying-assertion). Assuming the validation is successful, the server will note that the user is now authenticated. This is outside the scope of the Web Authentication API specification, but one option would be to drop a new cookie for the user session.



Interfaces
----------


 
[`Credential`](credential)  Experimental 
  Provides information about an entity as a prerequisite to a trust decision.

  [`CredentialsContainer`](credentialscontainer)  Exposes methods to request credentials and notify the user agent when events such as successful sign in or sign out happen. This interface is accessible from [`Navigator.credentials`](navigator/credentials). The Web Authentication specification adds a `publicKey` member to the [`create()`](credentialscontainer/create) and [`get()`](credentialscontainer/get) methods to either create a new public key pair or get an authentication for a key pair, respectively.

  [`PublicKeyCredential`](publickeycredential)  Provides information about a public key / private key pair, which is a credential for logging in to a service using an un-phishable and data-breach resistant asymmetric key pair instead of a password.

  [`AuthenticatorResponse`](authenticatorresponse)  The base interface for [`AuthenticatorAttestationResponse`](authenticatorattestationresponse) and [`AuthenticatorAssertionResponse`](authenticatorassertionresponse), which provide a cryptographic root of trust for a key pair. Returned by [`CredentialsContainer.create()`](credentialscontainer/create) and [`CredentialsContainer.get()`](credentialscontainer/get), respectively, the child interfaces include information from the browser such as the challenge origin. Either may be returned from [`PublicKeyCredential.response`](publickeycredential/response).

  [`AuthenticatorAttestationResponse`](authenticatorattestationresponse)  Returned by [`CredentialsContainer.create()`](credentialscontainer/create) when a [`PublicKeyCredential`](publickeycredential) is passed, and provides a cryptographic root of trust for the new key pair that has been generated.

  [`AuthenticatorAssertionResponse`](authenticatorassertionresponse)  Returned by [`CredentialsContainer.get()`](credentialscontainer/get) when a [`PublicKeyCredential`](publickeycredential) is passed, and provides proof to a service that it has a key pair and that the authentication request is valid and approved.

  
Options
-------


 [`PublicKeyCredentialCreationOptions`](credentialscontainer/create)  The options passed to [`CredentialsContainer.create()`](credentialscontainer/create).

  [`PublicKeyCredentialRequestOptions`](publickeycredentialrequestoptions)  The options passed to [`CredentialsContainer.get()`](credentialscontainer/get).

  
Examples
--------


### Demo sites


* [Mozilla Demo](https://webauthn.bin.coffee/) website and its [source code](https://github.com/jcjones/webauthn.bin.coffee).
* [Google Demo](https://try-webauthn.appspot.com/) website and its [source code](https://github.com/google/webauthndemo).
* [https://webauthn.io/ Demo](https://github.com/duo-labs/webauthn.io) website and its [source code](https://github.com/duo-labs/webauthn.io).
* [github.com/webauthn-open-source](https://github.com/webauthn-open-source) and its [client source code](https://github.com/webauthn-open-source/webauthn-simple-app) and [server source code](https://github.com/webauthn-open-source/fido2-lib)
* [OWASP Single Sign-On](https://owasp.org/www-project-sso/)

### Usage example



 **Warning:** For security reasons, web authentication calls ([`create()`](credentialscontainer/create) and [`get()`](credentialscontainer/get)) are cancelled if the browser window loses focus while the call is pending.

  
```
// sample arguments for registration
const createCredentialDefaultArgs = {
  publicKey: {
    // Relying Party (a.k.a. - Service):
    rp: {
      name: "Acme",
    },

    // User:
    user: {
      id: new Uint8Array(16),
      name: "carina.p.anand@example.com",
      displayName: "Carina P. Anand",
    },

    pubKeyCredParams: [
      {
        type: "public-key",
        alg: -7,
      },
    ],

    attestation: "direct",

    timeout: 60000,

    challenge: new Uint8Array([
      // must be a cryptographically random number sent from a server
      0x8c, 0x0a, 0x26, 0xff, 0x22, 0x91, 0xc1, 0xe9, 0xb9, 0x4e, 0x2e, 0x17, 0x1a,
      0x98, 0x6a, 0x73, 0x71, 0x9d, 0x43, 0x48, 0xd5, 0xa7, 0x6a, 0x15, 0x7e, 0x38,
      0x94, 0x52, 0x77, 0x97, 0x0f, 0xef,
    ]).buffer,
  },
};

// sample arguments for login
const getCredentialDefaultArgs = {
  publicKey: {
    timeout: 60000,
    // allowCredentials: [newCredential] // see below
    challenge: new Uint8Array([
      // must be a cryptographically random number sent from a server
      0x79, 0x50, 0x68, 0x71, 0xda, 0xee, 0xee, 0xb9, 0x94, 0xc3, 0xc2, 0x15, 0x67,
      0x65, 0x26, 0x22, 0xe3, 0xf3, 0xab, 0x3b, 0x78, 0x2e, 0xd5, 0x6f, 0x81, 0x26,
      0xe2, 0xa6, 0x01, 0x7d, 0x74, 0x50,
    ]).buffer,
  },
};

// register / create a new credential
navigator.credentials
  .create(createCredentialDefaultArgs)
  .then((cred) => {
    console.log("NEW CREDENTIAL", cred);

    // normally the credential IDs available for an account would come from a server
    // but we can just copy them from above…
    const idList = [
      {
        id: cred.rawId,
        transports: ["usb", "nfc", "ble"],
        type: "public-key",
      },
    ];
    getCredentialDefaultArgs.publicKey.allowCredentials = idList;
    return navigator.credentials.get(getCredentialDefaultArgs);
  })
  .then((assertion) => {
    console.log("ASSERTION", assertion);
  })
  .catch((err) => {
    console.log("ERROR", err);
  });

```


Specifications
--------------




| Specification |
| --- |
| [Credential Management Level 1 # the-credential-interface](https://w3c.github.io/webappsec-credential-management/#the-credential-interface) |
| [Credential Management Level 1 # credentialscontainer](https://w3c.github.io/webappsec-credential-management/#credentialscontainer) |
| [Web Authentication: An API for accessing Public Key Credentials - Level 3 # iface-pkcredential](https://w3c.github.io/webauthn/#iface-pkcredential) |
| [Web Authentication: An API for accessing Public Key Credentials - Level 3 # authenticatorresponse](https://w3c.github.io/webauthn/#authenticatorresponse) |
| [Web Authentication: An API for accessing Public Key Credentials - Level 3 # authenticatorattestationresponse](https://w3c.github.io/webauthn/#authenticatorattestationresponse) |
| [Web Authentication: An API for accessing Public Key Credentials - Level 3 # iface-authenticatorassertionresponse](https://w3c.github.io/webauthn/#iface-authenticatorassertionresponse) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Web_Authentication_API` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 48 | 13 | 10.0 |
| `authenticatorData` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 48 | 13 | 10.0 |
| `signature` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 48 | 13 | 10.0 |
| `userHandle` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 48 | 13 | 10.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Web_Authentication_API` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 48 | 13 | 10.0 |
| `attestationObject` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 48 | 13 | 10.0 |
| `getAuthenticatorData` | 85 | 85 | No | No | 71 | 16 | No | 85 | No | 60 | 16 | 14.0 |
| `getPublicKey` | 85 | 85 | No | No | 71 | 16 | No | 85 | No | 60 | 16 | 14.0 |
| `getPublicKeyAlgorithm` | 85 | 85 | No | No | 71 | 16 | No | 85 | No | 60 | 16 | 14.0 |
| `getTransports` | 74 | 79 | No | No | 62 | 16 | No | 74 | No | 53 | 16 | 11.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Web_Authentication_API` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 48 | 13 | 10.0 |
| `clientDataJSON` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 48 | 13 | 10.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Web_Authentication_API` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 49 | 13 | 10.0 |
| `authenticatorAttachment` | 98 | 98 | No | No | 84 | 15.5 | No | 98 | No | 68 | 15.5 | 18.0 |
| `getClientExtensionResults` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 49 | 13 | 10.0 |
| `isConditionalMediationAvailable` | 108 | 108 | No | No | 94 | 16 | No | 108 | No | 73 | No | No |
| `isUserVerifyingPlatformAuthenticatorAvailable` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 49 | 13 | 10.0 |
| `rawId` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 49 | 13 | 10.0 |
| `response` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 49 | 13 | 10.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Web_Authentication_API` | 51 | 18 | 60 | No | 38 | 13 | 51 | 51 | 60 | 41 | 13 | 5.0 |
| `create` | 60 | 18 | 60 | No | 47 | 13 | 60 | 60 | 60 | 44 | 13 | 8.0 |
| `get` | 51 | 18 | 60 | No | 38 | 13 | 51 | 51 | 60 | 41 | 13 | 5.0 |
| `preventSilentAccess` | 6051–60 | 18 | 60 | No | 4738–47 | 13 | 6051–60 | 6051–60 | 60 | 4441–44 | 13 | 8.05.0–8.0 |
| `store` | 51 | 79 | 60 | No | 38 | 13 | 51 | 51 | 60 | 41 | 13 | 5.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Web_Authentication_API` | 51 | 18 | 60 | No | 38 | 13 | 51 | 51 | 60 | 41 | 13 | 5.0 |
| `id` | 51 | 18 | 60 | No | 38 | 13 | 51 | 51 | 60 | 41 | 13 | 5.0 |
| `isConditionalMediationAvailable` | No | No | No | No | No | 16 | No | No | No | No | 16 | No |
| `type` | 51 | 18 | 60 | No | 38 | 13 | 51 | 51 | 60 | 41 | 13 | 5.0 |


### api.Credential


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.CredentialsContainer


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.PublicKeyCredential


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.AuthenticatorResponse


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.AuthenticatorAttestationResponse


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.AuthenticatorAssertionResponse


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API>

Web MIDI API
============



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The Web MIDI API connects to and interacts with Musical Instrument Digital Interface (MIDI) Devices.

  The interfaces deal with the practical aspects of sending and receiving MIDI messages. Therefore, the API can be used for musical and non-musical uses, with any MIDI device connected to your computer. 



Interfaces
----------


 [`MIDIInputMap`](midiinputmap)  Represents all of the available MIDI input ports.

  [`MIDIOutputMap`](midioutputmap)  Represents all of the available MIDI output ports.

  [`MIDIAccess`](midiaccess)  Provides the methods to list input and output devices, and to access an individual device.

  [`MIDIPort`](midiport)  Represents an individual MIDI port.

  [`MIDIInput`](midiinput)  Provides a method for dealing with MIDI messages from an input port.

  [`MIDIOutput`](midioutput)  Queues messages to the linked MIDI port. Messages can be sent immediately or after a specified delay.

  [`MIDIMessageEvent`](midimessageevent)  The event passed to [`MIDIInput.midimessage_event`](midiinput/midimessage_event).

  [`MIDIConnectionEvent`](midiconnectionevent)  The event passed to the [`MIDIAccess.statechange_event`](midiaccess/statechange_event) and [`MIDIPort.statechange_event`](midiport/statechange_event) events, when a port becomes available or unavailable.

  
Security requirements
---------------------



Access to the API is requested using the [`navigator.requestMIDIAccess()`](navigator/requestmidiaccess) method.

 * The method must be called in a [secure context](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts).
* Access may be gated by the [`midi`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy/midi) HTTP [Permission Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy).
* The user must explicitly grant permission to use the API through a user-agent specific mechanism, or have previously granted permission. Note that if access is denied by a permission policy it cannot be granted by a user permission.

 The permission status can be queried using the [Permissions API](permissions_api) method [`navigator.permissions.query()`](permissions/query), passing a permission descriptor with the `midi` permission and (optional) `sysex` property:

 
```
navigator.permissions.query({ name: "midi", sysex: true }).then((result) => {
  if (result.state === "granted") {
    // Access granted.
  } else if (result.state === "prompt") {
    // Using API will prompt for permission
  }
  // Permission was denied by user prompt or permission policy
});

```


Examples
--------


### Gaining access to the MIDI port



 The [`navigator.requestMIDIAccess()`](navigator/requestmidiaccess) method returns a promise that resolves to a [`MIDIAccess`](midiaccess) object, which can then be used to access a MIDI device. The method must be called in a secure context. 

 
```
let midi = null; // global MIDIAccess object
function onMIDISuccess(midiAccess) {
  console.log("MIDI ready!");
  midi = midiAccess; // store in the global (in real usage, would probably keep in an object instance)
}

function onMIDIFailure(msg) {
  console.error(`Failed to get MIDI access - ${msg}`);
}

navigator.requestMIDIAccess().then(onMIDISuccess, onMIDIFailure);

```


### Listing inputs and outputs



In this example the list of input and output ports are retrieved and printed to the console.

 
```
function listInputsAndOutputs(midiAccess) {
  for (const entry of midiAccess.inputs) {
    const input = entry[1];
    console.log(
      `Input port [type:'${input.type}']` +
        ` id:'${input.id}'` +
        ` manufacturer:'${input.manufacturer}'` +
        ` name:'${input.name}'` +
        ` version:'${input.version}'`
    );
  }

  for (const entry of midiAccess.outputs) {
    const output = entry[1];
    console.log(
      `Output port [type:'${output.type}'] id:'${output.id}' manufacturer:'${output.manufacturer}' name:'${output.name}' version:'${output.version}'`
    );
  }
}

```


### Handling MIDI Input



This example prints incoming MIDI messages on a single port to the console.

 
```
function onMIDIMessage(event) {
  let str = `MIDI message received at timestamp ${event.timeStamp}[${event.data.length} bytes]: `;
  for (const character of event.data) {
    str += `0x${character.toString(16)}`;
  }
  console.log(str);
}

function startLoggingMIDIInput(midiAccess, indexOfPort) {
  midiAccess.inputs.forEach((entry) => {
    entry.onmidimessage = onMIDIMessage;
  });
}

```


Specifications
--------------




| Specification |
| --- |
| [Web MIDI API](https://webaudio.github.io/web-midi-api/)  |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Web_MIDI_API` | 43 | 79 | 110 | No | 30 | No | No | 43 | 110 | 30 | No | 4.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Web_MIDI_API` | 8864 | 8879 | 74 | No | 7451 | No | 8864 | 8864 | No | 6347 | No | 15.09.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Web_MIDI_API` | 43 | 79 | 108API access is gated by installation of a [site permission add-on](https://support.mozilla.org/en-US/kb/site-permission-addons) (user prompt), secure context, and [Permission Policy: `midi`](https://developer.mozilla.org/docs/Web/HTTP/Headers/Feature-Policy/midi).97–108["Version 107 and later, API use is gated by a site permission add-on that is automatically generated by Firefox.", "Version 105 and later, the `dom.webmidi.gated` preference may be set `false` to allow WebMIDI to be used without a site permission addon.", "Version 100 to 104 (inclusive) WebMIDI is not available (API use is gated by a site permission add-on that is no longer available)."] | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `secure_context_required` | 43 | 79 | 108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |


### api.Navigator.requestMIDIAccess


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### http.headers.Permissions-Policy.midi


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.Permissions.permission\_midi


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


See also
--------


* [Introduction to Web MIDI](https://code.tutsplus.com/tutorials/introduction-to-web-midi--cms-25220)
* [Making Music in the Browser](https://www.keithmcmillen.com/blog/making-music-in-the-browser-web-midi-api/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Web_MIDI_API>

Touch events
============



To provide quality support for touch-based user interfaces, touch events offer the ability to interpret finger (or stylus) activity on touch screens or trackpads.

 The touch events interfaces are relatively low-level APIs that can be used to support application-specific multi-touch interactions such as a two-finger gesture. A multi-touch interaction starts when a finger (or stylus) first touches the contact surface. Other fingers may subsequently touch the surface and optionally move across the touch surface. The interaction ends when the fingers are removed from the surface. During this interaction, an application receives touch events during the start, move, and end phases.

 Touch events are similar to mouse events except they support simultaneous touches and at different locations on the touch surface. The [`TouchEvent`](touchevent) interface encapsulates all of the touchpoints that are currently active. The [`Touch`](touch) interface, which represents a single touchpoint, includes information such as the position of the touch point relative to the browser viewport.



Definitions
-----------


 Surface  The touch-sensitive surface. This may be a screen or trackpad.

  Touch point  A point of contact with the surface. This may be a finger (or elbow, ear, nose, whatever, but typically a finger) or stylus.

  
Interfaces
----------


 [`TouchEvent`](touchevent)  Represents an event that occurs when the state of touches on the surface changes.

  [`Touch`](touch)  Represents a single point of contact between the user and the touch surface.

  [`TouchList`](touchlist)  Represents a group of touches; this is used when the user has, for example, multiple fingers on the surface at the same time.

  
Example
-------



This example tracks multiple touchpoints at a time, allowing the user to draw in a [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) with more than one finger at a time. It will only work on a browser that supports touch events.

  **Note:** The text below uses the term "finger" when describing the contact with the surface, but it could, of course, also be a stylus or other contact method.

 

### Create a canvas




```
<canvas id="canvas" width="600" height="600" style="border:solid black 1px;">
  Your browser does not support canvas element.
</canvas>
<br />
Log:
<pre id="log" style="border: 1px solid #ccc;"></pre>

```
 
```
#log {
  height: 200px;
  width: 600px;
  overflow: scroll;
}

```


### Setting up the event handlers



 When the page loads, the `startup()` function shown below will be called. This sets up all the event listeners for our [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element so we can handle the touch events as they occur. 

 
```
function startup() {
  const el = document.getElementById("canvas");
  el.addEventListener("touchstart", handleStart);
  el.addEventListener("touchend", handleEnd);
  el.addEventListener("touchcancel", handleCancel);
  el.addEventListener("touchmove", handleMove);
  log("Initialized.");
}

document.addEventListener("DOMContentLoaded", startup);

```
 #### Tracking new touches

 We'll keep track of the touches in-progress.

 
```
const ongoingTouches = [];

```
 When a [`touchstart`](element/touchstart_event) event occurs, indicating that a new touch on the surface has occurred, the `handleStart()` function below is called.

 
```
function handleStart(evt) {
  evt.preventDefault();
  log("touchstart.");
  const el = document.getElementById("canvas");
  const ctx = el.getContext("2d");
  const touches = evt.changedTouches;

  for (let i = 0; i < touches.length; i++) {
    log(`touchstart: ${i}.`);
    ongoingTouches.push(copyTouch(touches[i]));
    const color = colorForTouch(touches[i]);
    log(`color of touch with id ${touches[i].identifier} = ${color}`);
    ctx.beginPath();
    ctx.arc(touches[i].pageX, touches[i].pageY, 4, 0, 2 \* Math.PI, false); // a circle at the start
    ctx.fillStyle = color;
    ctx.fill();
  }
}

```
 This calls [`event.preventDefault()`](event/preventdefault) to keep the browser from continuing to process the touch event (this also prevents a mouse event from also being delivered). Then we get the context and pull the list of changed touch points out of the event's [`TouchEvent.changedTouches`](touchevent/changedtouches) property.

 After that, we iterate over all the [`Touch`](touch) objects in the list, pushing them onto an array of active touchpoints and drawing the start point for the draw as a small circle; we're using a 4-pixel wide line, so a 4-pixel radius circle will show up neatly.

 #### Drawing as the touches move

 Each time one or more fingers move, a [`touchmove`](element/touchmove_event) event is delivered, resulting in our `handleMove()` function being called. Its responsibility in this example is to update the cached touch information and to draw a line from the previous position to the current position of each touch.

 
```
function handleMove(evt) {
  evt.preventDefault();
  const el = document.getElementById("canvas");
  const ctx = el.getContext("2d");
  const touches = evt.changedTouches;

  for (let i = 0; i < touches.length; i++) {
    const color = colorForTouch(touches[i]);
    const idx = ongoingTouchIndexById(touches[i].identifier);

    if (idx >= 0) {
      log(`continuing touch ${idx}`);
      ctx.beginPath();
      log(
        `ctx.moveTo( ${ongoingTouches[idx].pageX}, ${ongoingTouches[idx].pageY} );`
      );
      ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY);
      log(`ctx.lineTo( ${touches[i].pageX}, ${touches[i].pageY} );`);
      ctx.lineTo(touches[i].pageX, touches[i].pageY);
      ctx.lineWidth = 4;
      ctx.strokeStyle = color;
      ctx.stroke();

      ongoingTouches.splice(idx, 1, copyTouch(touches[i])); // swap in the new touch record
    } else {
      log("can't figure out which touch to continue");
    }
  }
}

```
 This iterates over the changed touches as well, but it looks in our cached touch information array for the previous information about each touch to determine the starting point for each touch's new line segment to be drawn. This is done by looking at each touch's [`Touch.identifier`](touch/identifier) property. This property is a unique integer for each touch and remains consistent for each event during the duration of each finger's contact with the surface.

 This lets us get the coordinates of the previous position of each touch and use the appropriate context methods to draw a line segment joining the two positions together.

 After drawing the line, we call [`Array.splice()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) to replace the previous information about the touchpoint with the current information in the `ongoingTouches` array.

 #### Handling the end of a touch

 When the user lifts a finger off the surface, a [`touchend`](element/touchend_event) event is sent. We handle this by calling the `handleEnd()` function below. Its job is to draw the last line segment for each touch that ended and remove the touchpoint from the ongoing touch list.

 
```
function handleEnd(evt) {
  evt.preventDefault();
  log("touchend");
  const el = document.getElementById("canvas");
  const ctx = el.getContext("2d");
  const touches = evt.changedTouches;

  for (let i = 0; i < touches.length; i++) {
    const color = colorForTouch(touches[i]);
    let idx = ongoingTouchIndexById(touches[i].identifier);

    if (idx >= 0) {
      ctx.lineWidth = 4;
      ctx.fillStyle = color;
      ctx.beginPath();
      ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY);
      ctx.lineTo(touches[i].pageX, touches[i].pageY);
      ctx.fillRect(touches[i].pageX - 4, touches[i].pageY - 4, 8, 8); // and a square at the end
      ongoingTouches.splice(idx, 1); // remove it; we're done
    } else {
      log("can't figure out which touch to end");
    }
  }
}

```
 This is very similar to the previous function; the only real differences are that we draw a small square to mark the end and that when we call [`Array.splice()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice), we remove the old entry from the ongoing touch list, without adding in the updated information. The result is that we stop tracking that touchpoint.

 #### Handling canceled touches

 If the user's finger wanders into browser UI, or the touch otherwise needs to be canceled, the [`touchcancel`](element/touchcancel_event) event is sent, and we call the `handleCancel()` function below.

 
```
function handleCancel(evt) {
  evt.preventDefault();
  log("touchcancel.");
  const touches = evt.changedTouches;

  for (let i = 0; i < touches.length; i++) {
    let idx = ongoingTouchIndexById(touches[i].identifier);
    ongoingTouches.splice(idx, 1); // remove it; we're done
  }
}

```
 Since the idea is to immediately abort the touch, we remove it from the ongoing touch list without drawing a final line segment.



### Convenience functions



This example uses two convenience functions that should be looked at briefly to help make the rest of the code more clear.

 #### Selecting a color for each touch

  To make each touch's drawing look different, the `colorForTouch()` function is used to pick a color based on the touch's unique identifier. This identifier is an opaque number, but we can at least rely on it differing between the currently-active touches. 

 
```
function colorForTouch(touch) {
  let r = touch.identifier % 16;
  let g = Math.floor(touch.identifier / 3) % 16;
  let b = Math.floor(touch.identifier / 7) % 16;
  r = r.toString(16); // make it a hex digit
  g = g.toString(16); // make it a hex digit
  b = b.toString(16); // make it a hex digit
  const color = `#${r}${g}${b}`;
  return color;
}

```
  The result from this function is a string that can be used when calling [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) functions to set drawing colors. For example, for a [`Touch.identifier`](touch/identifier) value of 10, the resulting string is "#a31". 

 #### Copying a touch object

 Some browsers (mobile Safari, for one) re-use touch objects between events, so it's best to copy the properties you care about, rather than referencing the entire object.

 
```
function copyTouch({ identifier, pageX, pageY }) {
  return { identifier, pageX, pageY };
}

```
 #### Finding an ongoing touch

 The `ongoingTouchIndexById()` function below scans through the `ongoingTouches` array to find the touch matching the given identifier then returns that touch's index into the array.

 
```
function ongoingTouchIndexById(idToFind) {
  for (let i = 0; i < ongoingTouches.length; i++) {
    const id = ongoingTouches[i].identifier;

    if (id === idToFind) {
      return i;
    }
  }
  return -1; // not found
}

```
 #### Showing what's going on

 
```
function log(msg) {
  const container = document.getElementById("log");
  container.textContent = `${msg} \n${container.textContent}`;
}

```


### Result



You can test this example on mobile devices by touching the box below.


   **Note:** More generally, the example will work on platforms that provide touch events. You can test this on desktop platforms that can simulate such events: 

 * On Firefox enable "touch simulation" in [Responsive Design Mode](https://firefox-source-docs.mozilla.org/devtools-user/responsive_design_mode/index.html#toggling-responsive-design-mode) (you may need to reload the page).
* On Chrome use [Device mode](https://developer.chrome.com/docs/devtools/device-mode/) and set the [Device type](https://developer.chrome.com/docs/devtools/device-mode/#type) to one that sends touch events.

 

Additional tips
---------------


This section provides additional tips on how to handle touch events in your web application.


### Handling clicks



Since calling `preventDefault()` on a [`touchstart`](element/touchstart_event) or the first [`touchmove`](element/touchmove_event) event of a series prevents the corresponding mouse events from firing, it's common to call `preventDefault()` on `touchmove` rather than `touchstart`. That way, mouse events can still fire and things like links will continue to work. Alternatively, some frameworks have taken to re-firing touch events as mouse events for this same purpose. (This example is oversimplified and may result in strange behavior. It is only intended as a guide.)

 
```
function onTouch(evt) {
  evt.preventDefault();
  if (
    evt.touches.length > 1 ||
    (evt.type === "touchend" && evt.touches.length > 0)
  )
    return;

  const newEvt = document.createEvent("MouseEvents");
  let type = null;
  let touch = null;

  switch (evt.type) {
    case "touchstart":
      type = "mousedown";
      touch = evt.changedTouches[0];
      break;
    case "touchmove":
      type = "mousemove";
      touch = evt.changedTouches[0];
      break;
    case "touchend":
      type = "mouseup";
      touch = evt.changedTouches[0];
      break;
  }

  newEvt.initMouseEvent(
    type,
    true,
    true,
    evt.originalTarget.ownerDocument.defaultView,
    0,
    touch.screenX,
    touch.screenY,
    touch.clientX,
    touch.clientY,
    evt.ctrlKey,
    evt.altKey,
    evt.shiftKey,
    evt.metaKey,
    0,
    null
  );
  evt.originalTarget.dispatchEvent(newEvt);
}

```


### Calling preventDefault() only on a second touch


One technique for preventing things like `pinchZoom` on a page is to call `preventDefault()` on the second touch in a series. This behavior is not well defined in the touch events spec and results in different behavior for different browsers (i.e., iOS will prevent zooming but still allow panning with both fingers; Android will allow zooming but not panning; Opera and Firefox currently prevent all panning and zooming.) Currently, it's not recommended to depend on any particular behavior in this case, but rather to depend on meta viewport to prevent zooming.


Specifications
--------------




| Specification |
| --- |
| [Touch Events # touch-interface](https://w3c.github.io/touch-events/#touch-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Touch` | 48 | 79 | 46 | No | 35 | No | 48 | 48 | 6 | 35 | ≤3 | 5.0 |
| `Touch_events` | 22 | ≤18 | 5218–24Removed in [bug 888304](https://bugzil.la/888304) due to web compatibility issues. | No | 15 | No | 4.4 | 25 | 6 | 14 | ≤3 | 1.5 |
| `altitudeAngle` | No | No | No | No | No | No | No | No | No | No | 10 | No |
| `azimuthAngle` | No | No | No | No | No | No | No | No | No | No | 10 | No |
| `clientX` | 22 | ≤18 | 5218–24Removed in [bug 888304](https://bugzil.la/888304) due to web compatibility issues. | No | 15 | No | 4.4 | 25 | 6 | 14 | 10 | 1.5 |
| `clientY` | 22 | ≤18 | 5218–24Removed in [bug 888304](https://bugzil.la/888304) due to web compatibility issues. | No | 15 | No | 4.4 | 25 | 6 | 14 | 10 | 1.5 |
| `force` | 3822–47 | ≤79 | 5218–24Removed in [bug 888304](https://bugzil.la/888304) due to web compatibility issues. | No | 2515–34 | No | 384.4–47 | 3825–47 | 6 | 2514–34 | 10 | 3.01.5–5.0 |
| `identifier` | 22 | ≤18 | 5218–24Removed in [bug 888304](https://bugzil.la/888304) due to web compatibility issues. | No | 15 | No | 4.4 | 25 | 6 | 14 | 10 | 1.5 |
| `pageX` | 22 | ≤18 | 5218–24Removed in [bug 888304](https://bugzil.la/888304) due to web compatibility issues. | No | 15 | No | 4.4 | 25 | 6 | 14 | 10 | 1.5 |
| `pageY` | 22 | ≤18 | 5218–24Removed in [bug 888304](https://bugzil.la/888304) due to web compatibility issues. | No | 15 | No | 4.4 | 25 | 6 | 14 | 10 | 1.5 |
| `radiusX` | 3822–47 | ≤79 | 5218–24Removed in [bug 888304](https://bugzil.la/888304) due to web compatibility issues. | No | 2515–34 | No | 384.4–47 | 3825–47 | 6 | 2514–34 | 10 | 3.01.5–5.0 |
| `radiusY` | 3822–47 | ≤79 | 5218–24Removed in [bug 888304](https://bugzil.la/888304) due to web compatibility issues. | No | 2515–34 | No | 384.4–47 | 3825–47 | 6 | 2514–34 | 10 | 3.01.5–5.0 |
| `rotationAngle` | 4322–47 | ≤79 | 5218–24Removed in [bug 888304](https://bugzil.la/888304) due to web compatibility issues. | No | 3015–34 | No | 434.4–47 | 4325–47 | 6 | 3014–34 | 10 | 4.01.5–5.0 |
| `screenX` | 22 | ≤18 | 5218–24Removed in [bug 888304](https://bugzil.la/888304) due to web compatibility issues. | No | 15 | No | 4.4 | 25 | 6 | 14 | 10 | 1.5 |
| `screenY` | 22 | ≤18 | 5218–24Removed in [bug 888304](https://bugzil.la/888304) due to web compatibility issues. | No | 15 | No | 4.4 | 25 | 6 | 14 | 10 | 1.5 |
| `target` | 22 | ≤18 | 5218–24Removed in [bug 888304](https://bugzil.la/888304) due to web compatibility issues. | No | 15 | No | 4.4 | 25 | 6 | 14 | 10 | 1.5 |
| `touchType` | No | No | No | No | No | No | No | No | No | No | 10 | No |



Touch events are typically available on devices with a touch screen, but many browsers make the touch events API unavailable on all desktop devices, even those with touch screens.

 The reason for this is that some websites use the availability of parts of the touch events API as an indicator that the browser is running on a mobile device. If the touch events API is available, these websites will assume a mobile device and serve mobile-optimized content. This may then provide a poor experience for users of desktop devices that have touch screens.

 To support both touch and mouse across all types of devices, use [pointer events](pointer_events) instead.




 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Touch_events>

Web Components
==============


Web Components is a suite of different technologies allowing you to create reusable custom elements — with their functionality encapsulated away from the rest of your code — and utilize them in your web apps.


Concepts and usage
------------------



As developers, we all know that reusing code as much as possible is a good idea. This has traditionally not been so easy for custom markup structures — think of the complex HTML (and associated style and script) you've sometimes had to write to render custom UI controls, and how using them multiple times can turn your page into a mess if you are not careful.

 Web Components aims to solve such problems — it consists of three main technologies, which can be used together to create versatile custom elements with encapsulated functionality that can be reused wherever you like without fear of code collisions.

 * **Custom elements**: A set of JavaScript APIs that allow you to define custom elements and their behavior, which can then be used as desired in your user interface.
* **Shadow DOM**: A set of JavaScript APIs for attaching an encapsulated "shadow" DOM tree to an element — which is rendered separately from the main document DOM — and controlling associated functionality. In this way, you can keep an element's features private, so they can be scripted and styled without the fear of collision with other parts of the document.
* **HTML templates**: The [`<template>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template) and [`<slot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot) elements enable you to write markup templates that are not displayed in the rendered page. These can then be reused multiple times as the basis of a custom element's structure.

 The basic approach for implementing a web component generally looks something like this:

 1. Create a class in which you specify your web component functionality, using the [class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) syntax.
2. Register your new custom element using the [`CustomElementRegistry.define()`](customelementregistry/define) method, passing it the element name to be defined, the class or function in which its functionality is specified, and optionally, what element it inherits from.
3. If required, attach a shadow DOM to the custom element using [`Element.attachShadow()`](element/attachshadow) method. Add child elements, event listeners, etc., to the shadow DOM using regular DOM methods.
4. If required, define an HTML template using [`<template>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template) and [`<slot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot). Again use regular DOM methods to clone the template and attach it to your shadow DOM.
5. Use your custom element wherever you like on your page, just like you would any regular HTML element.



Guides
------


 [Using custom elements](web_components/using_custom_elements)  A guide showing how to use the features of custom elements to create simple web components, as well as looking into lifecycle callbacks and some other more advanced features.

  [Using shadow DOM](web_components/using_shadow_dom)  A guide that looks at shadow DOM fundamentals, showing how to attach a shadow DOM to an element, add to the shadow DOM tree, style it, and more.

  [Using templates and slots](web_components/using_templates_and_slots)  A guide showing how to define a reusable HTML structure using [`<template>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template) and [`<slot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot) elements, and then use that structure inside your web components.

  
Reference
---------


### Custom elements


 [`CustomElementRegistry`](customelementregistry)  Contains functionality related to custom elements, most notably the [`CustomElementRegistry.define()`](customelementregistry/define) method used to register new custom elements so they can then be used in your document.

  [`Window.customElements`](window/customelements)  Returns a reference to the `CustomElementRegistry` object.

  [Life cycle callbacks](web_components/using_custom_elements#using_the_lifecycle_callbacks)  Special callback functions defined inside the custom element's class definition, which affect its behavior:

 * `connectedCallback`: Invoked when the custom element is first connected to the document's DOM.
* `disconnectedCallback`: Invoked when the custom element is disconnected from the document's DOM.
* `adoptedCallback`: Invoked when the custom element is moved to a new document.
* `attributeChangedCallback`: Invoked when one of the custom element's attributes is added, removed, or changed.

  Extensions for creating custom built-in elements  The following extensions are defined:

 * The [`is`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/is) global HTML attribute: Allows you to specify that a standard HTML element should behave like a registered custom built-in element.
* The "is" option of the [`Document.createElement()`](document/createelement) method: Allows you to create an instance of a standard HTML element that behaves like a given registered custom built-in element.

  CSS pseudo-classes  Pseudo-classes relating specifically to custom elements:

 * [`:defined`](https://developer.mozilla.org/en-US/docs/Web/CSS/:defined): Matches any element that is defined, including built in elements and custom elements defined with `CustomElementRegistry.define()`.
* [`:host`](https://developer.mozilla.org/en-US/docs/Web/CSS/:host): Selects the shadow host of the [shadow DOM](web_components/using_shadow_dom) containing the CSS it is used inside.
* [`:host()`](https://developer.mozilla.org/en-US/docs/Web/CSS/:host): Selects the shadow host of the [shadow DOM](web_components/using_shadow_dom) containing the CSS it is used inside (so you can select a custom element from inside its shadow DOM) — but only if the selector given as the function's parameter matches the shadow host.
* [`:host-context()`](https://developer.mozilla.org/en-US/docs/Web/CSS/:host-context): Selects the shadow host of the [shadow DOM](web_components/using_shadow_dom) containing the CSS it is used inside (so you can select a custom element from inside its shadow DOM) — but only if the selector given as the function's parameter matches the shadow host's ancestor(s) in the place it sits inside the DOM hierarchy.

  CSS pseudo-elements  Pseudo-elements relating specifically to custom elements:

 * [`::part`](https://developer.mozilla.org/en-US/docs/Web/CSS/::part): Represents any element within a [shadow tree](web_components/using_shadow_dom) that has a matching [`part`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#part) attribute.

  
### Shadow DOM


 [`ShadowRoot`](shadowroot)  Represents the root node of a shadow DOM subtree.

  
[`Element`](element) extensions  Extensions to the `Element` interface related to shadow DOM:

 * The [`Element.attachShadow()`](element/attachshadow) method attaches a shadow DOM tree to the specified element.
* The [`Element.shadowRoot`](element/shadowroot) property returns the shadow root attached to the specified element, or `null` if there is no shadow root attached.

  Relevant [`Node`](node) additions  Additions to the `Node` interface relevant to shadow DOM:

 * The [`Node.getRootNode()`](node/getrootnode) method returns the context object's root, which optionally includes the shadow root if it is available.
* The [`Node.isConnected`](node/isconnected) property returns a boolean indicating whether or not the Node is connected (directly or indirectly) to the context object, e.g. the [`Document`](document) object in the case of the normal DOM, or the [`ShadowRoot`](shadowroot) in the case of a shadow DOM.

  
[`Event`](event) extensions  Extensions to the `Event` interface related to shadow DOM:

 * [`Event.composed`](event/composed): Returns `true` if the event will propagate across the shadow DOM boundary into the standard DOM, otherwise `false`.
* [`Event.composedPath`](event/composedpath): Returns the event's path (objects on which listeners will be invoked). This does not include nodes in shadow trees if the shadow root was created with [`ShadowRoot.mode`](shadowroot/mode) closed.

  
### HTML templates


 [`<template>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template)  Contains an HTML fragment that is not rendered when a containing document is initially loaded, but can be displayed at runtime using JavaScript, mainly used as the basis of custom element structures. The associated DOM interface is [`HTMLTemplateElement`](htmltemplateelement).

  [`<slot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot)  A placeholder inside a web component that you can fill with your own markup, which lets you create separate DOM trees and present them together. The associated DOM interface is [`HTMLSlotElement`](htmlslotelement).

  The [`slot`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/slot) global HTML attribute  Assigns a slot in a shadow DOM shadow tree to an element.

  [`Element.assignedSlot`](element/assignedslot)  A read-only attribute which returns a reference to the [`<slot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot) in which this element is inserted.

  [`Text.assignedSlot`](text/assignedslot)  A read-only attribute which returns a reference to the [`<slot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot) in which this text node is inserted.

  
[`Element`](element) extensions  Extensions to the `Element` interface related to slots:

 * [`Element.slot`](element/slot): Returns the name of the shadow DOM slot attached to the element.

  CSS pseudo-elements  Pseudo-elements relating specifically to slots:

 * [`::slotted`](https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted): Matches any content that is inserted into a slot.

  The [`slotchange`](htmlslotelement/slotchange_event) event  Fired on an [`HTMLSlotElement`](htmlslotelement) instance ([`<slot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot) element) when the node(s) contained in that slot change.

  
Examples
--------


We are building up a number of examples in our [web-components-examples](https://github.com/mdn/web-components-examples) GitHub repo. More will be added as time goes on.


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-template-element](https://html.spec.whatwg.org/multipage/scripting.html#the-template-element) |
| [DOM Standard # interface-shadowroot](https://dom.spec.whatwg.org/#interface-shadowroot) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Web_components` | 53 | 79 | 63 | No | 40 | 10 | 53 | 53 | 63 | 41 | 10 | 6.0 |
| `activeElement` | 53 | 79 | 63 | No | 40 | 10 | 53 | 53 | 63 | 41 | 10 | 6.0 |
| `adoptedStyleSheets` | 73 | 79 | 101 | No | 60 | 16.4 | 73 | 73 | 101 | 50 | 16.4 | 11.0 |
| `delegatesFocus` | 53 | 79 | 94 | No | 40 | 15 | 53 | 53 | 94 | 41 | 15 | 6.0 |
| `elementFromPoint` | 53Before Chrome 66, this method returned `null` when the element was a child of a host node. See [issue 759947](https://crbug.com/759947). | 79 | 63 | No | 40Before Opera 53, this method returned `null` when the element was a child of a host node. See [issue 759947](https://crbug.com/759947). | 10.1 | 53Before Chrome 66, this method returned `null` when the element was a child of a host node. See [issue 759947](https://crbug.com/759947). | 53Before Chrome 66, this method returned `null` when the element was a child of a host node. See [issue 759947](https://crbug.com/759947). | 63 | 41Before Opera Android 47, this method returned `null` when the element was a child of a host node. See [issue 759947](https://crbug.com/759947). | 10.3 | 6.0Before Samsung Internet 9.0, this method returned `null` when the element was a child of a host node. See [issue 759947](https://crbug.com/759947). |
| `elementsFromPoint` | 53Before Chrome 66, this method returned `null` when the element was a child of a host node. See [issue 759947](https://crbug.com/759947). | 79 | 63 | No | 40 | 11.1 | 53Before Chrome 66, this method returned `null` when the element was a child of a host node. See [issue 759947](https://crbug.com/759947). | 53Before Chrome 66, this method returned `null` when the element was a child of a host node. See [issue 759947](https://crbug.com/759947). | 63 | 41 | 11.3 | 6.0Before Samsung Internet 9.0, this method returned `null` when the element was a child of a host node. See [issue 759947](https://crbug.com/759947). |
| `fullscreenElement` | 71 | 79 | 6463 | No | 58 | 16.4 | 71 | 71 | 6463 | 50 | 16.4 | 10.0 |
| `getAnimations` | 84 | 84 | 75 | No | 70 | 14 | 84 | 84 | 79 | 60 | 14 | 14.0 |
| `getSelection` | 53 | 79 | No | No | 40 | No | 53 | 53 | No | 41 | No | 6.0 |
| `host` | 53 | 79 | 63 | No | 40 | 10 | 53 | 53 | 63 | 41 | 10 | 6.0 |
| `innerHTML` | 53 | 79 | 63 | No | 40 | 10 | 53 | 53 | 63 | 41 | 10 | 6.0 |
| `mode` | 53 | 79 | 63 | No | 40 | 10.1 | 53 | 53 | 63 | 41 | 10.3 | 6.0 |
| `pictureInPictureElement` | 69 | 79 | No | No | 56 | 13.1 | 105 | 105 | No | 72 | 13.4 | 20.0 |
| `pointerLockElement` | 53 | 79 | 63 | No | 40 | 10.1 | 53 | 53 | 63 | 41 | No | 6.0 |
| `slotAssignment` | 86 | 86 | 92 | No | 72 | 16.4 | 86 | 86 | 92 | 61 | 16.4 | 14.0 |
| `styleSheets` | 53 | 79 | 63 | No | 40 | 12.1 | 53 | 53 | 63 | 41 | 12.2 | 6.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Web_components` | 26 | 13 | 22 | No | 15 | 8 | Yes | 26 | 22 | No | 8 | 1.5 |
| `shadowrootmode` | 11190–111 | 11190–111 | No | No | No | 16.4 | 11190–111 | 11190–111 | No | No | 16.4 | 15.0 |


### html.elements.template


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.ShadowRoot


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


See also
--------


* [Open Web Components](https://open-wc.org/) — Guides, tools and libraries for developing web components.
* [DataFormsJS](https://www.dataformsjs.com/) — Open source web components library — Set of Web Components that can be used to build Single Page Apps (SPA), Display JSON data from API's and Web Services, and bind data to different elements on screen. All Web Components are plain JavaScript and require no build process.
* [FAST](https://www.fast.design/) is a web component library built by Microsoft which offers several packages to leverage depending on your project needs. [Fast Element](https://github.com/microsoft/fast/tree/master/packages/web-components/fast-element) is a lightweight means to easily build performant, memory-efficient, standards-compliant Web Components. [Fast Foundation](https://github.com/microsoft/fast/tree/master/packages/web-components/fast-foundation) is a library of Web Component classes, templates, and other utilities built on fast-element intended to be composed into registered Web Components.
* [Hybrids](https://github.com/hybridsjs/hybrids) — Open source web components library, which favors plain objects and pure functions over `class` and `this` syntax. It provides a simple and functional API for creating custom elements.
* [Lit](https://lit.dev/) — Google's web components library, the core of which is a component base class designed to reduce boilerplate while providing reactive state, scoped styles, and a declarative template system.
* [Snuggsi](https://github.com/devpunks/snuggsi#readme) — Easy Web Components in ~1kB *Including polyfill* — All you need is a browser and basic understanding of HTML, CSS, and JavaScript classes to be productive.
* [Slim.js](https://github.com/slimjs/slim.js) — Open source web components library — a high-performant library for rapid and easy component authoring; extensible and pluggable and cross-framework compatible.
* [Stencil](https://stenciljs.com/) — Toolchain for building reusable, scalable design systems in web components.
* [omi](https://tencent.github.io/omi/) - Front End Cross-Frameworks Framework


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Web_components>

Web Crypto API
==============



The **Web Crypto API** is an interface allowing a script to use cryptographic primitives in order to build systems using cryptography.


 **Note:** This feature is available in [Web Workers](web_workers_api)

  **Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

  **Warning:** The Web Crypto API provides a number of low-level cryptographic primitives. It's very easy to misuse them, and the pitfalls involved can be very subtle.

 Even assuming you use the basic cryptographic functions correctly, secure key management and overall security system design are extremely hard to get right, and are generally the domain of specialist security experts.

 Errors in security system design and implementation can make the security of the system completely ineffective.

 Please learn and experiment, but don't guarantee or imply the security of your work before an individual knowledgeable in this subject matter thoroughly reviews it. The [Crypto 101 Course](https://www.crypto101.io/) can be a great place to start learning about the design and implementation of secure systems.

 

Interfaces
----------


Some browsers implemented an interface called [`Crypto`](crypto) without having it well defined or being cryptographically sound. In order to avoid confusion, methods and properties of this interface have been removed from browsers implementing the Web Crypto API, and all Web Crypto API methods are available on a new interface: [`SubtleCrypto`](subtlecrypto). The [`Crypto.subtle`](crypto/subtle) property gives access to an object implementing it.


Specifications
--------------




| Specification |
| --- |
| [Web Cryptography API # crypto-interface](https://w3c.github.io/webcrypto/#crypto-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Web_Crypto_API` | 11 | 12 | 21 | 11 | 15 | 5 | ≤37 | 18 | 21 | 14 | 5 | 1.0 |
| `getRandomValues` | 11 | 12 | 21 | 11 | 15 | 5 | ≤37 | 18 | 21 | 14 | 5 | 1.0 |
| `randomUUID` | 92 | 92 | 95 | No | 78 | 15.4 | 92 | 92 | 95 | 65 | 15.4 | 16.0 |
| `subtle` | 37 | 12 | 34 | 11 | 24 | 117–11.1 | 37 | 37 | 34 | 24 | 117–11.3 | 3.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API>

Web Locks API
=============



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The Web Locks API allows scripts running in one tab or worker to asynchronously acquire a lock, hold it while work is performed, then release it. While held, no other script executing in the same origin can acquire the same lock, which allows a web app running in multiple tabs or workers to coordinate work and the use of resources.



Web Locks Concepts and Usage
----------------------------



A lock is an abstract concept representing some potentially shared resource, identified by a name chosen by the web app. For example, if a web app running in multiple tabs wants to ensure that only one tab is syncing data between the network and Indexed DB, each tab could try to acquire a "my\_net\_db\_sync" lock, but only one tab will succeed (the [leader election pattern](https://en.wikipedia.org/wiki/Leader_election).)

 The API is used as follows:

 1. The lock is requested.
2. Work is done while holding the lock in an asynchronous task.
3. The lock is automatically released when the task completes.

 
```
navigator.locks.request("my\_resource", async (lock) => {
  // The lock has been acquired.
  await do\_something();
  await do\_something\_else();
  // Now the lock will be released.
});

```
 While a lock is held, requests for the same lock from this execution context, or from other tabs/workers, will be queued. The first queued request will be granted only when the lock is released.

 The API provides optional functionality that may be used as needed, including:

 * returning values from the asynchronous task
* shared and exclusive lock modes
* conditional acquisition
* diagnostics to query the state of locks in an origin
* an escape hatch to protect against deadlocks

 Locks are scoped to origins; the locks acquired by a tab from `https://example.com` have no effect on the locks acquired by a tab from `https://example.org:8080` as they are separate origins.

 The main entry point is `navigator.locks.request()` which requests a lock. It takes a lock name, an optional set of options, and a callback. The callback is invoked when the lock is granted. The lock is automatically released when the callback returns, so usually the callback is an *async function*, which causes the lock to be released only when the async function has completely finished.

  The `request()` method itself returns a promise which resolves once the lock has been released; within an async function, a script can `await` the call to make the asynchronous code flow linearly. For example: 

 
```
await do\_something\_without\_lock();

// Request the lock.
await navigator.locks.request("my\_resource", async (lock) => {
  // The lock has been acquired.
  await do\_something\_with\_lock();
  await do\_something\_else\_with\_lock();
  // Now the lock will be released.
});
// The lock has been released.

await do\_something\_else\_without\_lock();

```


### Options



Several options can be passed when requesting a lock:

 * `mode`: The default mode is "exclusive", but "shared" can be specified. There can be only one "exclusive" holder of a lock, but multiple "shared" requests can be granted at the same time. This can be used to implement the [readers-writer pattern](https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock).
* `signal`: An **AbortSignal** can be passed in, allowing a lock request to be aborted. This can be used to implement a timeout on requests.
* `ifAvailable`: If specified, the lock request will fail if the lock cannot be granted immediately without waiting. The callback is invoked with `null`.



### Monitoring


The `navigator.locks.query()` method can be used by scripts to introspect the state of the lock manager for the origin. This can be useful when debugging, for example, identifying why a lock could not be acquired. The results are a snapshot of the lock manager state, which identifies held and requested locks and some additional data (e.g. mode) about each, at the time the snapshot was taken.


### Advanced use



For more complicated cases, such as holding the lock for an arbitrary amount of time, the callback can return a promise explicitly resolved by the script:

 
```
// Capture promise control functions:
let resolve, reject;
const p = new Promise((res, rej) => {
  resolve = res;
  reject = rej;
});

// Request the lock:
navigator.locks.request(
  "my\_resource",
  // Lock is acquired.
  (lock) => p // Now lock will be held until either resolve() or reject() is called.
);

```


### Deadlocks


A deadlock occurs when a process can no longer make progress because each part is waiting on a request that cannot be satisfied. This can occur with this API in complex use-cases, for example, if multiple locks are requested out-of-order. If tab 1 holds lock A and tab 2 holds lock B, then tab 1 attempts to also acquire lock B and tab 2 attempts to also acquire lock A, neither request can be granted. Web applications can avoid this through several strategies, such as ensuring lock requests are not nested, or are always well ordered, or have timeouts. Note that such deadlocks only affect the locks themselves and code depending on them; the browser, other tabs, and other script in the page is not affected.


Interfaces
----------


 [`Lock`](lock)  Provides the name and mode of a previously requested lock, which is received in the callback to [`LockManager.request()`](lockmanager/request).

  [`LockManager`](lockmanager)  Provides methods for requesting a new [`Lock`](lock) object and querying for an existing Lock object. To get an instance of LockManager, call [`navigator.locks`](navigator/locks).

  
Specifications
--------------




| Specification |
| --- |
| [Web Locks API # api-lock-manager](https://w3c.github.io/web-locks/#api-lock-manager) |
| [Web Locks API # api-lock](https://w3c.github.io/web-locks/#api-lock) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Web_Locks_API` | 69 | 79 | 96 | No | 56 | 15.4 | 69 | 69 | 96 | 48 | 15.4 | 10.0 |
| `mode` | 69 | 79 | 96 | No | 56 | 15.4 | 69 | 69 | 96 | 48 | 15.4 | 10.0 |
| `name` | 69 | 79 | 96 | No | 56 | 15.4 | 69 | 69 | 96 | 48 | 15.4 | 10.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Web_Locks_API` | 69 | 79 | 96 | No | 56 | 15.4 | 69 | 69 | 96 | 48 | 15.4 | 10.0 |
| `query` | 69 | 79 | 96 | No | 56 | 15.4 | 69 | 69 | 96 | 48 | 15.4 | 10.0 |
| `request` | 69 | 79 | 96 | No | 56 | 15.4 | 69 | 69 | 96 | 48 | 15.4 | 10.0 |


### api.LockManager


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.Lock


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Web_Locks_API>

Web NFC API
===========



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The Web NFC API allows exchanging data over NFC via light-weight NFC Data Exchange Format (NDEF) messages.

  **Note:** Devices and tags have to be formatted and recorded specifically to support NDEF record format to be used with Web NFC. Low-level operations are currently not supported by the API, however there is a public discussion about API that would add such functionality.

 

Interfaces
----------


 [`NDEFMessage`](ndefmessage)  Interface that represents NDEF messages that can be received from or sent to a compatible tag via a `NDEFReader` object. A message is composed of metadata and NDEF Records.

  
[`NDEFReader`](ndefreader)  Experimental 
  Interface that enables reading and writing messages from compatible NFC tags. The messages are represented as `NDEFMessage` objects.

  [`NDEFRecord`](ndefrecord)  Interface that represents NDEF records that can be included in an NDEF message.

  
Specifications
--------------




| Specification |
| --- |
| [Web NFC API # the-ndefreader-object](https://w3c.github.io/web-nfc/#the-ndefreader-object) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `NDEFReader` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `Web_NFC_API` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `makeReadOnly` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `reading_event` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `readingerror_event` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `scan` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `secure_context_required` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `write` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Web_NFC_API>

URL Pattern API
===============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

  The URL Pattern API defines a syntax that is used to create URL pattern matchers. These patterns can be matched against URLs or individual URL components. The URL Pattern API is used by the [`URLPattern`](urlpattern) interface. 



Concepts and usage
------------------



 The pattern syntax is based on the syntax from the [path-to-regexp](https://github.com/pillarjs/path-to-regexp) library. Patterns can contain: 

 * Literal strings which will be matched exactly.
* Wildcards (`/posts/*`) that match any character.
* Named groups (`/books/:id`) which extract a part of the matched URL.
* Non-capturing groups (`/books{/old}?`) which make parts of a pattern optional or be matched multiple times.
* [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) groups (`/books/(\\d+)`) which make arbitrarily complex regex matches with a few [limitations](#regex_matchers_limitations).

  You can find details about the syntax in the [pattern syntax](#pattern_syntax) section below. 



URL Pattern API interfaces
--------------------------



The URL Pattern API only has a single related interface:

 * [`URLPattern`](urlpattern)  Experimental



Pattern syntax
--------------


 The syntax for patterns is based on the [path-to-regexp](https://github.com/pillarjs/path-to-regexp) JavaScript library. This syntax is similar to the one used in [Ruby on Rails](https://rubyonrails.org), or JavaScript frameworks like [Express](https://expressjs.com/) or [Next.js](https://nextjs.org/). 


### Fixed text and capture groups



 Each pattern can contain a combination of fixed text and groups. The fixed text is a sequence of characters that is matched exactly. Groups match an arbitrary string based on matching rules. Each URL part has its own default rules that are explained below, but they can be overwritten. 

 
```
// A pattern matching some fixed text
const pattern = new URLPattern({ pathname: "/books" });
console.log(pattern.test("https://example.com/books")); // true
console.log(pattern.exec("https://example.com/books").pathname.groups); // {}

```
 
```
// A pattern matching with a named group
const pattern = new URLPattern({ pathname: "/books/:id" });
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.exec("https://example.com/books/123").pathname.groups); // { id: '123' }

```


### Segment wildcard


 By default, a group matching the `pathname` part of the URL will match all characters but the forward slash (`/`). In the `hostname` part, the group will match all characters except the dot (`.`). In all other parts, the group will match all characters. The segment wildcard is non-greedy, meaning that it will match the shortest possible string. 


### Regex matchers



 Instead of using the default match rules for a group, you can use a regex for each group. This regex defines the matching rules for the group. Below is an example of a regex matcher on a named group that constrains the group to only match if it contains one or more digits: 

 
```
const pattern = new URLPattern("/books/:id(\\d+)", "https://example.com");
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books/abc")); // false
console.log(pattern.test("https://example.com/books/")); // false

```


### Regex matchers limitations



Some regex patterns do not work as you may expect:

 * Starts with `^` will only match if used at the start of the protocol portion of the URLPattern and is redundant if used. 
```
// with `^` in pathname
const pattern = new URLPattern({ pathname: "(^b)" });
console.log(pattern.test("https://example.com/ba")); // false
console.log(pattern.test("https://example.com/xa")); // false

```
 
```
// with `^` in protocol
const pattern = new URLPattern({ protocol: "(^https?)" });
console.log(pattern.test("https://example.com/index.html")); // true
console.log(pattern.test("xhttps://example.com/index.html")); // false

```
 
```
// without `^` in protocol
const pattern = new URLPattern({ protocol: "(https?)" });
console.log(pattern.test("https://example.com/index.html")); // true
console.log(pattern.test("xhttps://example.com/index.html")); // false

```
* Ends with `$` will only match if used at the end of the hash portion of the URLPattern and is redundant if used. 
```
// with `$` in pathname
const pattern = new URLPattern({ pathname: "(path$)" });
console.log(pattern.test("https://example.com/path")); // false
console.log(pattern.test("https://example.com/other")); // false

```
 
```
// with `$` in hash
const pattern = new URLPattern({ hash: "(hash$)" });
console.log(pattern.test("https://example.com/#hash")); // true
console.log(pattern.test("xhttps://example.com/#otherhash")); // false

```
 
```
// without `$` in hash
const pattern = new URLPattern({ hash: "(hash)" });
console.log(pattern.test("https://example.com/#hash")); // true
console.log(pattern.test("xhttps://example.com/#otherhash")); // false

```
* Lookaheads, and lookbehinds will never match any portion of the URLPattern. 
```
// lookahead
const pattern = new URLPattern({ pathname: "(a(?=b))" });
console.log(pattern.test("https://example.com/ab")); // false
console.log(pattern.test("https://example.com/ax")); // false

```
 
```
// negative-lookahead
const pattern = new URLPattern({ pathname: "(a(?!b))" });
console.log(pattern.test("https://example.com/ab")); // false
console.log(pattern.test("https://example.com/ax")); // false

```
 
```
// lookbehind
const pattern = new URLPattern({ pathname: "((?<=b)a)" });
console.log(pattern.test("https://example.com/ba")); // false
console.log(pattern.test("https://example.com/xa")); // false

```
 
```
// negative-lookbehind
const pattern = new URLPattern({ pathname: "((?<!b)a)" });
console.log(pattern.test("https://example.com/ba")); // false
console.log(pattern.test("https://example.com/xa")); // false

```
* Parentheses need to be escaped in range expressions within URLPattern even though they don't in RegExp. 
```
new URLPattern({ pathname: "([()])" }); // throws
new URLPattern({ pathname: "([\\(\\)])" }); // ok

new RegExp("[()]"); // ok
new RegExp("[\\(\\)]"); // ok

```



### Unnamed and named groups



 Groups can either be named or unnamed. Named groups are specified by prefixing the group name with a colon (`:`). Regexp groups that are not prefixed by a colon and a name are unnamed. Unnamed groups are numerically indexed in the match result based on their order in the pattern. 

 
```
// A named group
const pattern = new URLPattern("/books/:id(\\d+)", "https://example.com");
console.log(pattern.exec("https://example.com/books/123").pathname.groups); // { id: '123' }

```
 
```
// An unnamed group
const pattern = new URLPattern("/books/(\\d+)", "https://example.com");
console.log(pattern.exec("https://example.com/books/123").pathname.groups); // { '0': '123' }

```


### Group modifiers



 Groups can also have modifiers. These are specified after the group name (or after the regexp if there is one). There are three modifiers: `?` to make the group optional, `+` to make the group repeat one or more times, and `*` to make the group repeat zero or more times. 

 
```
// An optional group
const pattern = new URLPattern("/books/:id?", "https://example.com");
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books")); // true
console.log(pattern.test("https://example.com/books/")); // false
console.log(pattern.test("https://example.com/books/123/456")); // false
console.log(pattern.test("https://example.com/books/123/456/789")); // false

```
 
```
// A repeating group with a minimum of one
const pattern = new URLPattern("/books/:id+", "https://example.com");
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books")); // false
console.log(pattern.test("https://example.com/books/")); // false
console.log(pattern.test("https://example.com/books/123/456")); // true
console.log(pattern.test("https://example.com/books/123/456/789")); // true

```
 
```
// A repeating group with a minimum of zero
const pattern = new URLPattern("/books/:id\*", "https://example.com");
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books")); // true
console.log(pattern.test("https://example.com/books/")); // false
console.log(pattern.test("https://example.com/books/123/456")); // true
console.log(pattern.test("https://example.com/books/123/456/789")); // true

```


### Group delimiters



 Patterns can also contain group delimiters. These are pieces of a pattern that are surrounded by curly braces (`{}`). These group delimiters are not captured in the match result like capturing groups, but can still have modifiers applied to them, just like groups. If group delimiters are not modified by a modifier, they are treated as if the items in them were just part of the parent pattern. Group delimiters may not contain other group delimiters, but may contain any other pattern items (capturing groups, regex, wildcard, or fixed text). 

 
```
// A group delimiter with a ? (optional) modifier
const pattern = new URLPattern("/book{s}?", "https://example.com");
console.log(pattern.test("https://example.com/books")); // true
console.log(pattern.test("https://example.com/book")); // true
console.log(pattern.exec("https://example.com/books").pathname.groups); // {}

```
 
```
// A group delimiter without a modifier
const pattern = new URLPattern("/book{s}", "https://example.com");
console.log(pattern.pathname); // /books
console.log(pattern.test("https://example.com/books")); // true
console.log(pattern.test("https://example.com/book")); // false

```
 
```
// A group delimiter containing a capturing group
const pattern = new URLPattern({ pathname: "/blog/:id(\\d+){-:title}?" });
console.log(pattern.test("https://example.com/blog/123-my-blog")); // true
console.log(pattern.test("https://example.com/blog/123")); // true
console.log(pattern.test("https://example.com/blog/my-blog")); // false

```


### Automatic group prefixing in pathnames



 In patterns that match against the `pathname` part of a URL, groups get an automatic slash (`/`) prefix added if the group definition is preceded by a slash (`/`). This is useful for groups with modifiers, as it allows for repeating groups to work as expected. 

  If you do not want automatic prefixing, you can disable it by surrounding the group with group delimiters (`{}`). Group delimiters do not have automatic prefixing behavior. 

 
```
// A pattern with an optional group, preceded by a slash
const pattern = new URLPattern("/books/:id?", "https://example.com");
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books")); // true
console.log(pattern.test("https://example.com/books/")); // false

```
 
```
// A pattern with a repeating group, preceded by a slash
const pattern = new URLPattern("/books/:id+", "https://example.com");
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books/123/456")); // true
console.log(pattern.test("https://example.com/books/123/")); // false
console.log(pattern.test("https://example.com/books/123/456/")); // false

```
 
```
// Segment prefixing does not occur outside of pathname patterns
const pattern = new URLPattern({ hash: "/books/:id?" });
console.log(pattern.test("https://example.com#/books/123")); // true
console.log(pattern.test("https://example.com#/books")); // false
console.log(pattern.test("https://example.com#/books/")); // true

```
 
```
// Disabling segment prefixing for a group using a group delimiter
const pattern = new URLPattern({ pathname: "/books/{:id}?" });
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books")); // false
console.log(pattern.test("https://example.com/books/")); // true

```


### Wildcard tokens



 The wildcard token (`*`) is a shorthand for an unnamed capturing group that matches all characters zero or more times. You can place this anywhere in the pattern. The wildcard is greedy, meaning that it will match the longest possible string. 

 
```
// A wildcard at the end of a pattern
const pattern = new URLPattern("/books/\*", "https://example.com");
console.log(pattern.test("https://example.com/books/123")); // true
console.log(pattern.test("https://example.com/books")); // false
console.log(pattern.test("https://example.com/books/")); // true
console.log(pattern.test("https://example.com/books/123/456")); // true

```
 
```
// A wildcard in the middle of a pattern
const pattern = new URLPattern("/\*.png", "https://example.com");
console.log(pattern.test("https://example.com/image.png")); // true
console.log(pattern.test("https://example.com/image.png/123")); // false
console.log(pattern.test("https://example.com/folder/image.png")); // true
console.log(pattern.test("https://example.com/.png")); // true

```


### Pattern normalization


 When a pattern is parsed it is automatically normalized to a canonical form. For example, unicode characters are percent encoded in the pathname property, punycode encoding is used in the hostname, default port numbers are elided, paths like `/foo/./bar/` are collapsed to just `/foo/bar`, etc. In addition, there are some pattern representations that parse to the same underlying meaning, like `foo` and `{foo}`. Such cases are normalized to the simplest form. In this case `{foo}` gets changed to `foo`. 


Case sensitivity
----------------



The URL Pattern API treats many parts of the URL as case-sensitive by default when matching. In contrast, many client-side JavaScript frameworks use case-insensitive URL matching. An `ignoreCase` option is available on the [`URLPattern()`](urlpattern/urlpattern) constructor to enable case-insensitive matching if desired.

 
```
// Case-sensitive matching by default
const pattern = new URLPattern("https://example.com/2022/feb/\*");
console.log(pattern.test("https://example.com/2022/feb/xc44rsz")); // true
console.log(pattern.test("https://example.com/2022/Feb/xc44rsz")); // false

```
 Setting the `ignoreCase` option to `true` in the constructor switches all matching operations to case-insensitive for the given pattern:

 
```
// Case-insensitive matching
const pattern = new URLPattern("https://example.com/2022/feb/\*", {
  ignoreCase: true,
});
console.log(pattern.test("https://example.com/2022/feb/xc44rsz")); // true
console.log(pattern.test("https://example.com/2022/Feb/xc44rsz")); // true

```


Examples
--------


### Filter on a specific URL component



 The following example shows how a `URLPattern` filters a specific URL component. When the `URLPattern()` constructor is called with a structured object of component patterns any missing components default to the `*` wildcard value. 

 
```
// Construct a URLPattern that matches a specific domain and its subdomains.
// All other URL components default to the wildcard `\*` pattern.
const pattern = new URLPattern({
  hostname: "{\*.}?example.com",
});

console.log(pattern.hostname); // '{\*.}?example.com'

console.log(pattern.protocol); // '\*'
console.log(pattern.username); // '\*'
console.log(pattern.password); // '\*'
console.log(pattern.pathname); // '\*'
console.log(pattern.search); // '\*'
console.log(pattern.hash); // '\*'

console.log(pattern.test("https://example.com/foo/bar")); // true

console.log(pattern.test({ hostname: "cdn.example.com" })); // true

console.log(pattern.test("custom-protocol://example.com/other/path?q=1")); // false

// Prints `false` because the hostname component does not match
console.log(pattern.test("https://cdn-example.com/foo/bar"));

```


### Construct a URLPattern from a full URL string



 The following example shows how to construct a `URLPattern` from a full URL string with embedded patterns. For example, a `:` can be both the URL protocol suffix, like `https:`, and the beginning of a named pattern group, like `:foo`. It "just works" if there is no ambiguity between whether a character is part of the URL syntax or part of the pattern syntax. 

 
```
// Construct a URLPattern that matches URLs to CDN servers loading jpg images.
// URL components not explicitly specified, like search and hash here, result
// in the empty string similar to the URL() constructor.
const pattern = new URLPattern("https://cdn-\*.example.com/\*.jpg");

console.log(pattern.protocol); // 'https'

console.log(pattern.hostname); // 'cdn-\*.example.com'

console.log(pattern.pathname); // '/\*.jpg'

console.log(pattern.username); // ''
console.log(pattern.password); // ''
console.log(pattern.search); // ''
console.log(pattern.hash); // ''

// Prints `true`
console.log(
  pattern.test("https://cdn-1234.example.com/product/assets/hero.jpg")
);

// Prints `false` because the search component does not match
console.log(
  pattern.test("https://cdn-1234.example.com/product/assets/hero.jpg?q=1")
);

```


### Constructing a URLPattern with an ambiguous URL string



 The following example shows how a `URLPattern` constructed from an ambiguous string will favor treating characters as part of the pattern syntax. In this case the `:` character could be the protocol component suffix or it could be the prefix for a named group in the pattern. The constructor chooses to treat this as part of the pattern and therefore determines this is a relative pathname pattern. Since there is no base URL the relative pathname cannot be resolved and it throws an error. 

 
```
// Throws because this is interpreted as a single relative pathname pattern
// with a ":foo" named group and there is no base URL.
const pattern = new URLPattern("data:foo\*");

```


### Escaping characters to disambiguate URLPattern constructor strings



 The following example shows how an ambiguous constructor string character can be escaped to be treated as a URL separator instead of a pattern character. Here `:` is escaped as `\\:`. 

 
```
// Constructs a URLPattern treating the `:` as the protocol suffix.
const pattern = new URLPattern("data\\:foo\*");

console.log(pattern.protocol); // 'data'

console.log(pattern.pathname); // 'foo\*'

console.log(pattern.username); // ''
console.log(pattern.password); // ''
console.log(pattern.hostname); // ''
console.log(pattern.port); // ''
console.log(pattern.search); // ''
console.log(pattern.hash); // ''

console.log(pattern.test("data:foobar")); // true

```


### Using base URLs for test() and exec()



The following example shows how `test()` and `exec()` can use base URLs.

 
```
const pattern = new URLPattern({ hostname: "example.com", pathname: "/foo/\*" });

// Prints `true` as the hostname based in the dictionary `baseURL` property
// matches.
console.log(
  pattern.test({
    pathname: "/foo/bar",
    baseURL: "https://example.com/baz",
  })
);

// Prints `true` as the hostname in the second argument base URL matches.
console.log(pattern.test("/foo/bar", "https://example.com/baz"));

// Throws because the second argument cannot be passed with a dictionary input.
try {
  pattern.test({ pathname: "/foo/bar" }, "https://example.com/baz");
} catch (e) {}

// The `exec()` method takes the same arguments as `test()`.
const result = pattern.exec("/foo/bar", "https://example.com/baz");

console.log(result.pathname.input); // '/foo/bar'

console.log(result.pathname.groups[0]); // 'bar'

console.log(result.hostname.input); // 'example.com'

```


### Using base URLs in the URLPattern constructor



 The follow example shows how base URLs can also be used to construct the `URLPattern`. Note that the base URL in these cases is treated strictly as a URL and cannot contain any pattern syntax itself. 

  Also, since the base URL provides a value for every component the resulting `URLPattern` will also have a value for every component, even if it's the empty string. This means you do not get the "default to wildcard" behavior. 

 
```
const pattern1 = new URLPattern({
  pathname: "/foo/\*",
  baseURL: "https://example.com",
});

console.log(pattern1.protocol); // 'https'
console.log(pattern1.hostname); // 'example.com'
console.log(pattern1.pathname); // '/foo/\*'

console.log(pattern1.username); // ''
console.log(pattern1.password); // ''
console.log(pattern1.port); // ''
console.log(pattern1.search); // ''
console.log(pattern1.hash); // ''

// Equivalent to pattern1
const pattern2 = new URLPattern("/foo/\*", "https://example.com");

// Throws because a relative constructor string must have a base URL to resolve
// against.
try {
  const pattern3 = new URLPattern("/foo/\*");
} catch (e) {}

```


### Accessing matched group values



 The following example shows how input values that match pattern groups can later be accessed from the `exec()` result object. Unnamed groups are assigned index numbers sequentially. 

 
```
const pattern = new URLPattern({ hostname: "\*.example.com" });
const result = pattern.exec({ hostname: "cdn.example.com" });

console.log(result.hostname.groups[0]); // 'cdn'

console.log(result.hostname.input); // 'cdn.example.com'

console.log(result.inputs); // [{ hostname: 'cdn.example.com' }]

```


### Accessing matched group values using custom names



 The following example shows how groups can be given custom names which can be used to accessed the matched value in the result object. 

 
```
// Construct a URLPattern using matching groups with custom names. These
// names can then be later used to access the matched values in the result
// object.
const pattern = new URLPattern({ pathname: "/:product/:user/:action" });
const result = pattern.exec({ pathname: "/store/wanderview/view" });

console.log(result.pathname.groups.product); // 'store'
console.log(result.pathname.groups.user); // 'wanderview'
console.log(result.pathname.groups.action); // 'view'

console.log(result.pathname.input); // '/store/wanderview/view'

console.log(result.inputs); // [{ pathname: '/store/wanderview/view' }]

```


### Custom regular expression groups



 The following example shows how a matching group can use a custom regular expression. 

 
```
const pattern = new URLPattern({ pathname: "/(foo|bar)" });

console.log(pattern.test({ pathname: "/foo" })); // true
console.log(pattern.test({ pathname: "/bar" })); // true
console.log(pattern.test({ pathname: "/baz" })); // false

const result = pattern.exec({ pathname: "/foo" });

console.log(result.pathname.groups[0]); // 'foo'

```


### Named group with a custom regular expression



 The following example shows how to use a custom regular expression with a named group. 

 
```
const pattern = new URLPattern({ pathname: "/:type(foo|bar)" });
const result = pattern.exec({ pathname: "/foo" });

console.log(result.pathname.groups.type); // 'foo'

```


### Making matching groups optional



 The following example shows how to make a matching group optional by placing a `?` modifier after it. For the pathname component this also causes any preceding `/` character to be treated as an optional prefix to the group. 

 
```
const pattern = new URLPattern({ pathname: "/product/(index.html)?" });

console.log(pattern.test({ pathname: "/product/index.html" })); // true
console.log(pattern.test({ pathname: "/product" })); // true

const pattern2 = new URLPattern({ pathname: "/product/:action?" });

console.log(pattern2.test({ pathname: "/product/view" })); // true
console.log(pattern2.test({ pathname: "/product" })); // true

// Wildcards can be made optional as well. This may not seem to make sense
// since they already match the empty string, but it also makes the prefix
// `/` optional in a pathname pattern.
const pattern3 = new URLPattern({ pathname: "/product/\*?" });

console.log(pattern3.test({ pathname: "/product/wanderview/view" })); // true
console.log(pattern3.test({ pathname: "/product" })); // true
console.log(pattern3.test({ pathname: "/product/" })); // true

```


### Making matching groups repeated



 The following example shows how a matching group can be made repeated by placing `+` modifier after it. In the `pathname` component this also treats the `/` prefix as special. It is repeated with the group. 

 
```
const pattern = new URLPattern({ pathname: "/product/:action+" });
const result = pattern.exec({ pathname: "/product/do/some/thing/cool" });

result.pathname.groups.action; // 'do/some/thing/cool'

console.log(pattern.test({ pathname: "/product" })); // false

```


### Making matching groups optional and repeated



 The following example shows how to make a matching group that is both optional and repeated. Do this by placing a `*` modifier after the group. Again, the pathname component treats the `/` prefix as special. It both becomes optional and is also repeated with the group. 

 
```
const pattern = new URLPattern({ pathname: "/product/:action\*" });
const result = pattern.exec({ pathname: "/product/do/some/thing/cool" });

console.log(result.pathname.groups.action); // 'do/some/thing/cool'

console.log(pattern.test({ pathname: "/product" })); // true

```


### Using a custom prefix or suffix for an optional or repeated modifier



 The following example shows how curly braces can be used to denote a custom prefix and/or suffix to be operated on by a subsequent `?`, `*`, or `+` modifier. 

 
```
const pattern = new URLPattern({ hostname: "{:subdomain.}\*example.com" });

console.log(pattern.test({ hostname: "example.com" })); // true
console.log(pattern.test({ hostname: "foo.bar.example.com" })); // true
console.log(pattern.test({ hostname: ".example.com" })); // false

const result = pattern.exec({ hostname: "foo.bar.example.com" });

console.log(result.hostname.groups.subdomain); // 'foo.bar'

```


### Making text optional or repeated without a matching group



 The following example shows how curly braces can be used to denote fixed text values as optional or repeated without using a matching group. 

 
```
const pattern = new URLPattern({ pathname: "/product{/}?" });

console.log(pattern.test({ pathname: "/product" })); // true
console.log(pattern.test({ pathname: "/product/" })); // true

const result = pattern.exec({ pathname: "/product/" });

console.log(result.pathname.groups); // {}

```


### Using multiple components and features at once



 The following example shows how many features can be combined across multiple URL components. 

 
```
const pattern = new URLPattern({
  protocol: "http{s}?",
  username: ":user?",
  password: ":pass?",
  hostname: "{:subdomain.}\*example.com",
  pathname: "/product/:action\*",
});

const result = pattern.exec(
  "http://foo:bar@sub.example.com/product/view?q=12345"
);

console.log(result.username.groups.user); // 'foo'
console.log(result.password.groups.pass); // 'bar'
console.log(result.hostname.groups.subdomain); // 'sub'
console.log(result.pathname.groups.action); // 'view'

```


Specifications
--------------




| Specification |
| --- |
| [URLPattern API # urlpattern](https://wicg.github.io/urlpattern/#urlpattern) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `URLPattern` | 95 | 95 | No | No | 81 | No | 95 | 95 | No | 67 | No | 17.0 |
| `URL_Pattern_API` | 95 | 95 | No | No | 81 | No | 95 | 95 | No | 67 | No | 17.0 |
| `exec` | 95 | 95 | No | No | 81 | No | 95 | 95 | No | 67 | No | 17.0 |
| `hash` | 95 | 95 | No | No | 81 | No | 95 | 95 | No | 67 | No | 17.0 |
| `hostname` | 95 | 95 | No | No | 81 | No | 95 | 95 | No | 67 | No | 17.0 |
| `password` | 95 | 95 | No | No | 81 | No | 95 | 95 | No | 67 | No | 17.0 |
| `pathname` | 95 | 95 | No | No | 81 | No | 95 | 95 | No | 67 | No | 17.0 |
| `port` | 95 | 95 | No | No | 81 | No | 95 | 95 | No | 67 | No | 17.0 |
| `protocol` | 95 | 95 | No | No | 81 | No | 95 | 95 | No | 67 | No | 17.0 |
| `search` | 95 | 95 | No | No | 81 | No | 95 | 95 | No | 67 | No | 17.0 |
| `test` | 95 | 95 | No | No | 81 | No | 95 | 95 | No | 67 | No | 17.0 |
| `username` | 95 | 95 | No | No | 81 | No | 95 | 95 | No | 67 | No | 17.0 |


See also
--------


* A polyfill of `URLPattern` is available [on GitHub](https://github.com/kenchris/urlpattern-polyfill)
* The pattern syntax used by URLPattern is similar to the syntax used by [path-to-regexp](https://github.com/pillarjs/path-to-regexp)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API>

Notifications API
=================



 **Note:** This feature is available in [Web Workers](web_workers_api)

 
**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The Notifications API allows web pages to control the display of system notifications to the end user. These are outside the top-level browsing context viewport, so therefore can be displayed even when the user has switched tabs or moved to a different app. The API is designed to be compatible with existing notification systems, across different platforms.



Concepts and usage
------------------



On supported platforms, showing a system notification generally involves two things. First, the user needs to grant the current origin permission to display system notifications, which is generally done when the app or site initializes, using the [`Notification.requestPermission()`](notification/requestpermission) method. This should be done in response to a user gesture, such as clicking a button, for example:

 
```
btn.addEventListener("click", () => {
  let promise = Notification.requestPermission();
  // wait for permission
});

```
 This is not only best practice — you should not be spamming users with notifications they didn't agree to — but going forward browsers will explicitly disallow notifications not triggered in response to a user gesture. Firefox is already doing this from version 72, for example.

 This will spawn a request dialog, along the following lines:

  ![A dialog box asking the user to allow notifications from that origin. There are options to never allow or allow notifications.] 

 From here the user can choose to allow notifications from this origin, or block them. Once a choice has been made, the setting will generally persist for the current session.

  **Note:** As of Firefox 44, the permissions for Notifications and [Push](push_api) have been merged. If permission is granted for notifications, push will also be enabled.

  Next, a new notification is created using the [`Notification()`](notification/notification) constructor. This must be passed a title argument, and can optionally be passed an options object to specify options, such as text direction, body text, icon to display, notification sound to play, and more.

 In addition, the Notifications API spec specifies a number of additions to the [ServiceWorker API](service_worker_api), to allow service workers to fire notifications.

  **Note:** To find out more about using notifications in your own app, read [Using the Notifications API](notifications_api/using_the_notifications_api).

 

Notifications interfaces
------------------------


 [`Notification`](notification)  Defines a notification object.

  
### Service worker additions


 [`ServiceWorkerRegistration`](serviceworkerregistration)  Includes the [`ServiceWorkerRegistration.showNotification()`](serviceworkerregistration/shownotification) and [`ServiceWorkerRegistration.getNotifications()`](serviceworkerregistration/getnotifications) method, for controlling the display of notifications.

  [`ServiceWorkerGlobalScope`](serviceworkerglobalscope)  Includes the [`onnotificationclick`](serviceworkerglobalscope/notificationclick_event) handler, for firing custom functions when a notification is clicked.

  [`NotificationEvent`](notificationevent)  A specific type of event object, based on [`ExtendableEvent`](extendableevent), which represents a notification that has fired.

  
Specifications
--------------




| Specification |
| --- |
| [Notifications API Standard # api](https://notifications.spec.whatwg.org/#api) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Notification` | 20 | 14 | 224 | No | 23 | 7 | No | No | 224 | No | 16.4 | No |
| `Notifications_API` | 20["Starting in Chrome 49, notifications do not work in incognito mode.", "Before Chrome 42, service worker additions were not supported."] | 14 | 224 | No | 23["Starting in Opera 36, notifications do not work in incognito mode.", "Before Opera 29, service worker additions were not supported."] | 7 | NoSee [bug 551446](https://crbug.com/551446). | 42["Notifications in Chrome for Android are only available through service workers. To show notifications on Android, see [`ServiceWorkerRegistration.showNotification()`](https://developer.mozilla.org/docs/Web/API/ServiceWorkerRegistration/showNotification).", "Starting in Chrome 49, notifications do not work in incognito mode."] | 224 | 29["Notifications in Opera for Android are only available through service workers. To show notifications on Android, see [`ServiceWorkerRegistration.showNotification()`](https://developer.mozilla.org/docs/Web/API/ServiceWorkerRegistration/showNotification).", "Starting in Opera for Android 36, notifications do not work in incognito mode."] | 16.4 | 4.0["Notifications in Samsung Internet are only available through service workers. To show notifications on Android, see [`ServiceWorkerRegistration.showNotification()`](https://developer.mozilla.org/docs/Web/API/ServiceWorkerRegistration/showNotification).", "Starting in Samsung Internet 5.0, notifications do not work in incognito mode."] |
| `actions` | 53 | 18 | No | No | 39 | No | No | 53 | No | 41 | No | 6.0 |
| `badge` | 53 | 18 | No | No | 39 | No | No | 53 | No | 41 | No | 6.0 |
| `body` | 33 | 14 | 26 | No | 23 | 11 | No | 42 | 26 | 29 | 16.4 | 4.0 |
| `click_event` | 20 | 14 | 22 | No | 23 | 7 | No | 42 | 22 | 29 | No | 4.0 |
| `close` | 20 | 14 | 22 | No | 23 | 7 | No | 42 | 22 | 29 | 16.4 | 4.0 |
| `close_event` | 20 | 14 | 22 | No | 23 | 7 | No | 42 | 22 | 29 | No | 4.0 |
| `data` | 44 | 16 | 34 | No | 31 | 16 | No | 44 | 34 | 32 | 16.4 | 4.0 |
| `dir` | 20 | 14 | 26 | No | 23 | 7 | No | 42 | 26 | 29 | 16.4 | 4.0 |
| `error_event` | 20 | 14 | 22 | No | 23 | 7 | No | 42 | 22 | 29 | No | 4.0 |
| `icon` | 33 | 14 | 26 | No | 23 | 11 | No | 42 | 26 | 29 | 16.4 | 4.0 |
| `image` | 56 | 18 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `lang` | 33 | 14 | 26 | No | 23 | 11 | No | 42 | 26 | 29 | 16.4 | 4.0 |
| `maxActions` | 48 | 18 | No | No | 35 | No | No | 48 | No | 35 | No | 5.0 |
| `permission` | 32 | 14 | 22 | No | 23 | 7 | No | 42 | 22 | 29 | 16.4 | 4.0 |
| `renotify` | 50 | 79 | No | No | 37 | No | No | 50 | No | 37 | No | 5.0 |
| `requestPermission` | 20 | 14 | 22["From Firefox 70 onwards, cannot be called from a cross-origin `iframe`.", "From Firefox 72 onwards, can only be called in response to a user gesture such as a `click` event."] | No | 23 | 157–15Only supported the deprecated callback syntax. | No | 42 | 22["From Firefox Android 79 onwards, cannot be called from a cross-origin `iframe`.", "From Firefox Android 79 onwards, can only be called in response to a user gesture such as a `click` event."] | 29 | 16.4 | 4.0 |
| `requireInteraction` | 47 | 17 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |
| `secure_context_required` | 62 | 79 | 67 | No | 49 | No | No | 62 | 67 | 46 | No | 8.0 |
| `show_event` | 20 | 14 | 22 | No | 23 | 7 | No | 42 | 22 | 29 | No | 4.0 |
| `silent` | 43 | 17 | No | No | 30 | No | No | 43 | No | 30 | No | 4.0 |
| `tag` | 20 | 14 | 26 | No | 23 | 7 | No | 42 | 26 | 29 | 16.4 | 4.0 |
| `timestamp` | 50 | 17 | No | No | 37 | No | No | 50 | No | 37 | No | 5.0 |
| `title` | 33 | 14 | 26 | No | 23 | 11 | No | 42 | 26 | 29 | 16.4 | 4.0 |
| `vibrate` | 53 | 79 | No | No | 40 | No | No | 53[Does not work](https://crbug.com/971422) on Android O or later regardless of Chrome version. | No | 41[Does not work](https://crbug.com/971422) on Android O or later regardless of Chrome version. | No | 6.0[Does not work](https://crbug.com/971422) on Android O or later regardless of Chrome version. |
| `worker_support` | 42 | 15 | 41 | No | 29 | No | No | 42 | 41 | 29 | No | 4.0 |


See also
--------


* [Using the Notifications API](notifications_api/using_the_notifications_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API>

Web Share API
=============



The **Web Share API** provides a mechanism for sharing text, links, files, and other content to an arbitrary *share target* selected by the user.


**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

  **Note:** This API is *not available* in [Web Workers](web_workers_api) (not exposed via [`WorkerNavigator`](workernavigator)).

   **Note:** This API should not be confused with the [Web Share Target API](https://developer.mozilla.org/en-US/docs/Web/Manifest/share_target), which allows a website to specify itself as a share target.

 

Concepts and usage
------------------



 The **Web Share API** allows a site to share text, links, files, and other content to user-selected share targets, utilizing the sharing mechanisms of the underlying operating system. These share targets typically include the system clipboard, email, contacts or messaging applications, and Bluetooth or Wi-Fi channels. 

  The API has just two methods. The [`navigator.canShare()`](navigator/canshare) method may be used to first validate whether some data is "shareable", prior to passing it to [`navigator.share()`](navigator/share) for sending. 

  The [`navigator.share()`](navigator/share) method invokes the native sharing mechanism of the underlying operating system and passes the specified data. It requires [transient activation](https://developer.mozilla.org/en-US/docs/Glossary/Transient_activation), and hence must be triggered off a UI event like a button click. Further, the method must specify valid data that is supported for sharing by the native implementation. 

  The Web Share API is gated by the [web-share](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy/web-share) Permissions Policy. If the policy is supported but has not been granted, both methods will indicate that the data is not shareable. 



Interfaces
----------


 [`navigator.canShare()`](navigator/canshare)  Returns a boolean indicating whether the specified data is shareable.

  [`navigator.share()`](navigator/share)   Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves if the passed data was successfully sent to a share target. This method must be called on a button click or other user activation (requires [transient activation](https://developer.mozilla.org/en-US/docs/Glossary/Transient_activation)). 

  
Example
-------



The code below shows how you can share a link using [`navigator.share()`](navigator/share), triggered off a button click.

 
```
const shareData = {
  title: "MDN",
  text: "Learn web development on MDN!",
  url: "https://developer.mozilla.org",
};

const btn = document.querySelector("button");
const resultPara = document.querySelector(".result");

// Share must be triggered by "user activation"
btn.addEventListener("click", async () => {
  try {
    await navigator.share(shareData);
    resultPara.textContent = "MDN shared successfully";
  } catch (err) {
    resultPara.textContent = `Error: ${err}`;
  }
});

```
 The above example is taken from our [Web share test](https://mdn.github.io/dom-examples/web-share/) ([see the source code](https://github.com/mdn/dom-examples/blob/main/web-share/index.html)). You can also see this as a live example in [`navigator.share()`](navigator/share).



Specifications
--------------




| Specification |
| --- |
| [Web Share API # share-method](https://w3c.github.io/web-share/#share-method) |
| [Web Share API # canshare-data-method](https://w3c.github.io/web-share/#canshare-data-method) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Web_Share_API` | 89Only supported on Chrome OS and Windows, see [bug 770595](https://crbug.com/770595) and [bug 1144920](https://crbug.com/1144920). | 9389–93Only supported on Windows. | 96 | No | 75Only supported on Opera OS and Windows, see [bug 770595](https://crbug.com/770595) and [bug 1144920](https://crbug.com/1144920). | 14 | No | 75 | 96 | 54 | 14 | 11.0 |
| `data_files_parameter` | 89 | 89 | No | No | 75 | 15 | No | 76 | No | 54 | 15 | 11.0 |
| `data_text_parameter` | 89 | 89 | 96 | No | 75 | 15 | No | 76 | No | 54 | 15 | 11.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Web_Share_API` | 89Only supported on Chrome OS and Windows, see [bug 770595](https://crbug.com/770595) and [bug 1144920](https://crbug.com/1144920). | 9389–93Only supported on Windows. | 71 | No | 75Only supported on Opera OS and Windows, see [bug 770595](https://crbug.com/770595) and [bug 1144920](https://crbug.com/1144920). | 12.1 | No | 61 | 79 | 48 | 12.2 | 8.0 |
| `data_files_parameter` | 89 | 89 | No | No | 75 | 15 | No | 76 | No | 54 | 15 | 11.0 |
| `data_text_parameter` | 89 | 89 | 71 | No | 75 | 15 | No | 76 | No | 54 | 15 | 11.0 |


### api.Navigator.share


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.Navigator.canShare


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


See also
--------


* [Web Share Target API](https://developer.mozilla.org/en-US/docs/Web/Manifest/share_target)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Web_Share_API>

Web Speech API
==============


 The **Web Speech API** enables you to incorporate voice data into web apps. The Web Speech API has two parts: `SpeechSynthesis` (Text-to-Speech), and `SpeechRecognition` (Asynchronous Speech Recognition.) 


Web Speech Concepts and Usage
-----------------------------



 The Web Speech API makes web apps able to handle voice data. There are two components to this API: 

 * Speech recognition is accessed via the [`SpeechRecognition`](speechrecognition) interface, which provides the ability to recognize voice context from an audio input (normally via the device's default speech recognition service) and respond appropriately. Generally you'll use the interface's constructor to create a new [`SpeechRecognition`](speechrecognition) object, which has a number of event handlers available for detecting when speech is input through the device's microphone. The [`SpeechGrammar`](speechgrammar) interface represents a container for a particular set of grammar that your app should recognize. Grammar is defined using [JSpeech Grammar Format](https://www.w3.org/TR/jsgf/) (**JSGF**.)
* Speech synthesis is accessed via the [`SpeechSynthesis`](speechsynthesis) interface, a text-to-speech component that allows programs to read out their text content (normally via the device's default speech synthesizer.) Different voice types are represented by [`SpeechSynthesisVoice`](speechsynthesisvoice) objects, and different parts of text that you want to be spoken are represented by [`SpeechSynthesisUtterance`](speechsynthesisutterance) objects. You can get these spoken by passing them to the [`SpeechSynthesis.speak()`](speechsynthesis/speak) method.

 For more details on using these features, see [Using the Web Speech API](web_speech_api/using_the_web_speech_api).



Web Speech API Interfaces
-------------------------


### Speech recognition


 [`SpeechRecognition`](speechrecognition)  The controller interface for the recognition service; this also handles the [`SpeechRecognitionEvent`](speechrecognitionevent) sent from the recognition service.

  [`SpeechRecognitionAlternative`](speechrecognitionalternative)  Represents a single word that has been recognized by the speech recognition service.

  [`SpeechRecognitionErrorEvent`](speechrecognitionerrorevent)  Represents error messages from the recognition service.

  [`SpeechRecognitionEvent`](speechrecognitionevent)  The event object for the [`result`](speechrecognition/result_event) and [`nomatch`](speechrecognition/nomatch_event) events, and contains all the data associated with an interim or final speech recognition result.

  [`SpeechGrammar`](speechgrammar)  The words or patterns of words that we want the recognition service to recognize.

  [`SpeechGrammarList`](speechgrammarlist)  Represents a list of [`SpeechGrammar`](speechgrammar) objects.

  [`SpeechRecognitionResult`](speechrecognitionresult)  Represents a single recognition match, which may contain multiple [`SpeechRecognitionAlternative`](speechrecognitionalternative) objects.

  [`SpeechRecognitionResultList`](speechrecognitionresultlist)  Represents a list of [`SpeechRecognitionResult`](speechrecognitionresult) objects, or a single one if results are being captured in [`continuous`](speechrecognition/continuous) mode.

  
### Speech synthesis


 [`SpeechSynthesis`](speechsynthesis)  The controller interface for the speech service; this can be used to retrieve information about the synthesis voices available on the device, start and pause speech, and other commands besides.

  [`SpeechSynthesisErrorEvent`](speechsynthesiserrorevent)  Contains information about any errors that occur while processing [`SpeechSynthesisUtterance`](speechsynthesisutterance) objects in the speech service.

  [`SpeechSynthesisEvent`](speechsynthesisevent)  Contains information about the current state of [`SpeechSynthesisUtterance`](speechsynthesisutterance) objects that have been processed in the speech service.

  [`SpeechSynthesisUtterance`](speechsynthesisutterance)   Represents a speech request. It contains the content the speech service should read and information about how to read it (e.g. language, pitch and volume.) 

  [`SpeechSynthesisVoice`](speechsynthesisvoice)   Represents a voice that the system supports. Every `SpeechSynthesisVoice` has its own relative speech service including information about language, name and URI. 

  [`Window.speechSynthesis`](window/speechsynthesis)  Specified out as part of a `[NoInterfaceObject]` interface called `SpeechSynthesisGetter`, and Implemented by the `Window` object, the `speechSynthesis` property provides access to the [`SpeechSynthesis`](speechsynthesis) controller, and therefore the entry point to speech synthesis functionality.

  
Errors
------



For information on errors reported by the Speech API (for example, `"language-not-supported"` and `"language-unavailable"`), see the following documentation:

 * [`error` property of the `SpeechRecognitionErrorEvent` object](speechrecognitionerrorevent/error)
* [`error` property of the `SpeechSynthesisErrorEvent` object](speechsynthesiserrorevent/error)



Examples
--------


The [Web Speech API examples](https://github.com/mdn/dom-examples/tree/main/web-speech-api) on GitHub contains demos to illustrate speech recognition and synthesis.


Specifications
--------------




| Specification |
| --- |
| [Web Speech API # speechreco-section](https://wicg.github.io/speech-api/#speechreco-section) |
| [Web Speech API # tts-section](https://wicg.github.io/speech-api/#tts-section) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Web_Speech_API` | 33 | 14 | 49 | No | 21 | 7 | NoSee [bug 487255](https://crbug.com/487255). | 33 | 62 | No | 7 | 3.0 |
| `cancel` | 33 | 14 | 49 | No | 21 | 7 | No | 33 | 62 | No | 7 | 3.0 |
| `getVoices` | 33 | 14 | 49 | No | 21 | 7 | No | 33 | 62 | No | 7 | 3.0 |
| `pause` | 33 | 14 | 49 | No | 21 | 7 | No | 33In Android, `pause()` ends the current utterance. `pause()` behaves the same as `cancel()`. | 62In Android, `pause()` ends the current utterance. `pause()` behaves the same as `cancel()`. | No | 7 | 3.0In Android, `pause()` ends the current utterance. `pause()` behaves the same as `cancel()`. |
| `paused` | 33 | 14 | 49 | No | 21 | 7 | No | 33 | 62 | No | 7 | 3.0 |
| `pending` | 33 | 14 | 49 | No | 21 | 7 | No | 33 | 62 | No | 7 | 3.0 |
| `resume` | 33 | 14 | 49 | No | 21 | 7 | No | 33 | 62 | No | 7 | 3.0 |
| `speak` | 33 | 14 | 49 | No | 21 | 7 | No | 33 | 62 | No | 7 | 3.0 |
| `speaking` | 33 | 14 | 49 | No | 21 | 7 | No | 33 | 62 | No | 7 | 3.0 |
| `voiceschanged_event` | 33 | 14 | 49 | No | 21 | 16 | No | 33 | 62 | No | 16 | 3.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `SpeechRecognition` | 33 | 79 | No | No | No | 14.1 | 37 | 33 | No | No | 14.5 | 2.0 |
| `Web_Speech_API` | 33You'll need to serve your code through a web server for recognition to work. | 79You'll need to serve your code through a web server for recognition to work. | No | No | 20You'll need to serve your code through a web server for recognition to work. | 14.1 | 4.4.3You'll need to serve your code through a web server for recognition to work. | 33You'll need to serve your code through a web server for recognition to work. | No | 20You'll need to serve your code through a web server for recognition to work. | 14.5 | 2.0You'll need to serve your code through a web server for recognition to work. |
| `abort` | 33 | 79 | No | No | 20 | 14.1 | 4.4.3 | 33 | No | 20 | 14.5 | 2.0 |
| `audioend_event` | 33 | 79 | No | No | 20 | 14.1 | 4.4.3 | 33 | No | 20 | 14.5 | 2.0 |
| `audiostart_event` | 33 | 79 | No | No | 20 | 14.1 | 4.4.3 | 33 | No | 20 | 14.5 | 2.0 |
| `continuous` | 33 | 79 | No | No | 20 | 14.1 | 4.4.3 | 33 | No | 20 | 14.5 | 2.0 |
| `end_event` | 33 | 79 | No | No | 20 | 14.1 | 4.4.3 | 33 | No | 20 | 14.5 | 2.0 |
| `error_event` | 33 | 79 | No | No | 20 | 14.1 | 4.4.3 | 33 | No | 20 | 14.5 | 2.0 |
| `grammars` | 33 | 79 | No | No | 20 | No | 4.4.3 | 33 | No | 20 | No | 2.0 |
| `interimResults` | 33 | 79 | No | No | 20 | 14.1 | 4.4.3 | 33 | No | 20 | 14.5 | 2.0 |
| `lang` | 33 | 79 | No | No | 20 | 14.1 | 4.4.3 | 33 | No | 20 | 14.5 | 2.0 |
| `maxAlternatives` | 33 | 79 | No | No | 20 | 14.1 | 4.4.3 | 33 | No | 20 | 14.5 | 2.0 |
| `nomatch_event` | 33 | 79 | No | No | 20 | 14.1 | 4.4.3 | 33 | No | 20 | 14.5 | 2.0 |
| `result_event` | 33 | 79 | No | No | 20 | 14.1 | 4.4.3 | 33 | No | 20 | 14.5 | 2.0 |
| `soundend_event` | 33 | 79 | No | No | 20 | 14.1 | 4.4.3 | 33 | No | 20 | 14.5 | 2.0 |
| `soundstart_event` | 33 | 79 | No | No | 20 | 14.1 | 4.4.3 | 33 | No | 20 | 14.5 | 2.0 |
| `speechend_event` | 33 | 79 | No | No | 20 | 14.1 | 4.4.3 | 33 | No | 20 | 14.5 | 2.0 |
| `speechstart_event` | 33 | 79 | No | No | 20 | 14.1 | 4.4.3 | 33 | No | 20 | 14.5 | 2.0 |
| `start` | 33 | 79 | No | No | 20 | 14.1 | 4.4.3 | 33 | No | 20 | 14.5 | 2.0 |
| `start_event` | 33 | 79 | No | No | 20 | 14.1 | 4.4.3 | 33 | No | 20 | 14.5 | 2.0 |
| `stop` | 33 | 79 | No | No | 20 | 14.1 | 4.4.3 | 33 | No | 20 | 14.5 | 2.0 |


### api.SpeechRecognition


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.SpeechSynthesis


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


See also
--------


* [Using the Web Speech API](web_speech_api/using_the_web_speech_api)
* [SitePoint article](https://www.sitepoint.com/talking-web-pages-and-the-speech-synthesis-api/)
* [HTML5Rocks article](https://developer.chrome.com/blog/web-apps-that-talk-introduction-to-the-speech-synthesis-api/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API>

Web Storage API
===============


The **Web Storage API** provides mechanisms by which browsers can store key/value pairs, in a much more intuitive fashion than using [cookies](https://developer.mozilla.org/en-US/docs/Glossary/Cookie).


Web Storage concepts and usage
------------------------------



The two mechanisms within Web Storage are as follows:

 * `sessionStorage` maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, including page reloads and restores).
	+ Stores data only for a session, meaning that the data is stored until the browser (or tab) is closed.
	+ Data is never transferred to the server.
	+ Storage limit is larger than a cookie (at most 5MB).
* `localStorage` does the same thing, but persists even when the browser is closed and reopened.
	+ Stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser cache / Locally Stored Data.
	+ Storage limit is the maximum amongst the two.

 These mechanisms are available via the [`Window.sessionStorage`](window/sessionstorage) and [`Window.localStorage`](window/localstorage) properties (to be more precise, in supporting browsers the `Window` object implements the `WindowLocalStorage` and `WindowSessionStorage` objects, which the `localStorage` and `sessionStorage` properties hang off) — invoking one of these will create an instance of the [`Storage`](storage) object, through which data items can be set, retrieved and removed. A different Storage object is used for the `sessionStorage` and `localStorage` for each origin — they function and are controlled separately.

  **Note:** From Firefox 45 onwards, when the browser crashes/restarts, the amount of data saved per origin is limited to 10MB. This has been done to avoid memory issues caused by excessive usage of web storage.

   **Note:** Access to Web Storage from third-party IFrames is denied if the user has [disabled third-party cookies](https://support.mozilla.org/en-US/kb/third-party-cookies-firefox-tracking-protection) (Firefox implements this behavior from [version 43](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Releases/43) onwards).

   **Note:** Web Storage is not the same as `mozStorage` (Mozilla's XPCOM interfaces to SQLite) or the `Session store API` (an XPCOM storage utility for use by extensions).

 

Web Storage interfaces
----------------------


 [`Storage`](storage)  Allows you to set, retrieve and remove data for a specific domain and storage type (session or local).

  [`Window`](window)  The Web Storage API extends the [`Window`](window) object with two new properties — [`Window.sessionStorage`](window/sessionstorage) and [`Window.localStorage`](window/localstorage) — which provide access to the current domain's session and local [`Storage`](storage) objects respectively, and a [`storage`](window/storage_event) event handler that fires when a storage area changes (e.g., a new item is stored).

  [`StorageEvent`](storageevent)  The `storage` event is fired on a document's `Window` object when a storage area changes.

  
Examples
--------



To illustrate some typical web storage usage, we have created a simple example, imaginatively called [Web Storage Demo](https://github.com/mdn/dom-examples/tree/main/web-storage). The [landing page](https://mdn.github.io/dom-examples/web-storage/) provides controls that can be used to customize the color, font and decorative image. When you choose different options, the page is instantly updated; in addition your choices are stored in `localStorage`, so that when you leave the page then load it again later on your choices are remembered.

 In addition, we have provided an [event output page](https://mdn.github.io/dom-examples/web-storage/event.html) — if you load this page in another tab, then make changes to your choices in the landing page, you'll see the updated storage information outputted as the [`StorageEvent`](storageevent) is fired.



Specifications
--------------




| Specification |
| --- |
| [HTML Standard # dom-localstorage-dev](https://html.spec.whatwg.org/multipage/webstorage.html#dom-localstorage-dev) |
| [HTML Standard # dom-sessionstorage-dev](https://html.spec.whatwg.org/multipage/webstorage.html#dom-sessionstorage-dev) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Web_Storage_API` | 4 | 12 | 2 | 8 | 10.5 | 4 | ≤37 | 18 | 4 | 11 | 3.2 | 1.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Web_Storage_API` | 4 | 12 | 3.5 | 8 | 10.5 | 4 | ≤37 | 18 | 4 | 11 | 3.2 | 1.0 |


### api.Window.localStorage


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.Window.sessionStorage


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


Private Browsing / Incognito modes
----------------------------------



Most modern browsers support a privacy option called 'Incognito', 'Private Browsing' or something similar that doesn't store data like history and cookies. This is fundamentally incompatible with Web Storage for obvious reasons. As such, browser vendors are experimenting with different scenarios for how to deal with this incompatibility.

 Most browsers have opted for a strategy where storage APIs are still available and seemingly fully functional, with the one big difference that all stored data is wiped after the browser is closed. For these browsers there are still different interpretations of what should be done with existing stored data (from a regular browsing session). Should it be available to read when in Private mode? Then there are some browsers, most notably old versions of Safari, that have opted for a solution where storage is available, but is empty and has a quota of 0 bytes assigned, effectively making it impossible to write data to it.

 Developers should be aware of these different implementations and take them into account when developing websites depending on Web Storage APIs. For more information please have a look at [this WHATWG blog post](https://blog.whatwg.org/this-week-in-html-5-episode-30) that specifically deals with this topic.



See also
--------


* [Using the Web Storage API](web_storage_api/using_the_web_storage_api)
* [Browser storage quotas and eviction criteria](storage_api/storage_quotas_and_eviction_criteria)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API>

Web Workers API
===============


**Web Workers** makes it possible to run a script operation in a background thread separate from the main execution thread of a web application. The advantage of this is that laborious processing can be performed in a separate thread, allowing the main (usually the UI) thread to run without being blocked/slowed down.


Web Workers concepts and usage
------------------------------



A worker is an object created using a constructor (e.g. [`Worker()`](worker/worker)) that runs a named JavaScript file — this file contains the code that will run in the worker thread.

 In addition to the standard [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript) set of functions (such as [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String), [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array), [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object), [`JSON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON), etc.), you can run almost any code you like inside a worker thread. There are some exceptions: for example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the [`window`](window) object. For information about the code that you *can* run see [worker global context and functions](#worker_global_contexts_and_functions), and [supported web APIs](#supported_web_apis) below.

 Data is sent between workers and the main thread via a system of messages — both sides send their messages using the `postMessage()` method, and respond to messages via the `onmessage` event handler (the message is contained within the [`message`](worker/message_event) event's `data` property). The data is copied rather than shared.

 Workers may in turn spawn new workers, as long as those workers are hosted within the same [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin) as the parent page. In addition, workers may use [`XMLHttpRequest`](xmlhttprequest) for network I/O, with the exception that the `responseXML` and `channel` attributes on `XMLHttpRequest` always return `null`.



### Worker types



There are a number of different types of workers:

 * Dedicated workers are workers that are utilized by a single script. This context is represented by a [`DedicatedWorkerGlobalScope`](dedicatedworkerglobalscope) object.
* [`Shared workers`](sharedworker) are workers that can be utilized by multiple scripts running in different windows, IFrames, etc., as long as they are in the same domain as the worker. They are a little more complex than dedicated workers — scripts must communicate via an active port.
* [Service Workers](service_worker_api) essentially act as proxy servers that sit between web applications, the browser, and the network (when available). They are intended, among other things, to enable the creation of effective offline experiences, intercept network requests and take appropriate action based on whether the network is available, and update assets residing on the server. They will also allow access to push notifications and background sync APIs.

  **Note:** As per the [Web workers Spec](https://html.spec.whatwg.org/multipage/workers.html#runtime-script-errors-2), worker error events should not bubble (see [Firefox bug 1188141](https://bugzil.la/1188141). This has been implemented in Firefox 42.

 

### Worker global contexts and functions



Workers run in a different global context than the current [`window`](window)! While [`Window`](window) is not directly available to workers, many of the same methods are defined in a shared mixin (`WindowOrWorkerGlobalScope`), and made available to workers through their own [`WorkerGlobalScope`](workerglobalscope)-derived contexts:

 * [`DedicatedWorkerGlobalScope`](dedicatedworkerglobalscope) for dedicated workers
* [`SharedWorkerGlobalScope`](sharedworkerglobalscope) for shared workers
* [`ServiceWorkerGlobalScope`](serviceworkerglobalscope) for [service workers](service_worker_api)

 Some of the functions (a subset) that are common to all workers and to the main thread (from `WindowOrWorkerGlobalScope`) are:

 * [`atob()`](atob)
* [`btoa()`](btoa)
* [`clearInterval()`](clearinterval)
* [`clearTimeout()`](cleartimeout)
* [`dump()`](window/dump)  Non-standard
* [`setInterval()`](setinterval)
* [`setTimeout()`](settimeout)

 The following functions are **only** available to workers:

 * [`WorkerGlobalScope.importScripts()`](workerglobalscope/importscripts) (all workers),
* [`DedicatedWorkerGlobalScope.postMessage`](dedicatedworkerglobalscope/postmessage) (dedicated workers only).



### Supported Web APIs



 **Note:** If a listed API is supported by a platform in a particular version, then it can generally be assumed to be available in web workers. You can also test support for a particular object/function using the site: <https://worker-playground.glitch.me/>

  The following Web APIs are available to workers:

 * [`Barcode Detection API`](barcode_detection_api)
* [`Broadcast Channel API`](broadcast_channel_api)
* [`Cache API`](cache)
* [`Channel Messaging API`](channel_messaging_api)
* [`Console API`](console_api)
* [Web Crypto API](web_crypto_api) (e.g. [`Crypto`](crypto))
* [CSS Font Loading API](css_font_loading_api)
* [`CustomEvent`](customevent)
* [`Encoding API`](encoding_api) (e.g. [`TextEncoder`](textencoder), [`TextDecoder`](textdecoder))
* [`Fetch API`](fetch_api)
* [`FileReader`](filereader)
* [`FileReaderSync`](filereadersync) (only works in workers!)
* [`FormData`](formdata)
* [`ImageData`](imagedata)
* [`IndexedDB`](indexeddb_api)
* [Network Information API](network_information_api)
* [`Notifications API`](notifications_api)
* [`Performance API`](performance_api), including:
	+ [`Performance`](performance)
	+ [`PerformanceEntry`](performanceentry)
	+ [`PerformanceMeasure`](performancemeasure)
	+ [`PerformanceMark`](performancemark)
	+ [`PerformanceObserver`](performanceobserver)
	+ [`PerformanceResourceTiming`](performanceresourcetiming)
* [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
* [Server-sent events](server-sent_events)
* [`ServiceWorkerRegistration`](serviceworkerregistration)
* [`URL API`](url_api) (e.g. [`URL`](url))
* [WebGL](webgl_api) with [`OffscreenCanvas`](offscreencanvas)
* [`WebSocket`](websocket)
* [`XMLHttpRequest`](xmlhttprequest)

 Workers can also spawn other workers, so these APIs are also available:

 * [`Worker`](worker)
* [`WorkerGlobalScope`](workerglobalscope)
* [`WorkerLocation`](workerlocation)
* [`WorkerNavigator`](workernavigator)



Web Worker interfaces
---------------------


 [`Worker`](worker)  Represents a running worker thread, allowing you to pass messages to the running worker code.

  [`WorkerLocation`](workerlocation)  Defines the absolute location of the script executed by the [`Worker`](worker).

  [`SharedWorker`](sharedworker)  Represents a specific kind of worker that can be accessed from several [browsing contexts](https://developer.mozilla.org/en-US/docs/Glossary/Browsing_context) (i.e. windows, tabs, or iframes) or even other workers.

  [`WorkerGlobalScope`](workerglobalscope)  Represents the generic scope of any worker (doing the same job as [`Window`](window) does for normal web content). Different types of worker have scope objects that inherit from this interface and add more specific features.

  [`DedicatedWorkerGlobalScope`](dedicatedworkerglobalscope)  Represents the scope of a dedicated worker, inheriting from [`WorkerGlobalScope`](workerglobalscope) and adding some dedicated features.

  [`SharedWorkerGlobalScope`](sharedworkerglobalscope)  Represents the scope of a shared worker, inheriting from [`WorkerGlobalScope`](workerglobalscope) and adding some dedicated features.

  [`WorkerNavigator`](workernavigator)  Represents the identity and state of the user agent (the client).

  
Examples
--------



We have created a couple of demos to show web worker usage:

 * [Basic dedicated worker example](https://github.com/mdn/dom-examples/tree/main/web-workers/simple-web-worker) ([run dedicated worker](https://mdn.github.io/dom-examples/web-workers/simple-web-worker/)).
* [Basic shared worker example](https://github.com/mdn/dom-examples/tree/main/web-workers/simple-shared-worker) ([run shared worker](https://mdn.github.io/dom-examples/web-workers/simple-shared-worker/)).
* [OffscreenCanvas worker example](https://github.com/mdn/dom-examples/tree/main/web-workers/offscreen-canvas-worker) ([run OffscreenCanvas worker](https://mdn.github.io/dom-examples/web-workers/offscreen-canvas-worker/)).

 You can find out more information on how these demos work in [Using Web Workers](web_workers_api/using_web_workers).



Specifications
--------------




| Specification |
| --- |
| [HTML Standard # workers](https://html.spec.whatwg.org/multipage/workers.html#workers) |


See also
--------


* [Using Web Workers](web_workers_api/using_web_workers)
* [`Worker`](worker) interface
* [`SharedWorker`](sharedworker) interface
* [Service Worker API](service_worker_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API>

WebCodecs API
=============


 The **WebCodecs API** gives web developers low-level access to the individual frames of a video stream and chunks of audio. It is useful for web applications that require full control over the way media is processed. For example, video or audio editors, and video conferencing. 


Concepts and Usage
------------------



 Many Web APIs use media codecs internally. For example, the [`Web Audio API`](web_audio_api), and the [`WebRTC API`](webrtc_api). However these APIs do not allow developers to work with individual frames of a video stream and unmixed chunks of encoded audio or video. 

  Web developers have typically used WebAssembly in order to get around this limitation, and to work with media codecs in the browser. However, this requires additional bandwidth to download codecs that already exist in the browser, reducing performance and power efficiency, and adding additional development overhead. 

  The WebCodecs API provides access to codecs that are already in the browser. It gives access to raw video frames, chunks of audio data, image decoders, audio and video encoders and decoders. 



### Processing Model



 The WebCodecs API uses an asynchronous [processing model](https://w3c.github.io/webcodecs/#codec-processing-model-section). Each instance of an encoder or decoder maintains an internal, independent processing queue. When queueing a substantial amount of work, it's important to keep this model in mind. 

  Methods named `configure()`, `encode()`, `decode()`, and `flush()` operate asynchronously by appending control messages to the end the queue, while methods named `reset()` and `close()` synchronously abort all pending work and purge the processing queue. After `reset()`, more work may be queued following a call to `configure()`, but `close()` is a permanent operation. 

  Methods named `flush()` can be used to wait for the completion of all work that was pending at the time `flush()` was called. However, it should generally only be called once all desired work is queued. It is not intended to force progress at regular intervals. Calling it unnecessarily will affect encoder quality and cause decoders to require the next input to be a key frame. 



### Demuxing


 There is currently no API for demuxing media containers. Developers working with containerized media will need to implement their own or use third party libraries. E.g., [MP4Box.js](https://github.com/gpac/mp4box.js/) or [jswebm](https://github.com/jscodec/jswebm) can be used to demux audio and video data into [`EncodedAudioChunk`](encodedaudiochunk) and [`EncodedVideoChunk`](encodedvideochunk) objects respectively. 


Interfaces
----------


 [`AudioDecoder`](audiodecoder)  Decodes [`EncodedAudioChunk`](encodedaudiochunk) objects.

  [`VideoDecoder`](videodecoder)  Decodes [`EncodedVideoChunk`](encodedvideochunk) objects.

  [`AudioEncoder`](audioencoder)  Encodes [`AudioData`](audiodata) objects.

  [`VideoEncoder`](videoencoder)  Encodes [`VideoFrame`](videoframe) objects.

  [`EncodedAudioChunk`](encodedaudiochunk)  Represents codec-specific encoded audio bytes.

  [`EncodedVideoChunk`](encodedvideochunk)  Represents codec-specific encoded video bytes.

  [`AudioData`](audiodata)  Represents unencoded audio data.

  [`VideoFrame`](videoframe)  Represents a frame of unencoded video data.

  [`VideoColorSpace`](videocolorspace)  Represents the color space of a video frame.

  [`ImageDecoder`](imagedecoder)  Unpacks and decodes image data, giving access to the sequence of frames in an animated image.

  [`ImageTrackList`](imagetracklist)  Represents the list of tracks available in the image.

  [`ImageTrack`](imagetrack)  Represents an individual image track.

  
Examples
--------



 In the following example, frames are returned from a [`MediaStreamTrackProcessor`](mediastreamtrackprocessor), then encoded. See the full example and read more about it in the article [Video processing with WebCodecs](https://web.dev/webcodecs/). 

 
```
let frame_counter = 0;
const track = stream.getVideoTracks()[0];
const media_processor = new MediaStreamTrackProcessor(track);
const reader = media_processor.readable.getReader();
while (true) {
  const result = await reader.read();
  if (result.done) break;
  let frame = result.value;
  if (encoder.encodeQueueSize > 2) {
    // Too many frames in flight, encoder is overwhelmed
    // let's drop this frame.
    frame.close();
  } else {
    frame_counter++;
    const insert_keyframe = frame_counter % 150 === 0;
    encoder.encode(frame, { keyFrame: insert_keyframe });
    frame.close();
  }
}

```


See also
--------


* [Video processing with WebCodecs](https://web.dev/webcodecs/)
* [WebCodecs API Samples](https://w3c.github.io/webcodecs/samples/)
* [Real-Time Video Processing with WebCodecs and Streams: Processing Pipelines](https://webrtchacks.com/real-time-video-processing-with-webcodecs-and-streams-processing-pipelines-part-1/)
* [Video Frame Processing on the Web – WebAssembly, WebGPU, WebGL, WebCodecs, WebNN, and WebTransport](https://webrtchacks.com/video-frame-processing-on-the-web-webassembly-webgpu-webgl-webcodecs-webnn-and-webtransport/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/WebCodecs_API>

WebGL: 2D and 3D graphics for the web
=====================================



**WebGL** (Web Graphics Library) is a JavaScript API for rendering high-performance interactive 3D and 2D graphics within any compatible web browser without the use of plug-ins. WebGL does so by introducing an API that closely conforms to OpenGL ES 2.0 that can be used in HTML [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) elements. This conformance makes it possible for the API to take advantage of hardware graphics acceleration provided by the user's device.

 Support for WebGL is present in all modern browsers (see the [compatibility tables](#browser-compatibility) below); however, the user's device must also have hardware that supports these features.

 The [WebGL 2](#webgl_2) API introduces support for much of the OpenGL ES 3.0 feature set; it's provided through the [`WebGL2RenderingContext`](webgl2renderingcontext) interface.

 The [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element is also used by the [Canvas API](canvas_api) to do 2D graphics on web pages.



Reference
---------


### Standard interfaces


* [`WebGLRenderingContext`](webglrenderingcontext)
* [`WebGL2RenderingContext`](webgl2renderingcontext)
* [`WebGLActiveInfo`](webglactiveinfo)
* [`WebGLBuffer`](webglbuffer)
* [`WebGLContextEvent`](webglcontextevent)
* [`WebGLFramebuffer`](webglframebuffer)
* [`WebGLProgram`](webglprogram)
* [`WebGLQuery`](webglquery)
* [`WebGLRenderbuffer`](webglrenderbuffer)
* [`WebGLSampler`](webglsampler)
* [`WebGLShader`](webglshader)
* [`WebGLShaderPrecisionFormat`](webglshaderprecisionformat)
* [`WebGLSync`](webglsync)
* [`WebGLTexture`](webgltexture)
* [`WebGLTransformFeedback`](webgltransformfeedback)
* [`WebGLUniformLocation`](webgluniformlocation)
* [`WebGLVertexArrayObject`](webglvertexarrayobject)

### Extensions


* [`ANGLE_instanced_arrays`](angle_instanced_arrays)
* [`EXT_blend_minmax`](ext_blend_minmax)
* [`EXT_color_buffer_float`](ext_color_buffer_float)
* [`EXT_color_buffer_half_float`](ext_color_buffer_half_float)
* [`EXT_disjoint_timer_query`](ext_disjoint_timer_query)
* [`EXT_float_blend`](ext_float_blend)  Experimental
* [`EXT_frag_depth`](ext_frag_depth)
* [`EXT_shader_texture_lod`](ext_shader_texture_lod)
* [`EXT_sRGB`](ext_srgb)
* [`EXT_texture_compression_bptc`](ext_texture_compression_bptc)
* [`EXT_texture_compression_rgtc`](ext_texture_compression_rgtc)
* [`EXT_texture_filter_anisotropic`](ext_texture_filter_anisotropic)
* [`EXT_texture_norm16`](ext_texture_norm16)
* [`KHR_parallel_shader_compile`](khr_parallel_shader_compile)
* [`OES_draw_buffers_indexed`](oes_draw_buffers_indexed)
* [`OES_element_index_uint`](oes_element_index_uint)
* [`OES_fbo_render_mipmap`](oes_fbo_render_mipmap)
* [`OES_standard_derivatives`](oes_standard_derivatives)
* [`OES_texture_float`](oes_texture_float)
* [`OES_texture_float_linear`](oes_texture_float_linear)
* [`OES_texture_half_float`](oes_texture_half_float)
* [`OES_texture_half_float_linear`](oes_texture_half_float_linear)
* [`OES_vertex_array_object`](oes_vertex_array_object)
* [`OVR_multiview2`](ovr_multiview2)
* [`WEBGL_color_buffer_float`](webgl_color_buffer_float)
* [`WEBGL_compressed_texture_astc`](webgl_compressed_texture_astc)
* [`WEBGL_compressed_texture_etc`](webgl_compressed_texture_etc)
* [`WEBGL_compressed_texture_etc1`](webgl_compressed_texture_etc1)
* [`WEBGL_compressed_texture_pvrtc`](webgl_compressed_texture_pvrtc)
* [`WEBGL_compressed_texture_s3tc`](webgl_compressed_texture_s3tc)
* [`WEBGL_compressed_texture_s3tc_srgb`](webgl_compressed_texture_s3tc_srgb)
* [`WEBGL_debug_renderer_info`](webgl_debug_renderer_info)
* [`WEBGL_debug_shaders`](webgl_debug_shaders)
* [`WEBGL_depth_texture`](webgl_depth_texture)
* [`WEBGL_draw_buffers`](webgl_draw_buffers)
* [`WEBGL_lose_context`](webgl_lose_context)
* [`WEBGL_multi_draw`](webgl_multi_draw)

### Events


* [`webglcontextlost`](htmlcanvaselement/webglcontextlost_event)
* [`webglcontextrestored`](htmlcanvaselement/webglcontextrestored_event)
* [`webglcontextcreationerror`](htmlcanvaselement/webglcontextcreationerror_event)

### Constants and types


* [WebGL constants](webgl_api/constants)
* [WebGL types](webgl_api/types)

### WebGL 2



WebGL 2 is a major update to WebGL which is provided through the [`WebGL2RenderingContext`](webgl2renderingcontext) interface. It is based on OpenGL ES 3.0 and new features include:

 * [3D textures](webgl2renderingcontext/teximage3d),
* [Sampler objects](webglsampler),
* [Uniform Buffer objects](webgl2renderingcontext#uniform_buffer_objects),
* [Sync objects](webglsync),
* [Query objects](webglquery),
* [Transform Feedback objects](webgltransformfeedback),
* Promoted extensions that are now core to WebGL 2: [Vertex Array objects](webglvertexarrayobject), [instancing](webgl2renderingcontext/drawarraysinstanced), [multiple render targets](webgl2renderingcontext/drawbuffers), [fragment depth](ext_frag_depth).

 See also the blog post ["WebGL 2 lands in Firefox"](https://hacks.mozilla.org/2017/01/webgl-2-lands-in-firefox/) and [webglsamples.org/WebGL2Samples](https://webglsamples.org/WebGL2Samples/) for a few demos.



Guides and tutorials
--------------------


Below, you'll find an assortment of guides to help you learn WebGL concepts and tutorials that offer step-by-step lessons and examples.


### Guides


 [Data in WebGL](webgl_api/data)  A guide to variables, buffers, and other types of data used when writing WebGL code.

  [WebGL best practices](webgl_api/webgl_best_practices)  Tips and suggestions to help you improve the quality, performance, and reliability of your WebGL content.

  [Using extensions](webgl_api/using_extensions)  A guide to using WebGL extensions.

  
### Tutorials


 [WebGL tutorial](webgl_api/tutorial)  A beginner's guide to WebGL core concepts. A good place to start if you don't have previous WebGL experience.

  
### Examples


 [A basic 2D WebGL animation example](webgl_api/basic_2d_animation_example)  This example demonstrates the simple animation of a one-color shape. Topics examined are adapting to aspect ratio differences, a function to build shader programs from sets of multiple shaders, and the basics of drawing in WebGL.

  [WebGL by example](webgl_api/by_example)  A series of live samples with short explanations that showcase WebGL concepts and capabilities. The examples are sorted according to topic and level of difficulty, covering the WebGL rendering context, shader programming, textures, geometry, user interaction, and more.

  
### Advanced tutorials


 [WebGL model view projection](webgl_api/webgl_model_view_projection)  A detailed explanation of the three core matrices that are typically used to represent a 3D object view: the model, view and projection matrices.

  [Matrix math for the web](webgl_api/matrix_math_for_the_web)  A useful guide to how 3D transform matrices work, and can be used on the web — both for WebGL calculations and in CSS transforms.

  
Resources
---------


* [Khronos WebGL site](https://www.khronos.org/webgl/) The main web site for WebGL at the Khronos Group.
* [WebGL Fundamentals](https://web.dev/webgl-fundamentals/) A basic tutorial with fundamentals of WebGL.
* [Raw WebGL: An introduction to WebGL](https://www.youtube.com/embed/H4c8t6myAWU/?feature=player_detailpage) A talk by Nick Desaulniers that introduces the basics of WebGL.
* [WebGL playground](http://webglplayground.net) An online tool for creating and sharing WebGL projects. Good for quick prototyping and experimenting.
* [WebGL Academy](http://www.webglacademy.com) An HTML/JavaScript editor with tutorials to learn basics of webgl programming.
* [WebGL Stats](https://webglreport.com/) A site with statistics about WebGL capabilities in browsers on different platforms.

### Libraries


* [three.js](https://threejs.org/) is an open-source, fully featured 3D WebGL library.
* [Babylon.js](https://www.babylonjs.com) is a powerful, simple, and open game and 3D rendering engine packed into a friendly JavaScript framework.
* [Pixi.js](https://pixijs.com/) is a fast, open-source 2D WebGL renderer.
* [Phaser](https://phaser.io/) is a fast, free and fun open source framework for Canvas and WebGL powered browser games.
* [PlayCanvas](https://playcanvas.com/) is an open-source game engine.
* [glMatrix](https://github.com/toji/gl-matrix) is a JavaScript matrix and vector library for high-performance WebGL apps.
* [twgl](https://twgljs.org) is a library for making webgl less verbose.
* [RedGL](https://github.com/redcamel/RedGL2) is an open-source 3D WebGL library.
* [vtk.js](https://kitware.github.io/vtk-js/) is a JavaScript library for scientific visualization in your browser.
* [webgl-lint](https://greggman.github.io/webgl-lint/) will help find errors in your WebGL code and provide useful info

Specifications
--------------




| Specification |
| --- |
| [WebGL Specification # 5.14](https://registry.khronos.org/webgl/specs/latest/1.0/#5.14) |
| [WebGL 2.0 Specification # 3.7](https://registry.khronos.org/webgl/specs/latest/2.0/#3.7) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `WebGL_API` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `activeTexture` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `attachShader` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `beginQuery` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `beginTransformFeedback` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `bindAttribLocation` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `bindBuffer` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `bindBufferBase` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `bindBufferRange` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `bindFramebuffer` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `bindRenderbuffer` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `bindSampler` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `bindTexture` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `bindTransformFeedback` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `bindVertexArray` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `blendColor` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `blendEquation` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `blendEquationSeparate` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `blendFunc` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `blendFuncSeparate` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `blitFramebuffer` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `bufferData` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `bufferSubData` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `canvas` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `checkFramebufferStatus` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `clear` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `clearBufferfi` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `clearBufferfv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `clearBufferiv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `clearBufferuiv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `clearColor` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `clearDepth` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `clearStencil` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `clientWaitSync` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `colorMask` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `commit` | No | No | 105 | No | No | No | No | No | 105 | No | No | No |
| `compileShader` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `compressedTexImage2D` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `compressedTexImage3D` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `compressedTexSubImage2D` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `compressedTexSubImage3D` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `copyBufferSubData` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `copyTexImage2D` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `copyTexSubImage2D` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `copyTexSubImage3D` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `createBuffer` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `createFramebuffer` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `createProgram` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `createQuery` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `createRenderbuffer` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `createSampler` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `createShader` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `createTexture` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `createTransformFeedback` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `createVertexArray` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `cullFace` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `deleteBuffer` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `deleteFramebuffer` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `deleteProgram` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `deleteQuery` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `deleteRenderbuffer` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `deleteSampler` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `deleteShader` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `deleteSync` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `deleteTexture` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `deleteTransformFeedback` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `deleteVertexArray` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `depthFunc` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `depthMask` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `depthRange` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `detachShader` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `disable` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `disableVertexAttribArray` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `drawArrays` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `drawArraysInstanced` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `drawBuffers` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `drawElements` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `drawElementsInstanced` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `drawRangeElements` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `drawingBufferColorSpace` | 104 | 104 | No | No | 90 | 16.4 | 104 | 104 | No | 71 | 16.4 | 20.0 |
| `drawingBufferHeight` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `drawingBufferWidth` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `enable` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `enableVertexAttribArray` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `endQuery` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `endTransformFeedback` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `fenceSync` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `finish` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `flush` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `framebufferRenderbuffer` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `framebufferTexture2D` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `framebufferTextureLayer` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `frontFace` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `generateMipmap` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getActiveAttrib` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getActiveUniform` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getActiveUniformBlockName` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getActiveUniformBlockParameter` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getActiveUniforms` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getAttachedShaders` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getAttribLocation` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getBufferParameter` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getBufferSubData` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getContextAttributes` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getError` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getExtension` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getFragDataLocation` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getFramebufferAttachmentParameter` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getIndexedParameter` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getInternalformatParameter` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getParameter` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getProgramInfoLog` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getProgramParameter` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getQuery` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getQueryParameter` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getRenderbufferParameter` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getSamplerParameter` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getShaderInfoLog` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getShaderParameter` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getShaderPrecisionFormat` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getShaderSource` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getSupportedExtensions` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getSyncParameter` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getTexParameter` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getTransformFeedbackVarying` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getUniform` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getUniformBlockIndex` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getUniformIndices` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getUniformLocation` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getVertexAttrib` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `getVertexAttribOffset` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `hint` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `invalidateFramebuffer` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `invalidateSubFramebuffer` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `isBuffer` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `isContextLost` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `isEnabled` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `isFramebuffer` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `isProgram` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `isQuery` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `isRenderbuffer` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `isSampler` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `isShader` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `isSync` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `isTexture` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `isTransformFeedback` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `isVertexArray` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `lineWidth` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `linkProgram` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `makeXRCompatible` | 79 | 79 | No | No | 66 | No | No | 79 | No | 57 | No | 11.2 |
| `pauseTransformFeedback` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `pixelStorei` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `polygonOffset` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `readBuffer` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `readPixels` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `renderbufferStorage` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `renderbufferStorageMultisample` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `resumeTransformFeedback` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `sampleCoverage` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `samplerParameterf` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `samplerParameteri` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `scissor` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `shaderSource` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `stencilFunc` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `stencilFuncSeparate` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `stencilMask` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `stencilMaskSeparate` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `stencilOp` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `stencilOpSeparate` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `texImage2D` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `texImage3D` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `texParameterf` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `texParameteri` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `texStorage2D` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `texStorage3D` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `texSubImage2D` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `texSubImage3D` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `transformFeedbackVaryings` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform1f` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform1fv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform1i` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform1iv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform1ui` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform1uiv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform2f` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform2fv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform2i` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform2iv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform2ui` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform2uiv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform3f` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform3fv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform3i` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform3iv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform3ui` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform3uiv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform4f` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform4fv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform4i` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform4iv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform4ui` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniform4uiv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniformBlockBinding` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniformMatrix2fv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniformMatrix2x3fv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniformMatrix2x4fv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniformMatrix3fv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniformMatrix3x2fv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniformMatrix3x4fv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniformMatrix4fv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniformMatrix4x2fv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `uniformMatrix4x3fv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `unpackColorSpace` | 104 | 104 | No | No | 90 | No | 104 | 104 | No | 71 | No | 20.0 |
| `useProgram` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `validateProgram` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `vertexAttrib1f` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `vertexAttrib1fv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `vertexAttrib2f` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `vertexAttrib2fv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `vertexAttrib3f` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `vertexAttrib3fv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `vertexAttrib4f` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `vertexAttrib4fv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `vertexAttribDivisor` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `vertexAttribI4i` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `vertexAttribI4iv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `vertexAttribI4ui` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `vertexAttribI4uiv` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `vertexAttribIPointer` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `vertexAttribPointer` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `viewport` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |
| `waitSync` | 56 | 79 | 51 | No | 43 | 15 | 58 | 58 | 51 | 43 | 15 | 7.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `WebGL_API` | 9 | 12To access the WebGL context, use `experimental-webgl` rather than the standard `webgl` identifier. | 4 | 11To access the WebGL context, use `experimental-webgl` rather than the standard `webgl` identifier. | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `activeTexture` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `attachShader` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `bindAttribLocation` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `bindBuffer` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `bindFramebuffer` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `bindRenderbuffer` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `bindTexture` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `blendColor` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `blendEquation` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `blendEquationSeparate` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `blendFunc` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `blendFuncSeparate` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `bufferData` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `bufferSubData` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `canvas` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `checkFramebufferStatus` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `clear` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `clearColor` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `clearDepth` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `clearStencil` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `colorMask` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `commit` | No | No | 105 | No | No | No | No | No | 105 | No | No | No |
| `compileShader` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `compressedTexImage2D` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `compressedTexSubImage2D` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `copyTexImage2D` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `copyTexSubImage2D` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `createBuffer` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `createFramebuffer` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `createProgram` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `createRenderbuffer` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `createShader` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `createTexture` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `cullFace` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `deleteBuffer` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `deleteFramebuffer` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `deleteProgram` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `deleteRenderbuffer` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `deleteShader` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `deleteTexture` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `depthFunc` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `depthMask` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `depthRange` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `detachShader` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `disable` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `disableVertexAttribArray` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `drawArrays` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `drawElements` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `drawingBufferColorSpace` | 104 | 104 | No | No | 90 | 16.4 | 104 | 104 | No | 71 | 16.4 | 20.0 |
| `drawingBufferHeight` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `drawingBufferWidth` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `enable` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `enableVertexAttribArray` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `finish` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `flush` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `framebufferRenderbuffer` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `framebufferTexture2D` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `frontFace` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `generateMipmap` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `getActiveAttrib` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `getActiveUniform` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `getAttachedShaders` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `getAttribLocation` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `getBufferParameter` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `getContextAttributes` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `getError` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `getExtension` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `getFramebufferAttachmentParameter` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `getParameter` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `getProgramInfoLog` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `getProgramParameter` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `getRenderbufferParameter` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `getShaderInfoLog` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `getShaderParameter` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `getShaderPrecisionFormat` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `getShaderSource` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `getSupportedExtensions` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `getTexParameter` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `getUniform` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `getUniformLocation` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `getVertexAttrib` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `getVertexAttribOffset` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `hint` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `isBuffer` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `isContextLost` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `isEnabled` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `isFramebuffer` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `isProgram` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `isRenderbuffer` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `isShader` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `isTexture` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `lineWidth` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `linkProgram` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `makeXRCompatible` | 79 | 79 | No | No | No | No | No | 79 | No | No | No | 11.2 |
| `pixelStorei` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `polygonOffset` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `readPixels` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `renderbufferStorage` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `sampleCoverage` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `scissor` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `shaderSource` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `stencilFunc` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `stencilFuncSeparate` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `stencilMask` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `stencilMaskSeparate` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `stencilOp` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `stencilOpSeparate` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `texImage2D` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `texParameterf` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `texParameteri` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `texSubImage2D` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `uniform1f` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `uniform1fv` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `uniform1i` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `uniform1iv` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `uniform2f` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `uniform2fv` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `uniform2i` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `uniform2iv` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `uniform3f` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `uniform3fv` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `uniform3i` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `uniform3iv` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `uniform4f` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `uniform4fv` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `uniform4i` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `uniform4iv` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `uniformMatrix2fv` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `uniformMatrix3fv` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `uniformMatrix4fv` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `unpackColorSpace` | 104 | 104 | No | No | 90 | No | 104 | 104 | No | 71 | No | 20.0 |
| `useProgram` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `validateProgram` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `vertexAttrib1f` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `vertexAttrib1fv` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `vertexAttrib2f` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `vertexAttrib2fv` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `vertexAttrib3f` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `vertexAttrib3fv` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `vertexAttrib4f` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `vertexAttrib4fv` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `vertexAttribPointer` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `viewport` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4.3 | 25 | 4 | 12 | 8 | 1.5 |
| `worker_support` | No | No | 105 | No | No | No | No | No | 105 | No | No | No |


### api.WebGLRenderingContext


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.WebGL2RenderingContext


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### Compatibility notes


In addition to the browser, the GPU itself also needs to support the feature. So, for example, S3 Texture Compression (S3TC) is only available on Tegra-based tablets. Most browsers make the WebGL context available through the `webgl` context name, but older ones need `experimental-webgl` as well. In addition, the upcoming [WebGL 2](webgl2renderingcontext) is fully backwards-compatible and will have the context name `webgl2`.


### Gecko notes



#### WebGL debugging and testing

 Firefox provides two preferences available which let you control the capabilities of WebGL for testing purposes:

  `webgl.min_capability_mode`  A Boolean property that, when `true`, enables a minimum capability mode. When in this mode, WebGL is configured to only support the bare minimum feature set and capabilities required by the WebGL specification. This lets you ensure that your WebGL code will work on any device or browser, regardless of their capabilities. This is `false` by default.

  `webgl.disable_extensions`  A Boolean property that, when `true`, disables all WebGL extensions. This is `false` by default.

  

See also
--------


* [Canvas API](canvas_api)
* [Compatibility info about WebGL extensions](webglrenderingcontext/getsupportedextensions#browser_compatibility)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API>

WebHID API
==========



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 A Human Interface Device (HID) is a type of device that takes input from or provides output to humans. It also refers to the HID protocol, a standard for bi-directional communication between a host and a device that is designed to simplify the installation procedure. The HID protocol was originally developed for USB devices but has since been implemented over many other protocols, including Bluetooth.



Interfaces
----------


 [`HID`](hid)  Provides methods for connecting to HID devices, listing attached HID devices and event handlers for connected HID devices.

  [`HIDDevice`](hiddevice)  Represents an HID device. It's possible for a single physical device to be represented by multiple `HIDDevice` objects.

  [`HIDInputReportEvent`](hidinputreportevent)  Passed to [`HIDDevice.inputreport_event`](hiddevice/inputreport_event) when an input report is received from any associated HID device.

  [`HIDConnectionEvent`](hidconnectionevent)  Passed to [`HID.onconnect`](hid/connect_event) and [`HID.ondisconnect`](hid/disconnect_event) when a device is connected or disconnected.

  
Examples
--------



You can connect to a device with the [`requestDevice()`](hid/requestdevice) method. In this case, we select from all the available devices.

 
```
const device = await navigator.hid.requestDevice({ filters: [] });
// A popup titled `... wants to connect to a HID Device` with `Cancel` and `Connect` buttons will show up with a device list to select from.
// Select one and click on `Connect` button. Then the device will be an array with the selected device in it.

```
 We can retrieve all the devices the website has been granted access to previously and log the device names to the console.

 
```
let devices = await navigator.hid.getDevices();
devices.forEach((device) => {
  console.log(`HID: ${device.productName}`);
});

```
 We can register event listeners for disconnection of any HID devices.

 
```
navigator.hid.addEventListener("disconnect", (event) => {
  console.log(`HID disconnected: ${event.device.productName}`);
  console.dir(event);
});
// For example, when my connected keyboard gets disconnected, the log in the console will show:
// HID disconnected: USB Keyboard
// {
// bubbles: false
// cancelBubble: false
// cancelable: false
// composed: false
// currentTarget: HID {onconnect: null, ondisconnect: null}
// defaultPrevented: false
// device: HIDDevice {oninputreport: null, opened: false, vendorId: 6700, productId: 11555, productName: "USB Keyboard", …}
// eventPhase: 0
// isTrusted: true
// path: []
// returnValue: true
// srcElement: HID {onconnect: null, ondisconnect: null}
// target: HID {onconnect: null, ondisconnect: null}
// timeStamp: 18176.600000023842
// type: "disconnect"
// }

// The event above is an instance of the HIDConnectionEvent interface.

```


Specifications
--------------




| Specification |
| --- |
| [WebHID API # dom-hid](https://wicg.github.io/webhid/#dom-hid) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `WebHID_API` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `connect_event` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `disconnect_event` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `getDevices` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `requestDevice` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/WebHID_API>

WebOTP API
==========



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The **WebOTP API** provides a method for verifying that a phone number belongs to the user, by generating a one-time password on receipt of a specially formatted SMS message.



Concepts and Usage
------------------



Phone numbers are often used as a way to identify the user of an app, and to verify that the number belongs to the user, SMS is frequently deployed. A typical scenario would involve a message being sent to the user with a one-time password. They would then need to copy and paste that password into a form to verify that the user owns the number.

 The WebOTP API removes friction from this process by allowing the password to be received by the app and verified automatically, with no need to copy and paste any codes.



Interfaces
----------


 [`OTPCredential`](otpcredential)  Extends [`Credential`](credential) and contains the attributes that are returned when a new one-time password is created.

  
Examples
--------



In this example, when an SMS message arrives, and the user grants permission, an [`OTPCredential`](otpcredential) object is returned with a one-time password. This password is then prefilled into the form field, and the form submitted.

 [Try the demo using a phone here](https://glitch.com/edit/#!/web-otp?path=views%2Findex.html%3A55%3A8).

 
```
<input type="text" autocomplete="one-time-code" inputmode="numeric" />

```
 
```
if ("OTPCredential" in window) {
  window.addEventListener("DOMContentLoaded", (e) => {
    const input = document.querySelector('input[autocomplete="one-time-code"]');
    if (!input) return;
    const ac = new AbortController();
    const form = input.closest("form");
    if (form) {
      form.addEventListener("submit", (e) => {
        ac.abort();
      });
    }
    navigator.credentials
      .get({
        otp: { transport: ["sms"] },
        signal: ac.signal,
      })
      .then((otp) => {
        input.value = otp.code;
        if (form) form.submit();
      })
      .catch((err) => {
        console.error(err);
      });
  });
}

```


Specifications
--------------




| Specification |
| --- |
| [WebOTP API](https://wicg.github.io/web-otp/)  |


See also
--------


* [Verify phone numbers on the web with WebOTP](https://web.dev/web-otp/)
* [Fill OTP forms within cross-origin iframes with WebOTP API](https://web.dev/web-otp-iframe/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/WebOTP_API>

WebRTC API
==========



**WebRTC** (Web Real-Time Communication) is a technology that enables Web applications and sites to capture and optionally stream audio and/or video media, as well as to exchange arbitrary data between browsers without requiring an intermediary. The set of standards that comprise WebRTC makes it possible to share data and perform teleconferencing peer-to-peer, without requiring that the user install plug-ins or any other third-party software.

 WebRTC consists of several interrelated APIs and protocols which work together to achieve this. The documentation you'll find here will help you understand the fundamentals of WebRTC, how to set up and use both data and media connections, and more.



WebRTC concepts and usage
-------------------------



WebRTC serves multiple purposes; together with the [Media Capture and Streams API](media_capture_and_streams_api), they provide powerful multimedia capabilities to the Web, including support for audio and video conferencing, file exchange, screen sharing, identity management, and interfacing with legacy telephone systems including support for sending [DTMF](https://developer.mozilla.org/en-US/docs/Glossary/DTMF) (touch-tone dialing) signals. Connections between peers can be made without requiring any special drivers or plug-ins, and can often be made without any intermediary servers.

 Connections between two peers are represented by the [`RTCPeerConnection`](rtcpeerconnection) interface. Once a connection has been established and opened using `RTCPeerConnection`, media streams ([`MediaStream`](mediastream)s) and/or data channels ([`RTCDataChannel`](rtcdatachannel)s) can be added to the connection.

 Media streams can consist of any number of tracks of media information; tracks, which are represented by objects based on the [`MediaStreamTrack`](mediastreamtrack) interface, may contain one of a number of types of media data, including audio, video, and text (such as subtitles or even chapter names). Most streams consist of at least one audio track and likely also a video track, and can be used to send and receive both live media or stored media information (such as a streamed movie).

 You can also use the connection between two peers to exchange arbitrary binary data using the [`RTCDataChannel`](rtcdatachannel) interface. This can be used for back-channel information, metadata exchange, game status packets, file transfers, or even as a primary channel for data transfer.



### Interoperability


WebRTC is in general well supported in modern browsers, but some incompatibilities remain. The [adapter.js](https://github.com/webrtcHacks/adapter) library is a shim to insulate apps from these incompatibilities.


WebRTC reference
----------------


Because WebRTC provides interfaces that work together to accomplish a variety of tasks, we have divided up the reference by category. Please see the sidebar for an alphabetical list.


### Connection setup and management



These interfaces, dictionaries, and types are used to set up, open, and manage WebRTC connections. Included are interfaces representing peer media connections, data channels, and interfaces used when exchanging information on the capabilities of each peer in order to select the best possible configuration for a two-way media connection.

 #### Interfaces

  [`RTCPeerConnection`](rtcpeerconnection)  Represents a WebRTC connection between the local computer and a remote peer. It is used to handle efficient streaming of data between the two peers.

  [`RTCDataChannel`](rtcdatachannel)  Represents a bi-directional data channel between two peers of a connection.

  [`RTCDataChannelEvent`](rtcdatachannelevent)  Represents events that occur while attaching a [`RTCDataChannel`](rtcdatachannel) to a [`RTCPeerConnection`](rtcpeerconnection). The only event sent with this interface is [`datachannel`](rtcpeerconnection/datachannel_event).

  [`RTCSessionDescription`](rtcsessiondescription)  Represents the parameters of a session. Each `RTCSessionDescription` consists of a description [`type`](rtcsessiondescription/type) indicating which part of the offer/answer negotiation process it describes and of the [SDP](https://developer.mozilla.org/en-US/docs/Glossary/SDP) descriptor of the session.

  [`RTCStatsReport`](rtcstatsreport)  Provides information detailing statistics for a connection or for an individual track on the connection; the report can be obtained by calling [`RTCPeerConnection.getStats()`](rtcpeerconnection/getstats). Details about using WebRTC statistics can be found in [WebRTC Statistics API](webrtc_statistics_api).

  [`RTCIceCandidate`](rtcicecandidate)  Represents a candidate Interactive Connectivity Establishment ([ICE](https://developer.mozilla.org/en-US/docs/Glossary/ICE)) server for establishing an [`RTCPeerConnection`](rtcpeerconnection).

  [`RTCIceTransport`](rtcicetransport)  Represents information about an [ICE](https://developer.mozilla.org/en-US/docs/Glossary/ICE) transport.

  [`RTCPeerConnectionIceEvent`](rtcpeerconnectioniceevent)  Represents events that occur in relation to ICE candidates with the target, usually an [`RTCPeerConnection`](rtcpeerconnection). Only one event is of this type: [`icecandidate`](rtcpeerconnection/icecandidate_event).

  [`RTCRtpSender`](rtcrtpsender)  Manages the encoding and transmission of data for a [`MediaStreamTrack`](mediastreamtrack) on an [`RTCPeerConnection`](rtcpeerconnection).

  [`RTCRtpReceiver`](rtcrtpreceiver)  Manages the reception and decoding of data for a [`MediaStreamTrack`](mediastreamtrack) on an [`RTCPeerConnection`](rtcpeerconnection).

  [`RTCTrackEvent`](rtctrackevent)  The interface used to represent a [`track`](rtcpeerconnection/track_event) event, which indicates that an [`RTCRtpReceiver`](rtcrtpreceiver) object was added to the [`RTCPeerConnection`](rtcpeerconnection) object, indicating that a new incoming [`MediaStreamTrack`](mediastreamtrack) was created and added to the `RTCPeerConnection`.

  [`RTCSctpTransport`](rtcsctptransport)  Provides information which describes a Stream Control Transmission Protocol (**[SCTP](https://developer.mozilla.org/en-US/docs/Glossary/SCTP)**) transport and also provides a way to access the underlying Datagram Transport Layer Security (**[DTLS](https://developer.mozilla.org/en-US/docs/Glossary/DTLS)**) transport over which SCTP packets for all of an [`RTCPeerConnection`](rtcpeerconnection)'s data channels are sent and received.

   #### Dictionaries

  [`RTCIceServer`](rtciceserver)  Defines how to connect to a single [ICE](https://developer.mozilla.org/en-US/docs/Glossary/ICE) server (such as a [STUN](https://developer.mozilla.org/en-US/docs/Glossary/STUN) or [TURN](https://developer.mozilla.org/en-US/docs/Glossary/TURN) server).

  [`RTCRtpContributingSource`](rtcrtpcontributingsource)  Contains information about a given contributing source (CSRC) including the most recent time a packet that the source contributed was played out.

   #### Events

  [`bufferedamountlow`](rtcdatachannel/bufferedamountlow_event)  The amount of data currently buffered by the data channel—as indicated by its [`bufferedAmount`](rtcdatachannel/bufferedamount) property—has decreased to be at or below the channel's minimum buffered data size, as specified by [`bufferedAmountLowThreshold`](rtcdatachannel/bufferedamountlowthreshold).

  [`close`](rtcdatachannel/close_event)  The data channel has completed the closing process and is now in the `closed` state. Its underlying data transport is completely closed at this point. You can be notified *before* closing completes by watching for the `closing` event instead.

  [`closing`](rtcdatachannel/closing_event)  The `RTCDataChannel` has transitioned to the `closing` state, indicating that it will be closed soon. You can detect the completion of the closing process by watching for the `close` event.

  [`connectionstatechange`](rtcpeerconnection/connectionstatechange_event)  The connection's state, which can be accessed in [`connectionState`](rtcpeerconnection/connectionstate), has changed.

  [`datachannel`](rtcpeerconnection/datachannel_event)  A new [`RTCDataChannel`](rtcdatachannel) is available following the remote peer opening a new data channel. This event's type is [`RTCDataChannelEvent`](rtcdatachannelevent).

  [`error`](rtcdatachannel/error_event)  An [`RTCErrorEvent`](rtcerrorevent) indicating that an error occurred on the data channel.

  [`error`](rtcdtlstransport/error_event)  An [`RTCErrorEvent`](rtcerrorevent) indicating that an error occurred on the [`RTCDtlsTransport`](rtcdtlstransport). This error will be either `dtls-failure` or `fingerprint-failure`.

  [`gatheringstatechange`](rtcicetransport/gatheringstatechange_event)  The [`RTCIceTransport`](rtcicetransport)'s gathering state has changed.

  [`icecandidate`](rtcpeerconnection/icecandidate_event)  An [`RTCPeerConnectionIceEvent`](rtcpeerconnectioniceevent) which is sent whenever the local device has identified a new ICE candidate which needs to be added to the local peer by calling [`setLocalDescription()`](rtcpeerconnection/setlocaldescription).

  [`icecandidateerror`](rtcpeerconnection/icecandidateerror_event)  An [`RTCPeerConnectionIceErrorEvent`](rtcpeerconnectioniceerrorevent) indicating that an error has occurred while gathering ICE candidates.

  [`iceconnectionstatechange`](rtcpeerconnection/iceconnectionstatechange_event)  Sent to an [`RTCPeerConnection`](rtcpeerconnection) when its ICE connection's state—found in the [`iceconnectionstate`](rtcpeerconnection/iceconnectionstate) property—changes.

  [`icegatheringstatechange`](rtcpeerconnection/icegatheringstatechange_event)  Sent to an [`RTCPeerConnection`](rtcpeerconnection) when its ICE gathering state—found in the [`icegatheringstate`](rtcpeerconnection/icegatheringstate) property—changes.

  [`message`](rtcdatachannel/message_event)  A message has been received on the data channel. The event is of type [`MessageEvent`](messageevent).

  [`negotiationneeded`](rtcpeerconnection/negotiationneeded_event)  Informs the `RTCPeerConnection` that it needs to perform session negotiation by calling [`createOffer()`](rtcpeerconnection/createoffer) followed by [`setLocalDescription()`](rtcpeerconnection/setlocaldescription).

  [`open`](rtcdatachannel/open_event)  The underlying data transport for the `RTCDataChannel` has been successfully opened or re-opened.

  [`selectedcandidatepairchange`](rtcicetransport/selectedcandidatepairchange_event)  The currently-selected pair of ICE candidates has changed for the `RTCIceTransport` on which the event is fired.

  [`track`](rtcpeerconnection/track_event)  The `track` event, of type [`RTCTrackevent`](rtctrackevent) is sent to an [`RTCPeerConnection`](rtcpeerconnection) when a new track is added to the connection following the successful negotiation of the media's streaming.

  [`signalingstatechange`](rtcpeerconnection/signalingstatechange_event)  Sent to the peer connection when its [`signalingstate`](rtcpeerconnection/signalingstate) has changed. This happens as a result of a call to either [`setLocalDescription()`](rtcpeerconnection/setlocaldescription) or [`setRemoteDescription()`](rtcpeerconnection/setremotedescription).

  `statechange`  The state of the `RTCDtlsTransport` has changed.

  [`statechange`](rtcicetransport/statechange_event)  The state of the `RTCIceTransport` has changed.

  `statechange`  The state of the `RTCSctpTransport` has changed.

   #### Types

  [`RTCSctpTransport.state`](rtcsctptransport/state)  Indicates the state of an [`RTCSctpTransport`](rtcsctptransport) instance.

  

### Identity and security



These APIs are used to manage user identity and security, in order to authenticate the user for a connection.

  `RTCIdentityProvider`  Enables a user agent is able to request that an identity assertion be generated or validated.

  [`RTCIdentityAssertion`](rtcidentityassertion)  Represents the identity of the remote peer of the current connection. If no peer has yet been set and verified this interface returns `null`. Once set it can't be changed.

  `RTCIdentityProviderRegistrar`  Registers an identity provider (idP).

  [`RTCCertificate`](rtccertificate)  Represents a certificate that an [`RTCPeerConnection`](rtcpeerconnection) uses to authenticate.

  

### Telephony



These interfaces and events are related to interactivity with Public-Switched Telephone Networks (PTSNs). They're primarily used to send tone dialing sounds—or packets representing those tones—across the network to the remote peer.

 #### Interfaces

  [`RTCDTMFSender`](rtcdtmfsender)  Manages the encoding and transmission of Dual-Tone Multi-Frequency ([DTMF](https://developer.mozilla.org/en-US/docs/Glossary/DTMF)) signaling for an [`RTCPeerConnection`](rtcpeerconnection).

  [`RTCDTMFToneChangeEvent`](rtcdtmftonechangeevent)  Used by the [`tonechange`](rtcdtmfsender/tonechange_event) event to indicate that a DTMF tone has either begun or ended. This event does not bubble (except where otherwise stated) and is not cancelable (except where otherwise stated).

   #### Events

  [`tonechange`](rtcdtmfsender/tonechange_event)  Either a new [DTMF](https://developer.mozilla.org/en-US/docs/Glossary/DTMF) tone has begun to play over the connection, or the last tone in the `RTCDTMFSender`'s [`toneBuffer`](rtcdtmfsender/tonebuffer) has been sent and the buffer is now empty. The event's type is [`RTCDTMFToneChangeEvent`](rtcdtmftonechangeevent).

  

Guides
------


 [Introduction to WebRTC protocols](webrtc_api/protocols)  This article introduces the protocols on top of which the WebRTC API is built.

  [WebRTC connectivity](webrtc_api/connectivity)  A guide to how WebRTC connections work and how the various protocols and interfaces can be used together to build powerful communication apps.

  [Lifetime of a WebRTC session](webrtc_api/session_lifetime)  WebRTC lets you build peer-to-peer communication of arbitrary data, audio, or video—or any combination thereof—into a browser application. In this article, we'll look at the lifetime of a WebRTC session, from establishing the connection all the way through closing the connection when it's no longer needed.

  [Establishing a connection: The perfect negotiation pattern](webrtc_api/perfect_negotiation)  **Perfect negotiation** is a design pattern which is recommended for your signaling process to follow, which provides transparency in negotiation while allowing both sides to be either the offerer or the answerer, without significant coding needed to differentiate the two.

  [Signaling and two-way video calling](webrtc_api/signaling_and_video_calling)  A tutorial and example which turns a WebSocket-based chat system created for a previous example and adds support for opening video calls among participants. The chat server's WebSocket connection is used for WebRTC signaling.

  [Codecs used by WebRTC](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/WebRTC_codecs)  A guide to the codecs which WebRTC requires browsers to support as well as the optional ones supported by various popular browsers. Included is a guide to help you choose the best codecs for your needs.

  [Using WebRTC data channels](webrtc_api/using_data_channels)  This guide covers how you can use a peer connection and an associated [`RTCDataChannel`](rtcdatachannel) to exchange arbitrary data between two peers.

  [Using DTMF with WebRTC](webrtc_api/using_dtmf)  WebRTC's support for interacting with gateways that link to old-school telephone systems includes support for sending DTMF tones using the [`RTCDTMFSender`](rtcdtmfsender) interface. This guide shows how to do so.

  
Tutorials
---------


 [Improving compatibility using WebRTC adapter.js](webrtc_api#interoperability)  The WebRTC organization [provides on GitHub the WebRTC adapter](https://github.com/webrtc/adapter/) to work around compatibility issues in different browsers' WebRTC implementations. The adapter is a JavaScript shim which lets your code to be written to the specification so that it will "just work" in all browsers with WebRTC support.

  [A simple RTCDataChannel sample](webrtc_api/simple_rtcdatachannel_sample)  The [`RTCDataChannel`](rtcdatachannel) interface is a feature which lets you open a channel between two peers over which you may send and receive arbitrary data. The API is intentionally similar to the [WebSocket API](websockets_api), so that the same programming model can be used for each.

  [Building an internet connected phone with Peer.js](webrtc_api/build_a_phone_with_peerjs)  This tutorial is a step-by-step guide on how to build a phone using Peer.js

  
Specifications
--------------




| Specification |
| --- |
| [WebRTC: Real-Time Communication in Browsers](https://w3c.github.io/webrtc-pc/)  |
| [Media Capture and Streams](https://w3c.github.io/mediacapture-main/)  |
| [Media Capture from DOM Elements](https://w3c.github.io/mediacapture-fromelement/)  |


### WebRTC-proper protocols


* [Application Layer Protocol Negotiation for Web Real-Time Communications](https://datatracker.ietf.org/doc/rfc8833/)
* [WebRTC Audio Codec and Processing Requirements](https://datatracker.ietf.org/doc/rfc7874/)
* [RTCWeb Data Channels](https://datatracker.ietf.org/doc/rfc8831/)
* [RTCWeb Data Channel Protocol](https://datatracker.ietf.org/doc/rfc8832/)
* [Web Real-Time Communication (WebRTC): Media Transport and Use of RTP](https://datatracker.ietf.org/doc/rfc8834/)
* [WebRTC Security Architecture](https://datatracker.ietf.org/doc/rfc8827/)
* [Transports for RTCWEB](https://datatracker.ietf.org/doc/rfc8835/)

### Related supporting protocols


* [Interactive Connectivity Establishment (ICE): A Protocol for Network Address Translator (NAT) Traversal for Offer/Answer Protocol](https://datatracker.ietf.org/doc/html/rfc5245)
* [Session Traversal Utilities for NAT (STUN)](https://datatracker.ietf.org/doc/html/rfc5389)
* [URI Scheme for the Session Traversal Utilities for NAT (STUN) Protocol](https://datatracker.ietf.org/doc/html/rfc7064)
* [Traversal Using Relays around NAT (TURN) Uniform Resource Identifiers](https://datatracker.ietf.org/doc/html/rfc7065)
* [An Offer/Answer Model with Session Description Protocol (SDP)](https://datatracker.ietf.org/doc/html/rfc3264)
* [Session Traversal Utilities for NAT (STUN) Extension for Third Party Authorization](https://datatracker.ietf.org/doc/rfc7635/)

See also
--------


* [`MediaDevices`](mediadevices)
* [`MediaStreamEvent`](mediastreamevent)
* [`MediaStreamTrack`](mediastreamtrack)
* [`MessageEvent`](messageevent)
* [`MediaStream`](mediastream)
* [Media Capture and Streams API](media_capture_and_streams_api)
* [Firefox multistream and renegotiation for Jitsi Videobridge](https://hacks.mozilla.org/2015/06/firefox-multistream-and-renegotiation-for-jitsi-videobridge/)
* [Peering Through the WebRTC Fog with SocketPeer](https://hacks.mozilla.org/2015/04/peering-through-the-webrtc-fog-with-socketpeer/)
* [Inside the Party Bus: Building a Web App with Multiple Live Video Streams + Interactive Graphics](https://hacks.mozilla.org/2014/04/inside-the-party-bus-building-a-web-app-with-multiple-live-video-streams-interactive-graphics/)
* [Web media technologies](https://developer.mozilla.org/en-US/docs/Web/Media)
* [WebRTC Statistics API](webrtc_statistics_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API>

WebTransport API
================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.


**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The **WebTransport API** provides a modern update to [WebSockets](websockets_api), transmitting data between client and server using [HTTP/3 Transport](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/). WebTransport provides support for multiple streams, unidirectional streams, and out-of-order delivery. It enables reliable transport via [streams](streams_api) and unreliable transport via UDP-like datagrams.


 **Note:** This feature is available in [Web Workers](web_workers_api)

 

Concepts and usage
------------------



[HTTP/3](https://en.wikipedia.org/wiki/HTTP/3) has been in progress since 2018. It is based on Google's QUIC protocol (which is itself based on UDP), and fixes several issues around the classic TCP protocol, on which HTTP and WebSockets are based.

 These include:

 * Head-of-line blocking: HTTP/2 allows multiplexing, so a single connection can stream multiple resources simultaneously. However, if a single resource fails, all other resources on that connection are held up until any missing packets are retransmitted. With QUIC, only the failing resource is affected.
* Faster performance: QUIC is more performant than TCP in many ways. QUIC can handle security features itself, rather than handing responsibility off to other protocols like TLS, meaning fewer round trips. And streams provide better transport efficiency than the older packet mechanism. This can make a significant difference, especially on high-latency networks.
* Better network transitions: QUIC uses a unique connection ID to handle the source and destination of each request to ensure that packets are delivered correctly. This ID can persist between different networks, meaning that for example a download can continue interrupted if you switch from Wifi to a mobile network. HTTP/2 on the other hand uses IP addresses as identifiers, so network transitions can be problematic.
* Unreliable transport: HTTP/3 supports unreliable data transmission via datagrams.

 The WebTransport API provides low-level access to two-way communication via HTTP/3, taking advantage of the above benefits, and supporting both reliable and unreliable data transmission.



### Initial connection



To open a connection to an HTTP/3 server, you pass its URL to the [`WebTransport()`](webtransport/webtransport) constructor. Note that the scheme needs to be HTTPS, and the port number needs to be explicitly specified. Once the [`WebTransport.ready`](webtransport/ready) promise fulfills, you can start using the connection.

 Also note that you can respond to the connection closing by waiting for the [`WebTransport.closed`](webtransport/closed) promise to fulfill. Errors returned by WebTransport operations are of type [`WebTransportError`](webtransporterror), and contain additional data on top of the standard [`DOMException`](domexception) set.

 
```
const url = "https://example.com:4999/wt";

async function initTransport(url) {
  // Initialize transport connection
  const transport = new WebTransport(url);

  // The connection can be used once ready fulfills
  await transport.ready;

  // ...
}

// ...

async function closeTransport(transport) {
  // Respond to connection closing
  try {
    await transport.closed;
    console.log(`The HTTP/3 connection to ${url} closed gracefully.`);
  } catch (error) {
    console.error(`The HTTP/3 connection to ${url} closed due to ${error}.`);
  }
}

```


### Unreliable transmission via datagrams



"Unreliable" means that transmission of data is not guaranteed, nor is arrival in a specific order. This is fine in some situations and provides very fast delivery. For example, you might want to transmit regular game state updates where each message supersedes the last one that arrives, and order is not important.

 Unreliable data transmission is handled via the [`WebTransport.datagrams`](webtransport/datagrams) property — this returns a [`WebTransportDatagramDuplexStream`](webtransportdatagramduplexstream) object containing everything you need to send datagrams to the server, and receive them back.

 The [`WebTransportDatagramDuplexStream.writable`](webtransportdatagramduplexstream/writable) property returns a [`WritableStream`](writablestream) object that you can write data to using a writer, for transmission to the server:

 
```
const writer = transport.datagrams.writable.getWriter();
const data1 = new Uint8Array([65, 66, 67]);
const data2 = new Uint8Array([68, 69, 70]);
writer.write(data1);
writer.write(data2);

```
 The [`WebTransportDatagramDuplexStream.readable`](webtransportdatagramduplexstream/readable) property returns a [`ReadableStream`](readablestream) object that you can use to receive data from the server:

 
```
async function readData() {
  const reader = transport.datagrams.readable.getReader();
  while (true) {
    const { value, done } = await reader.read();
    if (done) {
      break;
    }
    // value is a Uint8Array.
    console.log(value);
  }
}

```


### Reliable transmission via streams


"Reliable" means that transmission and order of data are guaranteed. This provides slower delivery (albeit faster than with WebSockets), and is needed in situations where reliability and ordering are important, like chat applications.


### Unidirectional transmission



To open a unidirectional stream from a user agent, you use the [`WebTransport.createUnidirectionalStream()`](webtransport/createunidirectionalstream) method to get a reference to a [`WritableStream`](writablestream). From this you can [`get a writer`](writablestream/getwriter) to allow data to be written to the stream and sent to the server.

 
```
async function writeData() {
  const stream = await transport.createUnidirectionalStream();
  const writer = stream.writable.getWriter();
  const data1 = new Uint8Array([65, 66, 67]);
  const data2 = new Uint8Array([68, 69, 70]);
  writer.write(data1);
  writer.write(data2);

  try {
    await writer.close();
    console.log("All data has been sent.");
  } catch (error) {
    console.error(`An error occurred: ${error}`);
  }
}

```
 Note also the use of the [`WritableStreamDefaultWriter.close()`](writablestreamdefaultwriter/close) method to close the associated HTTP/3 connection once all data has been sent.

 If the server opens a unidirectional stream to transmit data to the client, this can be accessed via the [`WebTransport.incomingUnidirectionalStreams`](webtransport/incomingunidirectionalstreams) property, which returns a [`ReadableStream`](readablestream) of `WebTransportReceiveStream` objects. Each one can be used to read [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instances sent by the server.

 In this case, the first thing to do is set up a function to read a `WebTransportReceiveStream`. These objects inherit from the `ReadableStream` class, so can be used in just the same way:

 
```
async function readData(receiveStream) {
  const reader = receiveStream.getReader();
  while (true) {
    const { done, value } = await reader.read();
    if (done) {
      break;
    }
    // value is a Uint8Array
    console.log(value);
  }
}

```
 Next, call [`WebTransport.incomingUnidirectionalStreams`](webtransport/incomingunidirectionalstreams) and get a reference to the reader available on the `ReadableStream` it returns, and then use the reader to read the data from the server. Each chunk is a `WebTransportReceiveStream`, and we use the `readFrom()` set up earlier to read them:

 
```
async function receiveUnidirectional() {
  const uds = transport.incomingUnidirectionalStreams;
  const reader = uds.getReader();
  while (true) {
    const { done, value } = await reader.read();
    if (done) {
      break;
    }
    // value is an instance of WebTransportReceiveStream
    await readData(value);
  }
}

```
 #### Bidirectional transmission

 To open a bidirectional stream from a user agent, you use the [`WebTransport.createBidirectionalStream()`](webtransport/createbidirectionalstream) method to get a reference to a [`WebTransportBidirectionalStream`](webtransportbidirectionalstream). In the same way as the [`WebTransportDatagramDuplexStream`](webtransportdatagramduplexstream), this contains `readable` and `writable` properties returning references to `ReadableStream` and `WritableStream` instances, which can be used to read from and write to the server.

 
```
async function setUpBidirectional() {
  const stream = await transport.createBidirectionalStream();
  // stream is a WebTransportBidirectionalStream
  // stream.readable is a ReadableStream
  const readable = stream.readable;
  // stream.writable is a WritableStream
  const writable = stream.writable;

  ...
}

```
 Reading from the `ReadableStream` can then be done as follows:

 
```
async function readData(readable) {
  const reader = readable.getReader();
  while (true) {
    const { value, done } = await reader.read();
    if (done) {
      break;
    }
    // value is a Uint8Array.
    console.log(value);
  }
}

```
 And writing to the `WritableStream` can be done like this:

 
```
async function writeData(writable) {
  const writer = writable.getWriter();
  const data1 = new Uint8Array([65, 66, 67]);
  const data2 = new Uint8Array([68, 69, 70]);
  writer.write(data1);
  writer.write(data2);
}

```
 If the server opens a bidirectional stream to transmit data to and receive it from the client, this can be accessed via the [`WebTransport.incomingBidirectionalStreams`](webtransport/incomingbidirectionalstreams) property, which returns a [`ReadableStream`](readablestream) of `WebTransportBidirectionalStream` objects. Each one can be used to read and write [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instances as shown above. However, as with the unidirectional example, you need an initial function to read the bidirectional stream in the first place:

 
```
async function receiveBidirectional() {
  const bds = transport.incomingBidirectionalStreams;
  const reader = bds.getReader();
  while (true) {
    const { done, value } = await reader.read();
    if (done) {
      break;
    }
    // value is an instance of WebTransportBidirectionalStream
    await readData(value.readable);
    await writeData(value.writable);
  }
}

```


Interfaces
----------


 
[`WebTransport`](webtransport)  Experimental 
  Provides functionality to enable a user agent to connect to an HTTP/3 server, initiate reliable and unreliable transport in either or both directions, and close the connection once it is no longer needed.

  [`WebTransportBidirectionalStream`](webtransportbidirectionalstream)  Represents a bidirectional stream created by a server or a client that can be used for reliable transport. Provides access to a [`ReadableStream`](readablestream) for reading incoming data, and a [`WritableStream`](writablestream) for writing outgoing data.

  [`WebTransportDatagramDuplexStream`](webtransportdatagramduplexstream)  Represents a duplex stream that can be used for unreliable transport of datagrams between client and server. Provides access to a [`ReadableStream`](readablestream) for reading incoming datagrams, a [`WritableStream`](writablestream) for writing outgoing datagrams, and various settings and statistics related to the stream.

  [`WebTransportError`](webtransporterror)  Represents an error related to the WebTransport API, which can arise from server errors, network connection problems, or client-initiated abort operations (for example, arising from a [`WritableStream.abort()`](writablestream/abort) call).

  
Examples
--------



For complete examples, see:

 * [WebTransport over HTTP/3 client](https://webtransport.day/)
* [WebTransport (BYOB) Echo with WebCodecs in Worker](https://webrtc.internaut.com/wc/wtSender4/)



Specifications
--------------




| Specification |
| --- |
| [WebTransport # web-transport](https://w3c.github.io/webtransport/#web-transport) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `WebTransport` | 97 | 97 | No | No | 83 | No | 97 | 97 | No | 68 | No | 18.0 |
| `WebTransport_API` | 97 | 97 | No | No | 83 | No | 97 | 97 | No | 68 | No | 18.0 |
| `close` | 97 | 97 | No | No | 83 | No | 97 | 97 | No | 68 | No | 18.0 |
| `closed` | 97 | 97 | No | No | 83 | No | 97 | 97 | No | 68 | No | 18.0 |
| `createBidirectionalStream` | 97 | 97 | No | No | 83 | No | 97 | 97 | No | 68 | No | 18.0 |
| `createUnidirectionalStream` | 97 | 97 | No | No | 83 | No | 97 | 97 | No | 68 | No | 18.0 |
| `datagrams` | 97 | 97 | No | No | 83 | No | 97 | 97 | No | 68 | No | 18.0 |
| `incomingBidirectionalStreams` | 97 | 97 | No | No | 83 | No | 97 | 97 | No | 68 | No | 18.0 |
| `incomingUnidirectionalStreams` | 97 | 97 | No | No | 83 | No | 97 | 97 | No | 68 | No | 18.0 |
| `ready` | 97 | 97 | No | No | 83 | No | 97 | 97 | No | 68 | No | 18.0 |


See also
--------


* [Using WebTransport](https://web.dev/webtransport/)
* [WebSockets API](websockets_api)
* [Streams API](streams_api)
* [WebTransport over HTTP/3](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/WebTransport_API>

WebUSB API
==========



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The **WebUSB API** provides a way to expose non-standard Universal Serial Bus (USB) compatible devices services to the web, to make USB safer and easier to use.



Concepts and Usage
------------------



USB is the de-facto standard for wired peripherals. The USB devices that you connect to your computer are typically grouped into a number of device classes—such as keyboards, mice, video devices, and so on. These are supported using the operating system's class driver. Many of these are also web accessible via the [`WebHID API`](webhid_api).

 In addition to these standardized devices, there are a large number of devices that don't fit into any class. These need custom drivers, and are inaccessible from the web due to the native code required to take advantage of them. Installing one of these devices often involves searching on a manufacturer's website for drivers and, should you wish to use the device on another computer, repeating the process again.

 WebUSB provides a way for these non-standardized USB device services to be exposed to the web. This means that hardware manufacturers will be able to provide a way for their device to be accessed from the web, without having to provide their own API.

 When connecting a new WebUSB-compatible device, the browser displays a notification providing a link to the manufacturer's website. On arriving at the site the browser prompts for permission to connect to the device, then the device is ready for use. No drivers need be downloaded and installed.



Interfaces
----------


 [`USB`](usb)  Provides attributes and methods for finding and connecting USB devices from a web page.

  [`USBConnectionEvent`](usbconnectionevent)  The event type passed to [`USB.onconnect`](usb/connect_event) or [`USB.ondisconnect`](usb/disconnect_event) when the user agent detects a new USB device has been connected to, or disconnected from the host.

  [`USBDevice`](usbdevice)  Provides access to metadata about a paired USB device and methods for controlling it.

  [`USBInTransferResult`](usbintransferresult)  Represents the result from requesting a transfer of data from the USB device to the USB host.

  [`USBIsochronousInTransferPacket`](usbisochronousintransferpacket)  Represents the status of an individual packet from a request to transfer data from the USB device to the USB host over an isochronous endpoint.

  [`USBIsochronousInTransferResult`](usbisochronousintransferresult)  Represents the result from requesting a transfer of data from the USB device to the USB host.

  [`USBIsochronousOutTransferPacket`](usbisochronousouttransferpacket)  Represents the status of an individual packet from a request to transfer data from the USB host to the USB device over an isochronous endpoint.

  [`USBIsochronousOutTransferResult`](usbisochronousouttransferresult)  Represents the result from requesting a transfer of data from the USB host to the USB device.

  [`USBConfiguration`](usbconfiguration)  Provides information about a particular configuration of a USB device and the interfaces that it supports.

  [`USBInterface`](usbinterface)  Provides information about an interface provided by the USB device.

  [`USBAlternateInterface`](usbalternateinterface)  Provides information about a particular configuration of an interface provided by the USB device.

  [`USBEndPoint`](usbendpoint)  Provides information about an endpoint provided by the USB device.

  
Examples
--------


### Accessing a connected device



The following example demonstrates how to access a connected Arduino device using [`USB.requestDevice()`](usb/requestdevice), which has a vendorId of `0x2341`.

 
```
navigator.usb
  .requestDevice({ filters: [{ vendorId: 0x2341 }] })
  .then((device) => {
    console.log(device.productName); // "Arduino Micro"
    console.log(device.manufacturerName); // "Arduino LLC"
  })
  .catch((error) => {
    console.error(error);
  });

```


### Finding all connected devices



You can find all connected devices with [`USB.getDevices()`](usb/getdevices). In the following example, with the Arduino device connected, product and manufacturer name are printed to the console.

 
```
navigator.usb.getDevices().then((devices) => {
  devices.forEach((device) => {
    console.log(device.productName); // "Arduino Micro"
    console.log(device.manufacturerName); // "Arduino LLC"
  });
});

```


Specifications
--------------




| Specification |
| --- |
| [WebUSB API](https://wicg.github.io/webusb/)  |


See also
--------


* [Access USB Devices on the Web](https://web.dev/usb/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/WebUSB_API>

WebVR API
=========



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.


**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

  **Note:** WebVR API is replaced by [WebXR API](webxr_device_api). WebVR was never ratified as a standard, was implemented and enabled by default in very few browsers and supported a small number of devices.

  WebVR provides support for exposing virtual reality devices — for example, head-mounted displays like the Oculus Rift or HTC Vive — to web apps, enabling developers to translate position and movement information from the display into movement around a 3D scene. This has numerous, interesting applications, from virtual product tours and interactive training apps to immersive first-person games.



Concepts and usage
------------------



Any VR devices attached to your computer will be returned by the [`Navigator.getVRDisplays()`](navigator/getvrdisplays) method; each one will be represented by a [`VRDisplay`](vrdisplay) object.

  ![Sketch of a person in a chair with wearing goggles labelled "Head mounted display (HMD)" facing a monitor with a webcam labelled "Position sensor"] 

 [`VRDisplay`](vrdisplay) is the central interface in the WebVR API — via its properties and methods you can access functionality to:

 * Retrieve useful information to allow us to identify the display, what capabilities it has, controllers associated with it, and more.
* Retrieve [`frame data`](vrframedata) for each frame of content you want to present in a display, and submit those frames for display at a consistent rate.
* Start and stop presenting to the display.

 A typical (simple) WebVR app would work like so:

 1. [`Navigator.getVRDisplays()`](navigator/getvrdisplays) is used to get a reference to your VR display.
2. [`VRDisplay.requestPresent()`](vrdisplay/requestpresent) is used to start presenting to the VR display.
3. WebVR's dedicated [`VRDisplay.requestAnimationFrame()`](vrdisplay/requestanimationframe) method is used to run the app's rendering loop at the correct refresh rate for the display.
4. Inside the rendering loop, you grab the data required to display the current frame ([`VRDisplay.getFrameData()`](vrdisplay/getframedata)), draw the displayed scene twice — once for the view in each eye, then submit the rendered view to the display to show to the user ([`VRDisplay.submitFrame()`](vrdisplay/submitframe)).

 In addition, WebVR 1.1 adds a number of events on the [`Window`](window) object to allow JavaScript to respond to changes to the status of the display.

  **Note:** You can find a lot more out about how the API works in our [Using the WebVR API](webvr_api/using_the_webvr_api) and [WebVR Concepts](webvr_api/concepts) articles.

 

### API availability



The WebVR API, which was never ratified as a web standard, has been deprecated in favor of the [WebXR API](webxr_device_api), which is well on track toward finishing the standardization process. As such, you should try to update existing code to use the newer API instead. Generally the transition should be fairly painless.

 Additionally, on some devices and/or browsers, WebVR requires that the page be loaded using a secure context, over an HTTPS connection. If the page is not fully secure, the WebVR methods and functions will not be available. You can easily test for this by checking to see if the [`Navigator`](navigator) method [`getVRDisplays()`](navigator/getvrdisplays) is `NULL`:

 
```
if (!navigator.getVRDisplays) {
  console.error("WebVR is not available");
} else {
  /\* Use WebVR \*/
}

```


### Using controllers: Combining WebVR with the Gamepad API



Many WebVR hardware setups feature controllers that go along with the headset. These can be used in WebVR apps via the [Gamepad API](gamepad_api), and specifically the [Gamepad Extensions API](gamepad_api#experimental_gamepad_extensions) that adds API features for accessing [controller pose](gamepadpose), [haptic actuators](gamepadhapticactuator), and more.

  **Note:** Our [Using VR controllers with WebVR](webvr_api/using_vr_controllers_with_webvr) article explains the basics of how to use VR controllers with WebVR apps.

 

WebVR interfaces
----------------


 [`VRDisplay`](vrdisplay)  Represents any VR device supported by this API. It includes generic information such as device IDs and descriptions, as well as methods for starting to present a VR scene, retrieving eye parameters and display capabilities, and other important functionality.

  [`VRDisplayCapabilities`](vrdisplaycapabilities)  Describes the capabilities of a [`VRDisplay`](vrdisplay) — its features can be used to perform VR device capability tests, for example can it return position information.

  [`VRDisplayEvent`](vrdisplayevent)  Represents the event object of WebVR-related events (see the [window object extensions](#window) listed below).

  [`VRFrameData`](vrframedata)  Represents all the information needed to render a single frame of a VR scene; constructed by [`VRDisplay.getFrameData()`](vrdisplay/getframedata).

  [`VRPose`](vrpose)  Represents the position state at a given timestamp (which includes orientation, position, velocity, and acceleration).

  [`VREyeParameters`](vreyeparameters)  Provides access to all the information required to correctly render a scene for each given eye, including field of view information.

  [`VRFieldOfView`](vrfieldofview)  Represents a field of view defined by 4 different degree values describing the view from a center point.

  [`VRLayerInit`](vrlayerinit)  Represents a layer to be presented in a [`VRDisplay`](vrdisplay).

  [`VRStageParameters`](vrstageparameters)  Represents the values describing the stage area for devices that support room-scale experiences.

  
### Extensions to other interfaces



The WebVR API extends the following APIs, adding the listed features.

 #### Gamepad

  
[`Gamepad.displayId`](gamepad/displayid) Read only 
  *Returns the [`VRDisplay.displayId`](vrdisplay/displayid) of the associated [`VRDisplay`](vrdisplay) — the `VRDisplay` that the gamepad is controlling the displayed scene of.*

   #### Navigator

  
[`Navigator.activeVRDisplays`](navigator/activevrdisplays) Read only 
  Returns an array containing every [`VRDisplay`](vrdisplay) object that is currently presenting ([`VRDisplay.ispresenting`](vrdisplay/ispresenting) is `true`).

  [`Navigator.getVRDisplays()`](navigator/getvrdisplays)  Returns a promise that resolves to an array of [`VRDisplay`](vrdisplay) objects representing any available VR displays connected to the computer.

   #### Window events

  [`vrdisplaypresentchange`](window/vrdisplaypresentchange_event)  Fired when the presenting state of a VR display changes — i.e. goes from presenting to not presenting or vice versa.

  [`vrdisplayconnect`](window/vrdisplayconnect_event)  Fired when a compatible VR display has been connected to the computer.

  [`vrdisplaydisconnect`](window/vrdisplaydisconnect_event)  Fired when a compatible VR display has been disconnected from the computer.

  [`vrdisplayactivate`](window/vrdisplayactivate_event)  Fired when a display is able to be presented to.

  [`vrdisplaydeactivate`](window/vrdisplaydeactivate_event)  Fired when a display can no longer be presented to.

  [`vrdisplayblur`](window)  Fired when presentation to a display has been paused for some reason by the browser, OS, or VR hardware.

  [`vrdisplayfocus`](window)  Fired when presentation to a display has resumed after being blurred.

  

Examples
--------



You can find a number of examples at these locations:

 * [webvr-tests](https://github.com/mdn/webvr-tests) — very simple examples to accompany the MDN WebVR documentation.
* [Carmel starter kit](https://github.com/facebookarchive/Carmel-Starter-Kit) — nice simple, well-commented examples that go along with Carmel, Facebook's WebVR browser.
* [WebVR.info samples](https://webvr.info/samples/) — slightly more in-depth examples plus source code
* [WebVR.rocks Firefox demos](https://webvr.rocks/firefox#demos) — showcase examples
* [A-Frame homepage](https://aframe.io/) — examples showing A-Frame usage



Specifications
--------------



This API was specified in the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/) that has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). It is no longer on track to becoming a standard.

 Until all browsers have implemented the new [WebXR APIs](webxr_device_api/fundamentals), it is recommended to rely on frameworks, like [A-Frame](https://aframe.io/), [Babylon.js](https://www.babylonjs.com/), or [Three.js](https://threejs.org/), or a [polyfill](https://github.com/immersive-web/webxr-polyfill), to develop WebXR applications that will work across all browsers [[1]](https://developer.oculus.com/documentation/web/port-vr-xr/).



Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `WebVR_API` | NoAvailable on all platforms behind a flag, but currently only works on desktop in an [experimental version of Chrome](https://webvr.info/get-chrome/) (other builds won't return any devices when `Navigator.getVRDisplays()` is invoked). | 15–79 | 9864–98macOS support was enabled in Firefox 64.55–98Windows support was enabled in Firefox 55. | No | No | No | No | 79–80Currently supported only by Google Daydream. | 55 | No | No | 12.0–13.0Currently supported only by Google Daydream. |


See also
--------


* [vr.mozilla.org](https://mixedreality.mozilla.org/) — The main Mozilla landing pad for WebVR, with demos, utilities, and other information.
* [A-Frame](https://aframe.io/) — Open source web framework for building VR experiences.
* [webvr.info](https://webvr.info) — Up-to-date information about WebVR, browser setup, and community.
* [threejs-vr-boilerplate](https://github.com/MozillaReality/vr-web-examples/tree/master/threejs-vr-boilerplate) — A useful starter template for writing WebVR apps into.
* [Web VR polyfill](https://github.com/immersive-web/webvr-polyfill) — JavaScript implementation of WebVR.
* [Supermedium](https://www.supermedium.com) — A pure WebVR browser to easily access the best WebVR content.
* [WebVR Directory](https://webvr.directory/) — List of quality WebVR sites.


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/WebVR_API>

WebGPU API
==========



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.


**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The **WebGPU API** enables web developers to use the underlying system's GPU (Graphics Processing Unit) to carry out high-performance computations and draw complex images that can be rendered in the browser.

 WebGPU is the successor to [WebGL](webgl_api), providing better compatibility with modern GPUs, support for general-purpose GPU computations, faster operations, and access to more advanced GPU features.



Concepts and usage
------------------



It is fair to say that [WebGL](webgl_api) revolutionized the web in terms of graphical capabilities after it first appeared around 2011. WebGL is a JavaScript port of the [OpenGL ES 2.0](https://registry.khronos.org/OpenGL-Refpages/es2.0/) graphics library, allowing web pages to pass rendering computations directly to the device's GPU to be processed at very high speeds, and render the result inside a [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element.

 WebGL and the [GLSL](https://www.khronos.org/opengl/wiki/Core_Language_(GLSL)) language used to write WebGL shader code are complex, so several WebGL libraries have been created to make WebGL apps easier to write: Popular examples include [Three.js](https://threejs.org/), [Babylon.js](https://www.babylonjs.com/), and [PlayCanvas](https://playcanvas.com/). Developers have used these tools to build immersive web-based 3D games, music videos, training and modeling tools, VR and AR experiences, and more.

 However, WebGL has some fundamental issues that needed addressing:

 * Since WebGL's release, a new generation of native GPU APIs have appeared — the most popular being [Microsoft's Direct3D 12](https://docs.microsoft.com/en-us/windows/win32/direct3d12/direct3d-12-graphics), [Apple's Metal](https://developer.apple.com/metal/), and [The Khronos Group's Vulkan](https://www.vulkan.org/) — which provide a multitude of new features. There are no more updates planned to OpenGL (and therefore WebGL), so it won't get any of these new features. WebGPU on the other hand will have new features added to it going forwards.
* WebGL is based wholly around the use case of drawing graphics and rendering them to a canvas. It does not handle general-purpose GPU (GPGPU) computations very well. GPGPU computations are becoming more and more important for many different use cases, for example those based on machine learning models.
* 3D graphics apps are becoming increasingly demanding, both in terms of the number of objects to be rendered simultaneously, and usage of new rendering features.

 WebGPU addresses these issues, providing an updated general-purpose architecture compatible with modern GPU APIs, which feels more "webby". It supports graphic rendering, but also has first-class support for GPGPU computations. Rendering of individual objects is significantly cheaper on the CPU side, and it supports modern GPU rendering features such as compute-based particles and post-processing filters like color effects, sharpening, and depth-of-field simulation. In addition, it can handle expensive computations such as culling and skinned model transformation directly on the GPU.



General model
-------------



There are several layers of abstraction between a device GPU and a web browser running the WebGPU API. It is useful to understand these as you begin to learn WebGPU:

  ![A basic stack diagram showing the position of the different elements of a WebGPU architecture on a device] 

 * Physical devices have GPUs. Most devices only have one GPU, but some have more than one. Different GPU types are available:
	+ Integrated GPUs, which live on the same board as the CPU and share its memory.
	+ Discrete GPUs, which live on their own board, separate from the CPU.
	+ Software "GPUs", implemented on the CPU. **Note:** The above diagram assumes a device with only one GPU.
* A native GPU API, which is part of the OS (e.g. Metal on macOS), is a programming interface allowing native applications to use the capabilities of the GPU. API instructions are sent to the GPU (and responses received) via a driver. It is possible for a system to have multiple native OS APIs and drivers available to communicate with the GPU, although the above diagram assumes a device with only one native API/driver.
* A browser's WebGPU implementation handles communicating with the GPU via a native GPU API driver. A WebGPU adapter effectively represents a physical GPU and driver available on the underlying system, in your code.
* A logical device is an abstraction via which a single web app can access GPU capabilities in a compartmentalized way. Logical devices are required to provide multiplexing capabilities. A physical device's GPU is used by many applications and processes concurrently, including potentially many web apps. Each web app needs to be able to access WebGPU in isolation for security and logic reasons.



Accessing a device
------------------



A logical device — represented by a [`GPUDevice`](gpudevice) object instance — is the basis from which a web app accesses all WebGPU functionality. Accessing a device is done as follows:

 1. The [`Navigator.gpu`](navigator/gpu) property (or [`WorkerNavigator.gpu`](workernavigator/gpu) if you are using WebGPU functionality from inside a worker) returns the [`GPU`](gpu) object for the current context.
2. You access an adapter via the [`GPU.requestAdapter()`](gpu/requestadapter) method. This method accepts an optional settings object allowing you to request for example a high-performance or low-energy adapter. If this is not included, the device will provide access to the default adapter, which is good enough for most purposes.
3. A device can be requested via [`GPUAdapter.requestDevice()`](gpuadapter/requestdevice). This method also accepts an options object (referred to as a descriptor), which can be used to specify the exact features and limits you want the logical device to have. If this is not included, the supplied device will have a reasonable general-purpose spec that is good enough for most purposes.

 Putting this together with some feature detection checks, the above process could be achieved as follows:

 
```
async function init() {
  if (!navigator.gpu) {
    throw Error("WebGPU not supported.");
  }

  const adapter = await navigator.gpu.requestAdapter();
  if (!adapter) {
    throw Error("Couldn't request WebGPU adapter.");
  }

  const device = await adapter.requestDevice();

  //...
}

```


Pipelines and shaders: WebGPU app structure
-------------------------------------------



A pipeline is a logical structure containing programmable stages that are completed to get your program's work done. WebGPU is currently able to handle two types of pipeline:

 * A render pipeline renders graphics, typically into a [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element, but it could also render graphics offscreen. It has two main stages:
	+ A vertex stage, in which a vertex shader takes positioning data fed into the GPU and uses it to position a series of vertices in 3D space by applying specified effects like rotation, translation, or perspective. The vertices are then assembled into primitives such as triangles (the basic building block of rendered graphics) and rasterized by the GPU to figure out what pixels each one should cover on the drawing canvas.
	+ A fragment stage, in which a fragment shader computes the color for each pixel covered by the primitives produced by the vertex shader. These computations frequently use inputs such as images (in the form of textures) that provide surface details and the position and color of virtual lights.
* A compute pipeline is for general computation. A compute pipeline contains a single compute stage in which a compute shader takes general data, processes it in parallel across a specified number of workgroups, then returns the result in one or more buffers. The buffers can contain any kind of data.

 The shaders mentioned above are sets of instructions processed by the GPU. WebGPU shaders are written in a low-level Rust-like language called [WebGPU Shader Language](https://gpuweb.github.io/gpuweb/wgsl/) (WGSL).

 There are several different ways in which you could architect a WebGPU app, but the process will likely contain the following steps:

 1. [Create shader modules](#create_shader_modules): Write your shader code in WGSL and package it into one or more shader modules.
2. [Get and configure the canvas context](#get_and_configure_the_canvas_context): Get the `webgpu` context of a `<canvas>` element and configure it to receive information on what graphics to render from your GPU logical device. This step is not necessary if your app has no graphical output, such as one that only uses compute pipelines.
3. [Create resources containing your data](#create_a_buffer_and_write_our_triangle_data_into_it): The data that you want processed by your pipelines needs to be stored in GPU buffers or textures to be accessed by your app.
4. [Create pipelines](#define_and_create_the_render_pipeline): Define pipeline descriptors that describe the desired pipelines in detail, including the required data structure, bindings, shaders, and resource layouts, then create pipelines from them. Our basic demos only contain a single pipeline, but non-trivial apps will usually contain multiple pipelines for different purposes.
5. [Run a compute/rendering pass](#running_a_rendering_pass): This involves a number of substeps:
	1. Create a command encoder that can encode a set of commands to be passed to the GPU to execute.
	2. Create a pass encoder object on which compute/render commands are issued.
	3. Run commands to specify which pipelines to use, what buffer(s) to get the required data from, how many drawing operations to run (in the case of render pipelines), etc.
	4. Finalize the command list and encapsulate it in a command buffer.
	5. Submit the command buffer to the GPU via the logical device's command queue.

 In the sections below, we will examine a basic render pipeline demo, to allow you to explore what it requires. Later on, we'll also examine a [basic compute pipeline](#basic_compute_pipeline) example, looking at how it differs from the render pipeline.



Basic render pipeline
---------------------


In our [basic render demo](https://mdn.github.io/dom-examples/webgpu-render-demo/) we give a `<canvas>` element a solid blue background and draw a triangle onto it.


### Create shader modules



We are using the following shader code. The vertex shader stage (`@vertex` block) accepts a chunk of data containing a position and a color, positions the vertex according to the given position, interpolates the color, then passes the data along to the fragment shader stage. The fragment shader stage (`@fragment` block) accepts the data from the vertex shader stage and colors the vertex according to the given color.

 
```
const shaders = `
struct VertexOut {
 @builtin(position) position : vec4f,
 @location(0) color : vec4f
}

@vertex
fn vertex\_main(@location(0) position: vec4f,
 @location(1) color: vec4f) -> VertexOut
{
 var output : VertexOut;
 output.position = position;
 output.color = color;
 return output;
}

@fragment
fn fragment\_main(fragData: VertexOut) -> @location(0) vec4f
{
 return fragData.color;
}
`;

```
  **Note:** In our demos we are storing our shader code inside a template literal, but you can store it anywhere from which it can easily be retrieved as text to be fed into your WebGPU program. For example, another common practice is to store shaders inside a [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) element and retrieve the contents using [`Node.textContent`](node/textcontent). The correct mime type to use for WGSL is `text/wgsl`.

  To make your shader code available to WebGPU, you have to put it inside a [`GPUShaderModule`](gpushadermodule) via a [`GPUDevice.createShaderModule()`](gpudevice/createshadermodule) call, passing your shader code as a property inside a descriptor object. For example:

 
```
const shaderModule = device.createShaderModule({
  code: shaders,
});

```


### Get and configure the canvas context



In a render pipeline, we need to specify somewhere to render the graphics to. In this case we are getting a reference to an onscreen `<canvas>` element then calling [`HTMLCanvasElement.getContext()`](htmlcanvaselement/getcontext) with a parameter of `webgpu` to return its GPU context (a [`GPUCanvasContext`](gpucanvascontext) instance).

 From there, we configure the context with a call to [`GPUCanvasContext.configure()`](gpucanvascontext/configure), passing it an options object containing the [`GPUDevice`](gpudevice) that the rendering information will come from, the format the textures will have, and the alpha mode to use when rendering semi-transparent textures.

 
```
const canvas = document.querySelector("#gpuCanvas");
const context = canvas.getContext("webgpu");

context.configure({
  device: device,
  format: navigator.gpu.getPreferredCanvasFormat(),
  alphaMode: "premultiplied",
});

```
  **Note:** The best practice for determining the texture format is to use the [`GPU.getPreferredCanvasFormat()`](gpu/getpreferredcanvasformat) method; this selects the most efficient format (either `bgra8unorm` or `rgba8unorm`) for the user's device.

 

### Create a buffer and write our triangle data into it



Next we will provide our WebGPU program with our data, in a form it can use. Our data is initially provided in a [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array), which contains 8 data points for each triangle vertex — X, Y, Z, W for position, and R, G, B, A for color.

 
```
const vertices = new Float32Array([
  0.0, 0.6, 0, 1, 1, 0, 0, 1, -0.5, -0.6, 0, 1, 0, 1, 0, 1, 0.5, -0.6, 0, 1, 0,
  0, 1, 1,
]);

```
 However, we've got an issue here. We need to get our data into a [`GPUBuffer`](gpubuffer). Behind the scenes, this type of buffer is stored in memory very tightly integrated with the GPU's cores to allow for the desired high performance processing. As a side effect, this memory can't be accessed by processes running on the host system, like the browser.

 The [`GPUBuffer`](gpubuffer) is created via a call to [`GPUDevice.createBuffer()`](gpudevice/createbuffer). We give it a size equal to the length of the `vertices` array so it can contain all the data, and `VERTEX` and `COPY_DST` usage flags to indicate that the buffer will be used as a vertex buffer and the destination of copy operations.

 
```
const vertexBuffer = device.createBuffer({
  size: vertices.byteLength, // make it big enough to store vertices in
  usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY\_DST,
});

```
 We could handle getting our data into the `GPUBuffer` using a mapping operation, like we use in the [compute pipeline example](#basic_compute_pipeline) to read data from the GPU back to JavaScript. However, in this case we are going to use the handy [`GPUQueue.writeBuffer()`](gpuqueue/writebuffer) convenience method, which takes as its parameters the buffer to write to, the data source to write from, an offset value for each, and the size of data to write (we've specified the whole length of the array). The browser then works out the most efficient way to handle writing the data.

 
```
device.queue.writeBuffer(vertexBuffer, 0, vertices, 0, vertices.length);

```


### Define and create the render pipeline



Now we've got our data into a buffer, the next part of the setup is to actually create our pipeline, ready to be used for rendering.

 First of all, we create an object that describes the required layout of our vertex data. This perfectly describes what we saw earlier on in our `vertices` array and vertex shader stage — each vertex has position and color data. Both are formatted in `float32x4` format (which maps to the WGSL `vec4<f32>` type), and the color data starts at an offset of 16 bytes into each vertex. `arrayStride` specifies the stride, meaning the number of bytes making up each vertex, and `stepMode` specifies that the data should be fetched per-vertex.

 
```
const vertexBuffers = [
  {
    attributes: [
      {
        shaderLocation: 0, // position
        offset: 0,
        format: "float32x4",
      },
      {
        shaderLocation: 1, // color
        offset: 16,
        format: "float32x4",
      },
    ],
    arrayStride: 32,
    stepMode: "vertex",
  },
];

```
 Next, we create a descriptor object that specifies the configuration of our render pipeline stages. For both the shader stages, we specify the [`GPUShaderModule`](gpushadermodule) that the relevant code can be found in (`shaderModule`), and the name of the function that acts as the entry point for each stage.

 In addition, in the case of the vertex shader stage we provide our `vertexBuffers` object to provide the expected state of our vertex data. And in the case of our fragment shader stage, we provide an array of color target states that indicate the specified rendering format (this matches the format specified in our canvas context config earlier).

 We also specify a `primitive` state, which in this case just states the type of primitive we will be drawing, and a `layout` of `auto`. The `layout` property defines the layout (structure, purpose, and type) of all the GPU resources (buffers, textures, etc.) used during the execution of the pipeline. In more complex apps, this would take the form of a [`GPUPipelineLayout`](gpupipelinelayout) object, created using [`GPUDevice.createPipelineLayout()`](gpudevice/createpipelinelayout) (you can see an example in our [Basic compute pipeline](#basic_compute_pipeline)), which allows the GPU to figure out how to run the pipeline most efficiently ahead of time. Here however we are specifying the `auto` value, which will cause the pipeline to generate an implicit bind group layout based on any bindings defined in the shader code.

 
```
const pipelineDescriptor = {
  vertex: {
    module: shaderModule,
    entryPoint: "vertex\_main",
    buffers: vertexBuffers,
  },
  fragment: {
    module: shaderModule,
    entryPoint: "fragment\_main",
    targets: [
      {
        format: navigator.gpu.getPreferredCanvasFormat(),
      },
    ],
  },
  primitive: {
    topology: "triangle-list",
  },
  layout: "auto",
};

```
 Finally, we can create a [`GPURenderPipeline`](gpurenderpipeline) based on our `pipelineDescriptor` object, by passing it in as a parameter to a [`GPUDevice.createRenderPipeline()`](gpudevice/createrenderpipeline) method call.

 
```
const renderPipeline = device.createRenderPipeline(pipelineDescriptor);

```


### Running a rendering pass



Now that all the setup is done, we can actually run a rendering pass and draw something onto our `<canvas>`. To encode any commands to be later issued to the GPU, you need to create a [`GPUCommandEncoder`](gpucommandencoder) instance, which is done using a [`GPUDevice.createCommandEncoder()`](gpudevice/createcommandencoder) call.

 
```
const commandEncoder = device.createCommandEncoder();

```
 Next up we start the rendering pass running by creating a [`GPURenderPassEncoder`](gpurenderpassencoder) instance with a [`GPUCommandEncoder.beginRenderPass()`](gpucommandencoder/beginrenderpass) call. This method takes a descriptor object as a parameter, the only mandatory property of which is a `colorAttachments` array. In this case, we specify:

 1. A texture view to render into; we create a new view from the `<canvas>` via [`context.getCurrentTexture().createView()`](gputexture/createview).
2. That the view should be "cleared" to a specified color once loaded and before any drawing takes place. This is what causes the blue background behind the triangle.
3. That the value of the current rendering pass should be stored for this color attachment.

 
```
const clearColor = { r: 0.0, g: 0.5, b: 1.0, a: 1.0 };

const renderPassDescriptor = {
  colorAttachments: [
    {
      clearValue: clearColor,
      loadOp: "clear",
      storeOp: "store",
      view: context.getCurrentTexture().createView(),
    },
  ],
};

const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);

```
 Now we can invoke methods of the rendering pass encoder to draw our triangle:

 1. [`GPURenderPassEncoder.setPipeline()`](gpurenderpassencoder/setpipeline) is called with our `renderPipeline` object as a parameter to specify the pipeline to use for the rendering pass.
2. [`GPURenderPassEncoder.setVertexBuffer()`](gpurenderpassencoder/setvertexbuffer) is called with our `vertexBuffer` object as a parameter to act as the data source to pass to the pipeline to render. The first parameter is the slot to set the vertex buffer for, and is a reference to the index of the element in the `vertexBuffers` array which describes this buffer's layout.
3. [`GPURenderPassEncoder.draw()`](gpurenderpassencoder/draw) sets the drawing in motion. There is data for three vertices inside our `vertexBuffer`, so we set a vertex count value of `3` to draw them all.

 
```
passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);

```
 To finish encoding the sequence of commands and issue them to the GPU, three more steps are needed.

 1. We invoke the [`GPURenderPassEncoder.end()`](gpurenderpassencoder/end) method to signal the end of the render pass command list.
2. We invoke the [`GPUCommandEncoder.finish()`](gpucommandencoder/finish) method to complete recording of the issued command sequence and encapsulate it into a [`GPUCommandBuffer`](gpucommandbuffer) object instance.
3. We submit the [`GPUCommandBuffer`](gpucommandbuffer) to the device's command queue (represented by a [`GPUQueue`](gpuqueue) instance) to be sent to the GPU. The device's queue is available via the [`GPUDevice.queue`](gpudevice/queue) property, and an array of [`GPUCommandBuffer`](gpucommandbuffer) instances can be added to the queue via a [`GPUQueue.submit()`](gpuqueue/submit) call.

 These three steps can be achieved via the following two lines:

 
```
passEncoder.end();

device.queue.submit([commandEncoder.finish()]);

```


Basic compute pipeline
----------------------



In our [basic compute demo](https://mdn.github.io/dom-examples/webgpu-compute-demo/), we get the GPU to calculate some values, store them in an output buffer, copy the data across to a staging buffer, then map that staging buffer so that the data can be read out to JavaScript and logged to the console.

 The app follows a similar structure to the basic rendering demo. We create a [`GPUDevice`](gpudevice) reference in the same way as before, and encapsulate our shader code into a [`GPUShaderModule`](gpushadermodule) via a [`GPUDevice.createShaderModule()`](gpudevice/createshadermodule) call. The difference here is that our shader code only has one shader stage, a `@compute` stage:

 
```
// Define global buffer size
const BUFFER\_SIZE = 1000;

const shader = `
@group(0) @binding(0)
var<storage, read\_write> output: array<f32>;

@compute @workgroup\_size(64)
fn main(
 @builtin(global\_invocation\_id)
 global\_id : vec3u,

 @builtin(local\_invocation\_id)
 local\_id : vec3u,
) {
 // Avoid accessing the buffer out of bounds
 if (global\_id.x >= ${BUFFER\_SIZE}) {
 return;
 }

 output[global\_id.x] =
 f32(global\_id.x) \* 1000. + f32(local\_id.x);
}
`;

```


### Create buffers to handle our data



In this example we create two [`GPUBuffer`](gpubuffer) instances to handle our data, an `output` buffer to write the GPU calculation results to at high speed, and a `stagingBuffer` that we'll copy the `output` contents to, which can be mapped to allow JavaScript to access the values.

 * `output` is specified as a storage buffer that will be the source of a copy operation.
* `stagingBuffer` is specified as a buffer that can be mapped for reading by JavaScript, and will be the destination of a copy operation.

 
```
const output = device.createBuffer({
  size: BUFFER\_SIZE,
  usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY\_SRC,
});

const stagingBuffer = device.createBuffer({
  size: BUFFER\_SIZE,
  usage: GPUBufferUsage.MAP\_READ | GPUBufferUsage.COPY\_DST,
});

```


### Create a bind group layout



When the pipeline is created, we specify a bind group to use for the pipeline. This involves first creating a [`GPUBindGroupLayout`](gpubindgrouplayout) (via a call to [`GPUDevice.createBindGroupLayout()`](gpudevice/createbindgrouplayout)) that defines the structure and purpose of GPU resources such as buffers that will be used in this pipeline. This layout is used as a template for bind groups to adhere to. In this case we give the pipeline access to a single memory buffer, tied to binding slot 0 (this matches the relevant binding number in our shader code — `@binding(0)`), usable in the compute stage of the pipeline, and with the buffer's purpose defined as `storage`.

 
```
const bindGroupLayout = device.createBindGroupLayout({
  entries: [
    {
      binding: 0,
      visibility: GPUShaderStage.COMPUTE,
      buffer: {
        type: "storage",
      },
    },
  ],
});

```
 Next we create a [`GPUBindGroup`](gpubindgroup) by calling [`GPUDevice.createBindGroup()`](gpudevice/createbindgroup). We pass this method call a descriptor object that specifies the bind group layout to base this bind group on, and the details of the variable to bind to the slot defined in the layout. In this case, we are declaring binding 0, and specifying that the `output` buffer we defined earlier should be bound to it.

 
```
const bindGroup = device.createBindGroup({
  layout: bindGroupLayout,
  entries: [
    {
      binding: 0,
      resource: {
        buffer: output,
      },
    },
  ],
});

```
  **Note:** You could retrieve an implicit layout to use when creating a bind group by calling the [`GPUComputePipeline.getBindGroupLayout()`](gpucomputepipeline/getbindgrouplayout) method. There is also a version available for render pipelines: see [`GPURenderPipeline.getBindGroupLayout()`](gpurenderpipeline/getbindgrouplayout).

 

### Create a compute pipeline



With the above all in place, we can now create a compute pipeline by calling [`GPUDevice.createComputePipeline()`](gpudevice/createcomputepipeline), passing it a pipeline descriptor object. This works in a similar way to creating a render pipeline. We describe the compute shader, specifying what module to find the code in and what the entry point is. We also specify a `layout` for the pipeline, in this case creating a layout based on the `bindGroupLayout` we defined earlier via a [`GPUDevice.createPipelineLayout()`](gpudevice/createpipelinelayout) call.

 
```
const computePipeline = device.createComputePipeline({
  layout: device.createPipelineLayout({
    bindGroupLayouts: [bindGroupLayout],
  }),
  compute: {
    module: shaderModule,
    entryPoint: "main",
  },
});

```
 One difference here from the render pipeline layout is that we are not specifying a primitive type, as we are not drawing anything.



### Running a compute pass



Running a compute pass is similar in structure to running a rendering pass, with some different commands. For a start, the pass encoder is created using [`GPUCommandEncoder.beginComputePass()`](gpucommandencoder/begincomputepass).

 When issuing the commands, we specify the pipeline to use in the same way as before, using [`GPUComputePassEncoder.setPipeline()`](gpucomputepassencoder/setpipeline). We then however use [`GPUComputePassEncoder.setBindGroup()`](gpucomputepassencoder/setbindgroup) to specify that we want to use our `bindGroup` to specify the data to use in the calculation, and [`GPUComputePassEncoder.dispatchWorkgroups()`](gpucomputepassencoder/dispatchworkgroups) to specify the number of GPU workgroups to use to run the calculations.

 We then signal the end of the render pass command list using [`GPURenderPassEncoder.end()`](gpurenderpassencoder/end).

 
```
passEncoder.setPipeline(computePipeline);
passEncoder.setBindGroup(0, bindGroup);
passEncoder.dispatchWorkgroups(Math.ceil(BUFFER\_SIZE / 64));

passEncoder.end();

```


### Reading the results back to JavaScript



Before submitting the encoded commands to the GPU for execution using [`GPUQueue.submit()`](gpuqueue/submit), we copy the contents of the `output` buffer to the `stagingBuffer` buffer using [`GPUCommandEncoder.copyBufferToBuffer()`](gpucommandencoder/copybuffertobuffer).

 
```
// Copy output buffer to staging buffer
commandEncoder.copyBufferToBuffer(
  output,
  0, // Source offset
  stagingBuffer,
  0, // Destination offset
  BUFFER\_SIZE
);

// End frame by passing array of command buffers to command queue for execution
device.queue.submit([commandEncoder.finish()]);

```
 Once the output data is available in the `stagingBuffer`, we use the [`GPUBuffer.mapAsync()`](gpubuffer/mapasync) method to map the data to intermediate memory, grab a reference to the mapped range using [`GPUBuffer.getMappedRange()`](gpubuffer/getmappedrange), copy the data into JavaScript, and then log it to the console. We also unmap the `stagingBuffer` once we are finished with it.

 
```
// map staging buffer to read results back to JS
await stagingBuffer.mapAsync(
  GPUMapMode.READ,
  0, // Offset
  BUFFER\_SIZE // Length
);

const copyArrayBuffer = stagingBuffer.getMappedRange(0, BUFFER\_SIZE);
const data = copyArrayBuffer.slice();
stagingBuffer.unmap();
console.log(new Float32Array(data));

```


GPU error handling
------------------



WebGPU calls are validated asynchronously in the GPU process. If errors are found, the problem call is marked as invalid on the GPU side. If another call is made that relies on the return value of an invalidated call, that object will also be marked as invalid, and so on. For this reason, errors in WebGPU are referred to as "contagious".

 Each [`GPUDevice`](gpudevice) instance maintains its own error scope stack. This stack is initially empty, but you can start pushing an error scope to the stack by invoking [`GPUDevice.pushErrorScope()`](gpudevice/pusherrorscope) to capture errors of a particular type.

 Once you are done capturing errors, you can end capture by invoking [`GPUDevice.popErrorScope()`](gpudevice/poperrorscope). This pops the scope from the stack and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to an object ([`GPUInternalError`](gpuinternalerror), [`GPUOutOfMemoryError`](gpuoutofmemoryerror), or [`GPUValidationError`](gpuvalidationerror)) describing the first error captured in the scope, or `null` if no errors were captured.

 We have attempted to provide useful information to help you understand why errors are occurring in your WebGPU code in "Validation" sections where appropriate, which list criteria to meet to avoid errors. See for example the [`GPUDevice.createBindGroup()` Validation section](gpudevice/createbindgroup#validation). Some of this information is complex; rather than repeat the spec, we have decided to just list error criteria that are:

 * Non-obvious, for example combinations of descriptor properties that produce validation errors. There is no point telling you to make sure you use the correct descriptor object structure. That is both obvious and vague.
* Developer-controlled. Some of the error criteria are purely based on internals and not really relevant to web developers.

 You can find more information about WebGPU error handling in the explainer — see [Object validity and destroyed-ness](https://gpuweb.github.io/gpuweb/explainer/#invalid-and-destroyed) and [Errors](https://gpuweb.github.io/gpuweb/explainer/#errors). [WebGPU Error Handling best practices](https://toji.dev/webgpu-best-practices/error-handling) provides useful real-world examples and advice.

  **Note:** The historic way of handling errors in WebGL is to provide a [`getError()`](webglrenderingcontext/geterror) method to return error information. This is problematic in that it returns errors synchronously, which is bad for performance — each call requires a round-trip to the GPU and requires all previously issued operations to be finished. Its state model is also flat, meaning that errors can leak between unrelated code. The creators of WebGPU were determined to improve on this.

 

Interfaces
----------


### Entry point for the API


 
[`Navigator.gpu`](navigator/gpu) / [`WorkerNavigator.gpu`](workernavigator/gpu)
  The entry point for the API — returns the [`GPU`](gpu) object for the current context.

  [`GPU`](gpu)  The starting point for using WebGPU. It can be used to return a [`GPUAdapter`](gpuadapter).

  [`GPUAdapter`](gpuadapter)  Represents a GPU adapter. From this you can request a [`GPUDevice`](gpudevice), adapter info, features, and limits.

  [`GPUAdapterInfo`](gpuadapterinfo)  Contains identifying information about an adapter.

  
### Configuring GPUDevices


 [`GPUDevice`](gpudevice)  Represents a logical GPU device. This is the main interface through which the majority of WebGPU functionality is accessed.

  [`GPUSupportedFeatures`](gpusupportedfeatures)  A [setlike](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) object that describes additional functionality supported by a [`GPUAdapter`](gpuadapter) or [`GPUDevice`](gpudevice).

  [`GPUSupportedLimits`](gpusupportedlimits)  Describes the limits supported by a [`GPUAdapter`](gpuadapter) or [`GPUDevice`](gpudevice).

  
### Configuring a rendering `<canvas>`


 
[`HTMLCanvasElement.getContext()`](htmlcanvaselement/getcontext) — the `"webgpu"` `contextType`
  Invoking `getContext()` with the `"webgpu"` `contextType` returns a [`GPUCanvasContext`](gpucanvascontext) object instance, which can then be configured with [`GPUCanvasContext.configure()`](gpucanvascontext/configure).

  [`GPUCanvasContext`](gpucanvascontext)  Represents the WebGPU rendering context of an [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element.

  
### Representing pipeline resources


 [`GPUBuffer`](gpubuffer)  Represents a block of memory that can be used to store raw data to use in GPU operations.

  [`GPUExternalTexture`](gpuexternaltexture)  A wrapper object containing an [`HTMLVideoElement`](htmlvideoelement) snapshot that can be used as a texture in GPU rendering operations.

  [`GPUSampler`](gpusampler)  Controls how shaders transform and filter texture resource data.

  [`GPUShaderModule`](gpushadermodule)  A reference to an internal shader module object, a container for WGSL shader code that can be submitted to the GPU to execution by a pipeline.

  [`GPUTexture`](gputexture)  A container used to store 1D, 2D, or 3D arrays of data, such as images, to use in GPU rendering operations.

  [`GPUTextureView`](gputextureview)  A view onto some subset of the texture subresources defined by a particular [`GPUTexture`](gputexture).

  
### Representing pipelines


 [`GPUBindGroup`](gpubindgroup)  Based on a [`GPUBindGroupLayout`](gpubindgrouplayout), a `GPUBindGroup` defines a set of resources to be bound together in a group and how those resources are used in shader stages.

  [`GPUBindGroupLayout`](gpubindgrouplayout)  Defines the structure and purpose of related GPU resources such as buffers that will be used in a pipeline, and is used as a template when creating [`GPUBindGroup`](gpubindgroup)s.

  [`GPUComputePipeline`](gpucomputepipeline)  Controls the compute shader stage and can be used in a [`GPUComputePassEncoder`](gpucomputepassencoder).

  [`GPUPipelineLayout`](gpupipelinelayout)  Defines the [`GPUBindGroupLayout`](gpubindgrouplayout)s used by a pipeline. [`GPUBindGroup`](gpubindgroup)s used with the pipeline during command encoding must have compatible [`GPUBindGroupLayout`](gpubindgrouplayout)s.

  [`GPURenderPipeline`](gpurenderpipeline)  Controls the vertex and fragment shader stages and can be used in a [`GPURenderPassEncoder`](gpurenderpassencoder) or [`GPURenderBundleEncoder`](gpurenderbundleencoder).

  
### Encoding and submitting commands to the GPU


 [`GPUCommandBuffer`](gpucommandbuffer)  Represents a recorded list of GPU commands that can be submitted to a [`GPUQueue`](gpuqueue) for execution.

  [`GPUCommandEncoder`](gpucommandencoder)  Represents a command encoder, used to encode commands to be issued to the GPU.

  [`GPUComputePassEncoder`](gpucomputepassencoder)  Encodes commands related to controlling the compute shader stage, as issued by a [`GPUComputePipeline`](gpucomputepipeline). Part of the overall encoding activity of a [`GPUCommandEncoder`](gpucommandencoder).

  [`GPUQueue`](gpuqueue)  controls execution of encoded commands on the GPU.

  [`GPURenderBundle`](gpurenderbundle)  A container for pre-recorded bundles of commands (see [`GPURenderBundleEncoder`](gpurenderbundleencoder)).

  [`GPURenderBundleEncoder`](gpurenderbundleencoder)  Used to pre-record bundles of commands. These can be reused in [`GPURenderPassEncoder`](gpurenderpassencoder)s via the [`executeBundles()`](gpurenderpassencoder/executebundles) method, as many times as required.

  [`GPURenderPassEncoder`](gpurenderpassencoder)  Encodes commands related to controlling the vertex and fragment shader stages, as issued by a [`GPURenderPipeline`](gpurenderpipeline). Part of the overall encoding activity of a [`GPUCommandEncoder`](gpucommandencoder).

  
### Running queries on rendering passes


 [`GPUQuerySet`](gpuqueryset)  Used to record the results of queries on passes, such as occlusion or timestamp queries.

  
### Debugging errors


 [`GPUCompilationInfo`](gpucompilationinfo)  An array of [`GPUCompilationMessage`](gpucompilationmessage) objects, generated by the GPU shader module compiler to help diagnose problems with shader code.

  [`GPUCompilationMessage`](gpucompilationmessage)  Represents a single informational, warning, or error message generated by the GPU shader module compiler.

  [`GPUDeviceLostInfo`](gpudevicelostinfo)  Returned when the [`GPUDevice.lost`](gpudevice/lost) [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) resolves, providing information as to why the device was lost.

  [`GPUError`](gpuerror)  The base interface for errors surfaced by [`GPUDevice.popErrorScope`](gpudevice/poperrorscope) and the [`uncapturederror`](gpudevice/uncapturederror_event) event.

  [`GPUInternalError`](gpuinternalerror)  One of the types of errors surfaced by [`GPUDevice.popErrorScope`](gpudevice/poperrorscope) and the [`GPUDevice`](gpudevice) [`uncapturederror`](gpudevice/uncapturederror_event) event. Indicates that an operation failed for a system or implementation-specific reason, even when all validation requirements were satisfied.

  [`GPUOutOfMemoryError`](gpuoutofmemoryerror)  One of the types of errors surfaced by [`GPUDevice.popErrorScope`](gpudevice/poperrorscope) and the [`GPUDevice`](gpudevice) [`uncapturederror`](gpudevice/uncapturederror_event) event. Indicates that there was not enough free memory to complete the requested operation.

  [`GPUPipelineError`](gpupipelineerror)  Describes a pipeline failure. The value received when a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) returned by a [`GPUDevice.createComputePipelineAsync()`](gpudevice/createcomputepipelineasync) or [`GPUDevice.createRenderPipelineAsync()`](gpudevice/createrenderpipelineasync) call rejects.

  [`GPUUncapturedErrorEvent`](gpuuncapturederrorevent)  The event object type for the [`GPUDevice`](gpudevice) [`uncapturederror`](gpudevice/uncapturederror_event) event.

  [`GPUValidationError`](gpuvalidationerror)  One of the types of errors surfaced by [`GPUDevice.popErrorScope`](gpudevice/poperrorscope) and the [`GPUDevice`](gpudevice) [`uncapturederror`](gpudevice/uncapturederror_event) event. Describes an application error indicating that an operation did not pass the WebGPU API's validation constraints.

  
Security requirements
---------------------


The whole API is available only in a [secure context](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts).


Examples
--------


* [Basic compute demo](https://mdn.github.io/dom-examples/webgpu-compute-demo/)
* [Basic render demo](https://mdn.github.io/dom-examples/webgpu-render-demo/)
* [WebGPU samples](https://webgpu.github.io/webgpu-samples/)

Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpu-interface](https://gpuweb.github.io/gpuweb/#gpu-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `WebGPU_API` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `getPreferredCanvasFormat` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `requestAdapter` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* [WebGPU best practices](https://toji.dev/webgpu-best-practices/)
* [WebGPU explainer](https://gpuweb.github.io/gpuweb/explainer)
* [WebGPU — All of the cores, none of the canvas](https://surma.dev/things/webgpu/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/WebGPU_API>

The WebSocket API (WebSockets)
==============================



The **WebSocket API** is an advanced technology that makes it possible to open a two-way interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply.

  **Note:** While a WebSocket connection is functionally somewhat similar to standard Unix-style sockets, they are not related.

 

Interfaces
----------


 [`WebSocket`](websocket)  The primary interface for connecting to a WebSocket server and then sending and receiving data on the connection.

  [`CloseEvent`](closeevent)  The event sent by the WebSocket object when the connection closes.

  [`MessageEvent`](messageevent)  The event sent by the WebSocket object when a message is received from the server.

  
Guides
------


* [Writing WebSocket client applications](websockets_api/writing_websocket_client_applications)
* [Writing WebSocket servers](websockets_api/writing_websocket_servers)
* [Writing a WebSocket server in C#](websockets_api/writing_websocket_server)
* [Writing a WebSocket server in Java](websockets_api/writing_a_websocket_server_in_java)

Tools
-----


* [AsyncAPI](https://www.asyncapi.com/): A specification for describing event-driven architectures based on protocols like WebSocket. You can use it to describe WebSocket-based APIs just as you would describe REST APIs with the OpenAPI specification. Learn [why you should consider using AsyncAPI with WebSocket](https://www.asyncapi.com/blog/websocket-part1) and [how to do so](https://www.asyncapi.com/blog/websocket-part2).
* [HumbleNet](https://hacks.mozilla.org/2017/06/introducing-humblenet-a-cross-platform-networking-library-that-works-in-the-browser/): A cross-platform networking library that works in the browser. It consists of a C wrapper around WebSockets and WebRTC that abstracts away cross-browser differences, facilitating the creation of multi-user networking functionality for games and other apps.
* [µWebSockets](https://github.com/uNetworking/uWebSockets): Highly scalable WebSocket server and client implementation for [C++11](https://isocpp.org/) and [Node.js](https://nodejs.org).
* [Socket.IO](https://socket.io): A long polling/WebSocket based third party transfer protocol for [Node.js](https://nodejs.org).
* [SocketCluster](https://socketcluster.io/): A pub/sub WebSocket framework for [Node.js](https://nodejs.org) with a focus on scalability.
* [WebSocket-Node](https://github.com/theturtle32/WebSocket-Node): A WebSocket server API implementation for [Node.js](https://nodejs.org).
* [Total.js](https://www.totaljs.com): Web application framework for [Node.js](https://nodejs.org/en/) (Example: [WebSocket chat](https://github.com/totaljs/examples/tree/master/websocket))
* [Faye](https://www.npmjs.com/package/faye-websocket): A [`WebSocket`](websocket) (two-ways connections) and [EventSource](eventsource) (one-way connections) for [Node.js](https://nodejs.org) Server and Client.
* [SignalR](https://dotnet.microsoft.com/en-us/apps/aspnet/signalr): SignalR will use WebSockets under the covers when it's available, and gracefully fallback to other techniques and technologies when it isn't, while your application code stays the same.
* [Caddy](https://caddyserver.com/): A web server capable of proxying arbitrary commands (stdin/stdout) as a websocket.
* [ws](https://github.com/websockets/ws): a popular WebSocket client & server library for [Node.js](https://nodejs.org/).
* [jsonrpc-bidirectional](https://github.com/bigstepinc/jsonrpc-bidirectional): Asynchronous RPC which, on a single connection, may have functions exported on the server and, and the same time, on the client (client may call server, server may also call client).
* [cowboy](https://github.com/ninenines/cowboy): Cowboy is a small, fast and modern HTTP server for Erlang/OTP with WebSocket support.
* [ZeroMQ](https://zeromq.org): ZeroMQ is embeddable networking library that carries messages across in-process, IPC, TCP, UDP, TIPC, multicast and WebSocket.
* [WebSocket King](https://websocketking.com): A client tool to help develop, test and work with WebSocket servers.
* [PHP WebSocket Server](https://github.com/napengam/phpWebSocketServer): Server written in PHP to handle connections via websockets wss:// or ws://and normal sockets over ssl:// ,tcp://
* [Channels](https://channels.readthedocs.io/en/stable/index.html): Django library that adds support for WebSockets (and other protocols that require long running asynchronous connections).
* [Flask-SocketIO](https://flask-socketio.readthedocs.io/en/latest/): gives Flask applications access to low latency bi-directional communications between the clients and the server.
* [Gorilla WebSocket](https://pkg.go.dev/github.com/gorilla/websocket): Gorilla WebSocket is a [Go](https://go.dev/) implementation of the WebSocket protocol.

Related Topics
--------------


* [AJAX](https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX)
* [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript)

Specifications
--------------




| Specification |
| --- |
| [WebSockets Standard # the-websocket-interface](https://websockets.spec.whatwg.org/#the-websocket-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `WebSocket` | 5 | 12 | 117–11 | 10 | 12.1 | 5 | 4.4 | 18 | 147–14 | 12.1 | 4.2 | 1.0 |
| `WebSockets_API` | 5 | 12 | 117–11Message size limited to 16 MB (see [bug 711205](https://bugzil.la/711205)). | 10 | 12.1 | 5 | 4.4 | 18 | 147–14Message size limited to 16 MB (see [bug 711205](https://bugzil.la/711205)). | 12.1 | 4.2 | 1.0 |
| `binaryType` | 15 | 12 | 11 | 10 | 12.1 | 6 | 4.4 | 18 | 14 | 12.1 | 6 | 1.0 |
| `bufferedAmount` | 5 | 12 | 7 | 10 | 12.1 | 5 | 4.4 | 18 | 7 | 12.1 | 4.2 | 1.0 |
| `close` | 5 | 12 | 7 | 10 | 12.1 | 5 | 4.4 | 18 | 7 | 12.1 | 4.2 | 1.0 |
| `close_event` | 5 | 12 | 7 | 10 | 12.1 | 5 | ≤37 | 18 | 7 | 12.1 | 4.2 | 1.0 |
| `error_event` | 5 | 12 | 7 | 10 | 12.1 | 5 | ≤37 | 18 | 7 | 12.1 | 4.2 | 1.0 |
| `extensions` | 16 | 12 | 8 | 10 | 12.1 | 6 | 4.4 | 18 | 8 | 12.1 | 6 | 1.0 |
| `message_event` | 5 | 12 | 7 | 10 | 12.1 | 5 | ≤37 | 18 | 7 | 12.1 | 4.2 | 1.0 |
| `open_event` | 5 | 12 | 7 | 10 | 12.1 | 5 | ≤37 | 18 | 7 | 12.1 | 4.2 | 1.0 |
| `protocol` | 15 | 12 | 7 | No | 12.1 | 6 | 4.4 | 18 | 7 | 12.1 | 6 | 1.0 |
| `protocol_rfc_6455` | 16 | 12 | 11 | 10 | 15 | 6 | ≤37 | 18 | 14 | 14 | 6 | 1.0 |
| `readyState` | 5 | 12 | 7 | 10 | 12.1 | 5 | 4.4 | 18 | 7 | 12.1 | 4.2 | 1.0 |
| `send` | 5 | 12 | 18See [bug 775368](https://bugzil.la/775368).11–18Only parameter of type `ArrayBuffer` and `String` supported.8–11Only parameter of type `String` supported.7–8Only parameter of type `String` supported. Returns `boolean`. | 10 | 12.1 | 5 | 4.4 | 18 | 18See [bug 775368](https://bugzil.la/775368).14–18Only parameter of type `ArrayBuffer` and `String` supported.8–14Only parameter of type `String` supported.7–8Only parameter of type `String` supported. Returns `boolean`. | 12.1 | 4.2 | 1.0 |
| `url` | 18 | 12 | 7 | No | 12.1 | 6 | 4.4 | 18 | 7 | 12.1 | 6 | 1.0 |
| `worker_support` | 5 | 12 | 37 | 10 | 12.1 | 5 | ≤37 | 18 | 37 | 12.1 | 5 | 1.0 |


See also
--------


* [RFC 6455 — The WebSocket Protocol](https://datatracker.ietf.org/doc/html/rfc6455)
* [WebSocket API Specification](https://websockets.spec.whatwg.org/)
* [Server-Sent Events](server-sent_events)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API>

Web Video Text Tracks Format (WebVTT)
=====================================


**Web Video Text Tracks Format** (**WebVTT**) is a format for displaying timed text tracks (such as subtitles or captions) using the [`<track>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track) element. The primary purpose of WebVTT files is to add text overlays to a [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video). WebVTT is a text based format, which must be encoded using [UTF-8](https://developer.mozilla.org/en-US/docs/Glossary/UTF-8). Where you can use spaces you can also use tabs. There is also a small API available to represent and manage these tracks and the data needed to perform the playback of the text at the correct times.


WebVTT files
------------



The MIME type of WebVTT is `text/vtt`.

 A WebVTT file (`.vtt`) contains cues, which can be either a single line or multiple lines, as shown below:

 
```
WEBVTT

00:01.000 --> 00:04.000
- Never drink liquid nitrogen.

00:05.000 --> 00:09.000
- It will perforate your stomach.
- You could die.

```


WebVTT body
-----------



The structure of a WebVTT consists of the following components, some of them optional, in this order:

 * An optional byte order mark (BOM).
* The string "`WEBVTT`".
* An optional text header to the right of `WEBVTT`.
	+ There must be at least one space after `WEBVTT`.
	+ You could use this to add a description to the file.
	+ You may use anything in the text header except newlines or the string "`-->`".
* A blank line, which is equivalent to two consecutive newlines.
* Zero or more cues or comments.
* Zero or more blank lines.



### Examples


* Simplest possible WebVTT file 
```
WEBVTT

```
* Very simple WebVTT file with a text header 
```
WEBVTT - This file has no cues.

```
* Common WebVTT example with a header and cues 
```
WEBVTT - This file has cues.

14
00:01:14.815 --> 00:01:18.114
- What?
- Where are we now?

15
00:01:18.171 --> 00:01:20.991
- This is big bat country.

16
00:01:21.058 --> 00:01:23.868
- [ Bats Screeching ]
- They won't get in your hair. They're after the bugs.

```

### Inner structure of a WebVTT file



Let's re-examine one of our previous examples, and look at the cue structure in a bit more detail.

 
```
WEBVTT

00:01.000 --> 00:04.000
- Never drink liquid nitrogen.

00:05.000 --> 00:09.000
- It will perforate your stomach.
- You could die.

```
 In the case of each cue:

 * The first line is started with a time, which is the starting time for showing the text that appears underneath.
* On the same line, we then have a string of "`-->`".
* We finish the first line with a second time, which is the ending time for showing the associated text.
* We can then have one or more lines that start with a hyphen (-), each containing part of the text track to be shown.

 We can also place comments in our `.vtt` file, to help us remember important information about the parts of our file. These should be on separate lines, starting with the string `NOTE`. You'll find more about these in the below section.

 It is important to not use "extra" blank lines within a cue, for example between the timings line and the cue payload. WebVTT is line based; a blank line will close the cue.



WebVTT comments
---------------



Comments are an optional component that can be used to add information to a WebVTT file. Comments are intended for those reading the file and are not seen by users. Comments may contain newlines but cannot contain a blank line, which is equivalent to two consecutive newlines. A blank line signifies the end of a comment.

 A comment cannot contain the string `-->`, the ampersand character (`&`), or the less-than sign (`<`). If you wish to use such characters, you need to escape them using for example `&amp;` for ampersand and `&lt;` for less-than. It is also recommended that you use the greater-than escape sequence (`&gt;`) instead of the greater-than character (`>`) to avoid confusion with tags.

 A comment consists of three parts:

 * The string `NOTE`.
* A space or a newline.
* Zero or more characters other than those noted above.



### Examples


* Common WebVTT example 
```
NOTE This is a comment

```
* Multi-line comment 
```
NOTE
One comment that is spanning
more than one line.

NOTE You can also make a comment
across more than one line this way.

```
* Common comment usage 
```
WEBVTT - Translation of that film I like

NOTE
This translation was done by Kyle so that
some friends can watch it with their parents.

1
00:02:15.000 --> 00:02:20.000
- Ta en kopp varmt te.
- Det är inte varmt.

2
00:02:20.000 --> 00:02:25.000
- Har en kopp te.
- Det smakar som te.

NOTE This last line may not translate well.

3
00:02:25.000 --> 00:02:30.000
- Ta en kopp

```

Styling WebVTT cues
-------------------


You can style WebVTT cues by looking for elements which match the [`::cue`](https://developer.mozilla.org/en-US/docs/Web/CSS/::cue) pseudo-element.


### Within site CSS




```
video::cue {
  background-image: linear-gradient(to bottom, dimgray, lightgray);
  color: papayawhip;
}

video::cue(b) {
  color: peachpuff;
}

```
 Here, all video elements are styled to use a gray linear gradient as their backgrounds, with a foreground color of `"papayawhip"`. In addition, text boldfaced using the [`<b>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/b) element are colored `"peachpuff"`.

 The HTML snippet below actually handles displaying the media itself.

 
```
<video controls autoplay src="video.webm">
  <track default src="track.vtt" />
</video>

```


### Within the WebVTT file itself



You can also define the style directly in the WebVTT file. In this case, you insert your CSS rules into the file with each rule preceded by the string `"STYLE"` all by itself on a line of text, as shown below:

 
```
WEBVTT

STYLE
::cue {
  background-image: linear-gradient(to bottom, dimgray, lightgray);
  color: papayawhip;
}
/* Style blocks cannot use blank lines nor "dash dash greater than" */

NOTE comment blocks can be used between style blocks.

STYLE
::cue(b) {
  color: peachpuff;
}

00:00:00.000 --> 00:00:10.000
- Hello <b>world</b>.

NOTE style blocks cannot appear after the first cue.

```
 We can also use identifiers inside WebVTT file, which can be used for defining a new style for some particular cues in the file. The example where we wanted the transcription text to be red highlighted and the other part to remain normal, we can define it as follows using CSS. Where it must be noted that the CSS uses escape sequences the way they are used in HTML pages:

 
```
WEBVTT

1
00:00.000 --> 00:02.000
That's an, an, that's an L!

crédit de transcription
00:04.000 --> 00:05.000
Transcrit par Célestes™

```
 
```
::cue(#\31) {
  color: lime;
}
::cue(#crédit\ de\ transcription) {
  color: red;
}

```
 Positioning of text tracks is also supported, by including positioning information after the timings in a cue, as seen below (see [Cue settings](#cue_settings) for more information):

 
```
WEBVTT

00:00:00.000 --> 00:00:04.000 position:10%,line-left align:left size:35%
Where did he go?

00:00:03.000 --> 00:00:06.500 position:90% align:right size:35%
I think he went down this lane.

00:00:04.000 --> 00:00:06.500 position:45%,line-right align:center size:35%
What are you waiting for?

```


WebVTT cues
-----------



A cue is a single subtitle block that has a single start time, end time, and textual payload. A cue consists of five components:

 * An optional cue identifier followed by a newline.
* Cue timings.
* Optional cue settings with at least one space before the first and between each setting.
* A single newline.
* The cue payload text.

 Here is an example of a cue:

 
```
1 - Title Crawl
00:00:05.000 --> 00:00:10.000 line:0 position:20% size:60% align:start
Some time ago in a place rather distant....

```


### Cue identifier



The identifier is a name that identifies the cue. It can be used to reference the cue from a script. It must not contain a newline and cannot contain the string "`-->`". It must end with a single new line. They do not have to be unique, although it is common to number them (e.g., 1, 2, 3).

 Here are a few examples:

 * A basic cue identifier 
```
1 - Title Crawl

```
* Common usage of identifiers 
```
WEBVTT

1
00:00:22.230 --> 00:00:24.606
This is the first subtitle.

2
00:00:30.739 --> 00:00:34.074
This is the second.

3
00:00:34.159 --> 00:00:35.743
Third

```



### Cue timings



A cue timing indicates when the cue is shown. It has a start and end time which are represented by timestamps. The end time must be greater than the start time, and the start time must be greater than or equal to all previous start times. Cues may have overlapping timings.

 If the WebVTT file is being used for chapters ([`<track>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track) [`kind`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track#kind) is `chapters`) then the file cannot have overlapping timings.

 Each cue timing contains five components:

 * Timestamp for start time.
* At least one space.
* The string "`-->`".
* At least one space.
* Timestamp for end time, which must be greater than the start time.

 The timestamps must be in one of two formats:

 * `mm:ss.ttt`
* `hh:mm:ss.ttt`

 Where the components are defined as follows:

  `hh`  Represents hours and must be at least two digits. It can be greater than two digits (e.g., `9999:00:00.000`).

  `mm`  Represents minutes and must be between 00 and 59, inclusive.

  `ss`  Represents seconds and must be between 00 and 59, inclusive.

  `ttt`  Represents milliseconds and must be between 000 and 999, inclusive.

   Here are a few cue timing examples:

 * Basic cue timing examples 
```
00:00:22.230 --> 00:00:24.606
00:00:30.739 --> 00:00:34.074
00:00:34.159 --> 00:00:35.743
00:00:35.827 --> 00:00:40.122

```
* Overlapping cue timing examples 
```
00:00:00.000 --> 00:00:10.000
00:00:05.000 --> 00:01:00.000
00:00:30.000 --> 00:00:50.000

```
* Non-overlapping cue timing examples 
```
00:00:00.000 --> 00:00:10.000
00:00:10.000 --> 00:01:00.581
00:01:00.581 --> 00:02:00.100
00:02:01.000 --> 00:02:01.000

```



### Cue settings



Cue settings are optional components used to position where the cue payload text will be displayed over the video. This includes whether the text is displayed horizontally or vertically. There can be zero or more of them, and they can be used in any order so long as each setting is used no more than once.

 The cue settings are added to the right of the cue timings. There must be one or more spaces between the cue timing and the first setting and between each setting. A setting's name and value are separated by a colon. The settings are case sensitive so use lower case as shown. There are five cue settings:

  `vertical`  Indicates that the text will be displayed vertically rather than horizontally, such as in some Asian languages. There are two possible values:

  `rl`  The writing direction is right to left

  `lr`  The writing direction is left to right

    `line`  If vertical is not set, specifies where the text appears vertically. If vertical is set, line specifies where text appears horizontally. Its value can be:

  a line number  The number is the height of the first line of the cue as it appears on the video. Positive numbers indicate top down and negative numbers indicate bottom up.

  a percentage  It must be an integer (i.e., no decimals) between 0 and 100 inclusive and must be followed by a percent sign (%).

   

| Line | `vertical` omitted | `vertical:rl` | `vertical:lr` |
| --- | --- | --- | --- |
| `line:0` | top | right | left |
| `line:-1` | bottom | left | right |
| `line:0%` | top | right | left |
| `line:100%` | bottom | left | right |

  `position`  Specifies where the text will appear horizontally. If vertical is set, position specifies where the text will appear vertically. The value is a percentage, that is an integer (no decimals) between 0 and 100 inclusive followed by a percent sign (%).

 

| Position | `vertical` omitted | `vertical:rl` | `vertical:lr` |
| --- | --- | --- | --- |
| `position:0%` | left | top | top |
| `position:100%` | right | bottom | bottom |

  `size`  Specifies the width of the text area. If vertical is set, size specifies the height of the text area. The value is a percentage, that is an integer (no decimals) between 0 and 100 inclusive followed by a percent sign (%).

 

| Size | `vertical` omitted | `vertical:rl` | `vertical:lr` |
| --- | --- | --- | --- |
| `size:100%` | full width | full height | full height |
| `size:50%` | half width | half height | half height |

  `align`  Specifies the alignment of the text. Text is aligned within the space given by the size cue setting if it is set.

 

| Align | `vertical` omitted | `vertical:rl` | `vertical:lr` |
| --- | --- | --- | --- |
| `align:start` | left | top | top |
| `align:center` | centered horizontally | centered vertically | centered vertically |
| `align:end` | right | bottom | bottom |

   Let's study an example of cue setting.

 The first line demonstrates no settings. The second line might be used to overlay text on a sign or label. The third line might be used for a title. The last line might be used for an Asian language.

 
```
00:00:05.000 --> 00:00:10.000
00:00:05.000 --> 00:00:10.000 line:63% position:72% align:start
00:00:05.000 --> 00:00:10.000 line:0 position:20% size:60% align:start
00:00:05.000 --> 00:00:10.000 vertical:rt line:-1 align:end

```


### Cue payload



The payload is where the main information or content is located. In normal usage the payload contains the subtitles to be displayed. The payload text may contain newlines but it cannot contain a blank line, which is equivalent to two consecutive newlines. A blank line signifies the end of a cue.

 A cue text payload cannot contain the string `-->`, the ampersand character (`&`), or the less-than sign (`<`). Instead use the escape sequence `&amp;` for ampersand and `&lt;` for less-than. It is also recommended that you use the greater-than escape sequence `&gt;` instead of the greater-than character (`>`) to avoid confusion with tags. If you are using the WebVTT file for metadata these restrictions do not apply.

 In addition to the three escape sequences mentioned above, there are fours others. They are listed in the table below.

 

| Name | Character | Escape sequence |
| --- | --- | --- |
| Ampersand | `&` | `&amp;` |
| Less-than | `<` | `&lt;` |
| Greater-than | `>` | `&gt;` |
| Left-to-right mark | *none* | `&lrm;` |
| Right-to-left mark | *none* | `&rlm;` |
| Non-breaking space |  | `&nbsp;` |



### Cue payload text tags



There are a number of tags, such as `<b>`, that can be used. However, if the WebVTT file is used in a [`<track>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track) element where the attribute [`kind`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track#kind) is `chapters` then you cannot use tags.

  Timestamp tag  The timestamp must be greater that the cue's start timestamp, greater than any previous timestamp in the cue payload, and less than the cue's end timestamp. The *active text* is the text between the timestamp and the next timestamp or to the end of the payload if there is not another timestamp in the payload. Any text before the *active text* in the payload is *previous text*. Any text beyond the *active text* is *future text*. This enables karaoke style captions.

 
```
1
00:16.500 --> 00:18.500
When the moon <00:17.500>hits your eye

1
00:00:18.500 --> 00:00:20.500
Like a <00:19.000>big-a <00:19.500>pizza <00:20.000>pie

1
00:00:20.500 --> 00:00:21.500
That's <00:00:21.000>amore

```
   The following tags are the HTML tags allowed in a cue and require opening and closing tags (e.g., `<b>text</b>`).

  Class tag (`<c></c>`)  Style the contained text using a CSS class.

 
```
<c.classname>text</c>

```
  Italics tag (`<i></i>`)  Italicize the contained text.

 
```
<i>text</i>

```
  Bold tag (`<b></b>`)  Bold the contained text.

 
```
<b>text</b>

```
  Underline tag (`<u></u>`)  Underline the contained text.

 
```
<u>text</u>

```
  Ruby tag (`<ruby></ruby>`)  Used with ruby text tags to display [ruby characters](https://en.wikipedia.org/wiki/Ruby_character) (i.e., small annotative characters above other characters).

 
```
<ruby>WWW<rt>World Wide Web</rt>oui<rt>yes</rt></ruby>

```
  Ruby text tag (`<rt></rt>`)  Used with ruby tags to display [ruby characters](https://en.wikipedia.org/wiki/Ruby_character) (i.e., small annotative characters above other characters).

 
```
<ruby>WWW<rt>World Wide Web</rt>oui<rt>yes</rt></ruby>

```
  Voice tag (`<v></v>`)  Similar to class tag, also used to style the contained text using CSS.

 
```
<v Bob>text</v>

```
  

Instance methods and properties
-------------------------------


The methods used in WebVTT are those which are used to alter the cue or region as the attributes for both interfaces are different. We can categorize them for better understanding relating to each interface in WebVTT:


### VTTCue



The methods which are available in the [`VTTCue`](vttcue) interface are:

 * [`getCueAsHTML()`](vttcue/getcueashtml) to get the HTML of that cue.
* A constructor, [`VTTCue()`](vttcue/vttcue) for creating new instances of this interface.

 Different properties allowing to read and set the characteristics of the cue, like its position, alignment or size are also available. Check [`VTTCue`](vttcue) for a complete list.



### VTTRegion


The [`VTTRegion`](vttregion) provides methods used for region are listed below along with description of their functionality, especially it allows to adjust the scrolling setting of all nodes present in the given region.


Tutorial on how to write a WebVTT file
--------------------------------------



There are few steps that can be followed to write a simple webVTT file. Before start, it must be noted that you can make use of a notepad and then save the file as '.vtt' file. Steps are given below:

 * Open a notepad.
* The first line of WebVTT is standardized similar to the way some other languages require you to put headers as the file starts to indicate the file type. On the very first line you have to write: 
```
WEBVTT

```
* Leave the second line blank, and on the third line the time for first cue is to be specified. For example, for a first cue starting at time 1 second and ending at 5 seconds, it is written as: 
```
00:01.000 --> 00:05.000

```
* On the next line you can write the caption for this cue which will run from the first second to the fifth second, inclusive.
* Following the similar steps, a complete WebVTT file for specific video or audio file can be made.



CSS pseudo-classes
------------------



CSS pseudo classes allow us to classify the type of object which we want to differentiate from other types of objects. It works in similar manner in WebVTT files as it works in HTML file.

 It is one of the good features supported by WebVTT is the localization and use of class elements which can be used in same way they are used in HTML and CSS to classify the style for particular type of objects, but here these are used for styling and classifying the Cues as shown below:

 
```
WEBVTT

04:02.500 --> 04:05.000
J'ai commencé le basket à l'âge de 13, 14 ans

04:05.001 --> 04:07.800
Sur les <i.foreignphrase><lang en>playground</lang></i>, ici à Montpellier

```
 In the above example it can be observed that we can use the identifier and pseudo class name for defining the language of caption, where `<i>` tag is for italics.

 The type of pseudo class is determined by the selector it is using and working is similar in nature as it works in HTML. Following CSS pseudo classes can be used:

 * `lang` (Language): e.g., `p:lang(it)`.
* `link`: e.g., `a:link`.
* `nth-last-child`: e.g., `p:nth-last-child(2)`.
* `nth-child(n)`: e.g., `p:nth-child(2)`.

 Where p and a are the tags which are used in HTML for paragraph and link, respectively and they can be replaced by identifiers which are used for Cues in WebVTT file.



Specifications
--------------




| Specification |
| --- |
| [WebVTT: The Web Video Text Tracks Format # the-vttcue-interface](https://w3c.github.io/webvtt/#the-vttcue-interface) |
| [HTML Standard # texttrack](https://html.spec.whatwg.org/multipage/media.html#texttrack) |
| [WebVTT: The Web Video Text Tracks Format # the-vttregion-interface](https://w3c.github.io/webvtt/#the-vttregion-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `VTTRegion` | No | No | 59 | No | No | 7 | No | No | 59 | No | 7 | No |
| `WebVTT_API` | No | No | 59 | No | No | 7 | No | No | 59 | No | 7 | No |
| `id` | No | No | 59 | No | No | 7 | No | No | 59 | No | 7 | No |
| `lines` | No | No | 59 | No | No | 12.1 | No | No | 59 | No | 12.2 | No |
| `regionAnchorX` | No | No | 59 | No | No | 7 | No | No | 59 | No | 7 | No |
| `regionAnchorY` | No | No | 59 | No | No | 7 | No | No | 59 | No | 7 | No |
| `scroll` | No | No | 59 | No | No | 7 | No | No | 59 | No | 7 | No |
| `viewportAnchorX` | No | No | 59 | No | No | 7 | No | No | 59 | No | 7 | No |
| `viewportAnchorY` | No | No | 59 | No | No | 7 | No | No | 59 | No | 7 | No |
| `width` | No | No | 59 | No | No | 7 | No | No | 59 | No | 7 | No |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `WebVTT_API` | 23 | 12 | 31Firefox versions before Firefox 50 didn't display captions when playing media without one or more video tracks being played. | 10 | ≤12.1 | 6 | 4.4 | 25 | 31 | ≤12.1 | 7 | 1.5 |
| `activeCues` | 23 | 12 | 31Starting in Firefox 69, cues are no longer incorrectly loaded when the `TextTrack`'s `mode` is `disabled`; if that's the case, the returned list is empty. | 10 | ≤12.1 | 6 | 4.4 | 25 | 31 | ≤12.1 | 7 | 1.5 |
| `addCue` | 23 | 12 | 31 | 10 | ≤12.1 | 6 | 4.4 | 25 | 31 | ≤12.1 | 7 | 1.5 |
| `cuechange_event` | 23 | 12 | 31 | 10 | ≤12.1 | 6 | 4.4 | 25 | 31 | ≤12.1 | 7 | 1.5 |
| `cues` | 23 | 12 | 31Starting in Firefox 69, cues are no longer incorrectly loaded when the `TextTrack`'s `mode` is `disabled`; if that's the case, the returned list is empty. | 10 | ≤12.1 | 6 | 4.4 | 25 | 31 | ≤12.1 | 7 | 1.5 |
| `id` | 33 | 18 | 31 | No | 20 | 8 | 4.4.3 | 33 | 31 | 20 | 8 | 2.0 |
| `inBandMetadataTrackDispatchType` | NoSee [bug 754093](https://crbug.com/754093). | 12–79 | 31 | No | NoSee [bug 754093](https://crbug.com/754093). | 8 | NoSee [bug 754093](https://crbug.com/754093). | NoSee [bug 754093](https://crbug.com/754093). | 31 | NoSee [bug 754093](https://crbug.com/754093). | 8 | NoSee [bug 754093](https://crbug.com/754093). |
| `kind` | 23 | 12 | 31 | 10 | ≤12.1 | 6 | 4.4 | 25 | 31 | ≤12.1 | 7 | 1.5 |
| `label` | 23 | 12 | 31 | 10 | ≤12.1 | 6 | 4.4 | 25 | 31 | ≤12.1 | 7 | 1.5 |
| `language` | 23 | 12 | 31 | 10 | ≤12.1 | 6 | 4.4 | 25 | 31 | ≤12.1 | 7 | 1.5 |
| `mode` | 23 | 12 | 31Before Firefox 52, using JavaScript to change the mode of a text track that's part of a media element would send one change event to the element's textTracks TextTrackList for each change, even if multiple changes are made in a single pass through the Firefox event loop. Starting in Firefox 52, these changes are reflected by a single event. | 10 | ≤12.1 | 6 | 4.4 | 25 | 31 | ≤12.1 | 7 | 1.5 |
| `removeCue` | 23 | 12 | 31 | 10 | ≤12.1 | 6 | 4.4 | 25 | 31 | ≤12.1 | 7 | 1.5 |
| `sourceBuffer` | No | No | No | No | No | 8 | No | No | No | No | 13Exposed in Mobile Safari on iPad but not on iPhone. | No |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `VTTCue` | 33 | 79 | 31 | No | 20 | 8 | 4.4.3 | 33 | 31 | 20 | 8 | 2.0 |
| `WebVTT_API` | 23 | 12 | 31 | 10 | ≤12.1 | 6 | 4.4 | 25 | 31 | ≤12.1 | 8 | 1.5 |
| `align` | 23 | 79 | 31 | No | ≤12.1 | 6 | 4.4 | 25 | 31 | ≤12.1 | 8 | 1.5 |
| `getCueAsHTML` | 23 | 12 | 31 | 10 | ≤12.1 | 6 | 4.4 | 25 | 31 | ≤12.1 | 8 | 1.5 |
| `line` | 23 | 79 | 31 | No | ≤12.1 | 6 | 4.4 | 25 | 31 | ≤12.1 | 8 | 1.5 |
| `lineAlign` | NoSee [bug 633690](https://crbug.com/633690). | NoSee [bug 633690](https://crbug.com/633690). | 31 | No | NoSee [bug 633690](https://crbug.com/633690). | 14.1 | NoSee [bug 633690](https://crbug.com/633690). | NoSee [bug 633690](https://crbug.com/633690). | 31 | NoSee [bug 633690](https://crbug.com/633690). | 14.5 | NoSee [bug 633690](https://crbug.com/633690). |
| `position` | 23 | 79 | 31 | No | ≤12.1 | 6 | 4.4 | 25 | 31 | ≤12.1 | 8 | 1.5 |
| `positionAlign` | NoSee [bug 633690](https://crbug.com/633690). | NoSee [bug 633690](https://crbug.com/633690). | 31 | No | NoSee [bug 633690](https://crbug.com/633690). | 14.1 | NoSee [bug 633690](https://crbug.com/633690). | NoSee [bug 633690](https://crbug.com/633690). | 31 | NoSee [bug 633690](https://crbug.com/633690). | 14.5 | NoSee [bug 633690](https://crbug.com/633690). |
| `region` | No | No | 59 | No | No | 14.1 | No | No | 59 | No | 14.5 | No |
| `size` | 23 | 79 | 31 | No | ≤12.1 | 6 | 4.4 | 25 | 31 | ≤12.1 | 8 | 1.5 |
| `snapToLines` | 23 | 79 | 31 | No | ≤12.1 | 6 | 4.4 | 25 | 31 | ≤12.1 | 8 | 1.5 |
| `text` | 23 | 12 | 31 | 10 | ≤12.1 | 6 | 4.4 | 25 | 31 | ≤12.1 | 8 | 1.5 |
| `vertical` | 23 | 79 | 31 | No | 15 | 6 | 4.4 | 25 | 31 | 14 | 8 | 1.5 |


### api.VTTCue


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.TextTrack


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.VTTRegion


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### Notes



Prior to Firefox 50, the `AlignSetting` enum (representing possible values for [`VTTCue.align`](vttcue/align)) incorrectly included the value `"middle"` instead of `"center"`. This has been corrected.

 WebVTT was implemented in Firefox 24 behind the preference `media.webvtt.enabled`, which is disabled by default; you can enable it by setting this preference to `true`. WebVTT is enabled by default starting in Firefox 31 and can be disabled by setting the preference to `false`.

 Prior to Firefox 58, the `REGION` keyword was creating [`VTTRegion`](vttregion) objects, but they were not being used. Firefox 58 now fully supports `VTTRegion` and its use; however, this feature is disabled by default behind the preference `media.webvtt.regions.enabled`; set it to `true` to enable region support in Firefox 58. Regions are enabled by default starting in Firefox 59 (see bugs [Firefox bug 1338030](https://bugzil.la/1338030) and [Firefox bug 1415805](https://bugzil.la/1415805)).



See also
--------


* The CSS [`::cue` and `::cue()`](https://developer.mozilla.org/en-US/docs/Web/CSS/::cue) pseudo-elements


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/WebVTT_API>

WebXR Device API
================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 **WebXR** is a group of standards which are used together to support rendering 3D scenes to hardware designed for presenting virtual worlds (**virtual reality**, or **VR**), or for adding graphical imagery to the real world, (**augmented reality**, or **AR**). The **WebXR Device API** implements the core of the WebXR feature set, managing the selection of output devices, render the 3D scene to the chosen device at the appropriate frame rate, and manage motion vectors created using input controllers.

 WebXR-compatible devices include fully-immersive 3D headsets with motion and orientation tracking, eyeglasses which overlay graphics atop the real-world scene passing through the frames, and handheld mobile phones which augment reality by capturing the world with a camera and augment that scene with computer-generated imagery.

 To accomplish these things, the WebXR Device API provides the following key capabilities:

 * Find compatible VR or AR output devices
* Render a 3D scene to the device at an appropriate frame rate
* (Optionally) mirror the output to a 2D display
* Create vectors representing the movements of input controls

 At the most basic level, a scene is presented in 3D by computing the perspective to apply to the scene in order to render it from the viewpoint of each of the user's eyes by computing the position of each eye and rendering the scene from that position, looking in the direction the user is currently facing. Each of these two images is rendered into a single framebuffer, with the left eye's rendered image on the left and the right eye's viewpoint rendered into the right half of the buffer. Once both eyes' perspectives on the scene have been rendered, the resulting framebuffer is delivered to the WebXR device to be presented to the user through their headset or other appropriate display device.

 While the older [WebVR API](webvr_api) was designed solely to support Virtual Reality (VR), WebXR provides support for both VR and Augmented Reality (AR) on the web. Support for AR functionality is added by the WebXR Augmented Reality Module.

 A typical XR device can have either 3 or 6 degrees of freedom and might or might not have an external positional sensor.

 The equipment may also include an accelerometer, barometer, or other sensors which are used to sense when the user moves through space, rotates their head, or the like.



WebXR reference docs
--------------------


 ### Initialization

 * [`navigator.xr`](navigator/xr)
* [`XRSystem`](xrsystem)
* `XRPermissionStatus`
* `Permissions-Policy`: [`xr-spatial-tracking`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy/xr-spatial-tracking)

 ### Session

 * [`XRSession`](xrsession)
* [`XRSessionEvent`](xrsessionevent)
* [`XRRenderState`](xrrenderstate)

 ### Frame loop

 * [`XRFrame`](xrframe)

 ### Spaces

 * [`XRSpace`](xrspace)
* [`XRReferenceSpace`](xrreferencespace)
* [`XRBoundedReferenceSpace`](xrboundedreferencespace)
* [`XRReferenceSpaceEvent`](xrreferencespaceevent)
* [`XRJointSpace`](xrjointspace)

 ### Views

 * [`XRView`](xrview)
* [`XRViewport`](xrviewport)

 ### Geometric primitives

 * [`XRRigidTransform`](xrrigidtransform)

 ### Pose

 * [`XRPose`](xrpose)
* [`XRJointPose`](xrjointpose)
* [`XRViewerPose`](xrviewerpose)

 ### Input

 * [`XRHand`](xrhand)
* [`XRInputSource`](xrinputsource)
* [`XRInputSourceArray`](xrinputsourcearray)
* [`XRInputSourceEvent`](xrinputsourceevent)
* [`XRInputSourcesChangeEvent`](xrinputsourceschangeevent)

 ### Layers

 * [`XRLayer`](xrlayer)
* [`XRLayerEvent`](xrlayerevent)
* [`XRCompositionLayer`](xrcompositionlayer)
* [`XRCubeLayer`](xrcubelayer)
* [`XRCylinderLayer`](xrcylinderlayer)
* [`XREquirectLayer`](xrequirectlayer)
* [`XRProjectionLayer`](xrprojectionlayer)
* [`XRQuadLayer`](xrquadlayer)
* [`XRMediaBinding`](xrmediabinding)

 ### WebGL binding

 * [`XRWebGLBinding`](xrwebglbinding)
* [`WebGLRenderingContext.makeXRCompatible()`](webglrenderingcontext/makexrcompatible)
* [`XRWebGLLayer`](xrwebgllayer)
* [`XRSubImage`](xrsubimage)
* [`XRWebGLSubImage`](xrwebglsubimage)

 ### Anchors

 * [`XRAnchor`](xranchor)
* [`XRAnchorSet`](xranchorset)

 ### Depth sensing

 * [`XRDepthInformation`](xrdepthinformation)
* [`XRCPUDepthInformation`](xrcpudepthinformation)
* [`XRWebGLDepthInformation`](xrwebgldepthinformation)

 ### Hit testing

 * [`XRHitTestSource`](xrhittestsource)
* [`XRTransientInputHitTestSource`](xrtransientinputhittestsource)
* [`XRHitTestResult`](xrhittestresult)
* [`XRTransientInputHitTestResult`](xrtransientinputhittestresult)
* [`XRRay`](xrray)

 ### Lighting estimation

 * [`XRLightEstimate`](xrlightestimate)
* [`XRLightProbe`](xrlightprobe)

 
Guides and tutorials
--------------------



The following guides and tutorials are a great resource to learn how to comprehend WebXR and the underlying 3D and VR/AR graphics concepts.

  ### Foundations and basics

 * [Fundamentals of WebXR](webxr_device_api/fundamentals)
* [Matrix math for the web](webgl_api/matrix_math_for_the_web)
* [WebXR application life cycle](webxr_device_api/lifecycle)

 ### Creating a mixed reality experience

 * [Starting up and shutting down a WebXR session](webxr_device_api/startup_and_shutdown)
* [Geometry and reference spaces in WebXR](webxr_device_api/geometry)
* [Spatial tracking in WebXR](webxr_device_api/spatial_tracking)
* [Rendering and the WebXR frame animation callback](webxr_device_api/rendering)
* [Viewpoints and viewers: Simulating cameras in WebXR](webxr_device_api/cameras)
* [A perspective retrospective for WebXR developers](webxr_device_api/perspective)
* [Lighting a WebXR setting](webxr_device_api/lighting)
* [Using bounded reference spaces](webxr_device_api/bounded_reference_spaces)

 ### Making it interactive

 * [Movement, orientation, and motion: A WebXR example](webxr_device_api/movement_and_motion)
* [Inputs and input sources](webxr_device_api/inputs)
* [Targeting and hit detection](webxr_device_api/targeting)

 ### Performance and security

 * [WebXR performance guide](webxr_device_api/performance)
* [Permissions and security for WebXR](webxr_device_api/permissions_and_security)

 

Specifications
--------------




| Specification |
| --- |
| [**WebXR Device API**](https://immersive-web.github.io/webxr/) ([Source](https://github.com/immersive-web/webxr), [Issues](https://github.com/immersive-web/webxr/issues), [Explainer](https://github.com/immersive-web/webxr/blob/master/explainer.md))  |
| [**WebXR Anchors Module**](https://immersive-web.github.io/anchors/) ([Source](https://github.com/immersive-web/anchors), [Issues](https://github.com/immersive-web/anchors/issues), [Explainer](https://github.com/immersive-web/anchors/blob/master/explainer.md))  |
| [**WebXR Augmented Reality Module**](https://immersive-web.github.io/webxr-ar-module/) ([Source](https://github.com/immersive-web/webxr-ar-module), [Issues](https://github.com/immersive-web/webxr-ar-module/issues), [Explainer](https://github.com/immersive-web/webxr-ar-module/blob/master/ar-module-explainer.md))  |
| [**WebXR Depth Sensing Module**](https://immersive-web.github.io/depth-sensing/) ([Source](https://github.com/immersive-web/depth-sensing), [Issues](https://github.com/immersive-web/depth-sensing/issues), [Explainer](https://github.com/immersive-web/depth-sensing/blob/master/explainer.md))  |
| [**WebXR DOM Overlays Module**](https://immersive-web.github.io/dom-overlays) ([Source](https://github.com/immersive-web/dom-overlays), [Issues](https://github.com/immersive-web/dom-overlays/issues), [Explainer](https://github.com/immersive-web/dom-overlays/blob/master/explainer.md))  |
| [**WebXR Gamepads Module**](https://immersive-web.github.io/webxr-gamepads-module/) ([Source](https://github.com/immersive-web/webxr-gamepads-module), [Issues](https://github.com/immersive-web/webxr-gamepads-module/issues), [Explainer](https://github.com/immersive-web/webxr-gamepads-module/blob/master/gamepads-module-explainer.md))  |
| [**WebXR Hand Input Module**](https://immersive-web.github.io/webxr-hand-input/) ([Source](https://github.com/immersive-web/webxr-hand-input), [Issues](https://github.com/immersive-web/webxr-hand-input/issues), [Explainer](https://github.com/immersive-web/webxr-hand-input/blob/master/explainer.md))  |
| [**WebXR Hit Test Module**](https://immersive-web.github.io/hit-test) ([Source](https://github.com/immersive-web/hit-test), [Issues](https://github.com/immersive-web/hit-test/issues), [Explainer](https://github.com/immersive-web/hit-test/blob/master/hit-testing-explainer.md))  |
| [**WebXR Layers API**](https://immersive-web.github.io/layers/) ([Source](https://github.com/immersive-web/layers), [Issues](https://github.com/immersive-web/layers/issues), [Explainer](https://github.com/immersive-web/layers/blob/master/explainer.md))  |
| [**WebXR Lighting Estimation API**](https://immersive-web.github.io/lighting-estimation/) ([Source](https://github.com/immersive-web/lighting-estimation), [Issues](https://github.com/immersive-web/lighting-estimation/issues), [Explainer](https://github.com/immersive-web/lighting-estimation/blob/master/lighting-estimation-explainer.md))  |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `WebXR_Device_API` | 79 | 79 | No | No | 66 | No | No | 79 | No | 57 | No | 11.2 |


See also
--------


* [Graphics on the web](https://developer.mozilla.org/en-US/docs/Web/Guide/Graphics)
* [Drawing graphics](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Drawing_graphics)
* [WebGL API](webgl_api): Accelerated 2D and 3D graphics on the web
* [Canvas API](canvas_api): 2D drawing for the web
* [Canvas tutorial](canvas_api/tutorial)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API>

Window Controls Overlay API
===========================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

  The Window Controls Overlay API gives Progressive Web Apps installed on desktop operating systems the ability to hide the default window title bar and display their own content over the full surface area of the app window, turning the control buttons (maximize, minimize, and close) into an overlay. 



Opting-in to the feature
------------------------



Before using this feature, the following conditions must be true:

 * The Web App Manifest's [`display_override`](https://developer.mozilla.org/en-US/docs/Web/Manifest/display_override) member must be set to `window-controls-overlay`.
* The Progressive Web App must be installed on a desktop operating system.



Main concepts
-------------



Progressive Web Apps installed on desktop devices can be displayed in standalone app windows, just like native apps. Here is what an application window looks like:

  ![Illustration of a PWA installed on desktop, with window control buttons, a title bar, and web content below that] 

 As seen above, the app window is made of two main areas:

 * The title bar area at the top.
* The application content area at the bottom, which displays the HTML content from the PWA.

 The title bar area contains the system-critical maximize, minimize, and close buttons (their position may vary across operating systems), the name of the application (which comes from the `<title>` HTML element in the page), and possibly user-agent-specific PWA buttons.

 With the Window Controls Overlay feature, Progressive Web Apps can display their web content over the whole app window surface area. Because the window control buttons and user-agent-specific PWA buttons must remain visible, they get turned into an overlay displayed on top of the web content.

  ![Illustration of a PWA installed on desktop with the Window Controls Overlay feature, with window control buttons, no title bar, and web content spanning the whole window] 

 The part of the title bar that normally contains the application name is hidden, and the area that it normally occupies becomes available via the Window Controls Overlay API.

 PWAs can use the API to position content in this area, and avoid having content hidden behind the control buttons overlay, similar to how web authors can account for the presence of notches on certain mobile devices.



CSS environment variables
-------------------------


 Progressive Web Apps can position their web content in the area that the title bar normally occupies by using the `titlebar-area-x`, `titlebar-area-y`, `titlebar-area-width`, and `titlebar-area-height` CSS environment variables. See [Using env() to ensure content is not obscured by window control buttons in desktop PWAs](https://developer.mozilla.org/en-US/docs/Web/CSS/env#using_env_to_ensure_content_is_not_obscured_by_window_control_buttons_in_desktop_pwas). 


Interfaces
----------


 [`WindowControlsOverlay`](windowcontrolsoverlay)  Provides information about the visibility and geometry of the title bar and an event to know whenever it changes.

  
Specifications
--------------




| Specification |
| --- |
| [Window Controls Overlay # windowcontrolsoverlay-interface](https://wicg.github.io/window-controls-overlay/#windowcontrolsoverlay-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Window_Controls_Overlay_API` | 105 | 105 | No | No | 91 | No | No | No | No | No | No | No |
| `geometrychange_event` | 105 | 105 | No | No | 91 | No | No | No | No | No | No | No |
| `getTitlebarAreaRect` | 105 | 105 | No | No | 91 | No | No | No | No | No | No | No |
| `visible` | 105 | 105 | No | No | 91 | No | No | No | No | No | No | No |


See also
--------


* [Customize the window controls overlay of your PWA's title bar](https://web.dev/window-controls-overlay/)
* [Breaking Out of the Box](https://alistapart.com/article/breaking-out-of-the-box/)
* [Display content in the title bar](https://docs.microsoft.com/microsoft-edge/progressive-web-apps-chromium/how-to/window-controls-overlay)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Window_Controls_Overlay_API>

XMLHttpRequest
==============



`XMLHttpRequest` (XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing.

 `XMLHttpRequest` is used heavily in [AJAX](https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX) programming.


 EventTarget XMLHttpRequestEventTarget XMLHttpRequest Despite its name, `XMLHttpRequest` can be used to retrieve any type of data, not just XML.

 If your communication needs to involve receiving event data or message data from a server, consider using [server-sent events](server-sent_events) through the [`EventSource`](eventsource) interface. For full-duplex communication, [WebSockets](websockets_api) may be a better choice.


 **Note:** This feature is available in [Web Workers](web_workers_api), except for [Service Workers](service_worker_api)

 

Constructor
-----------


 [`XMLHttpRequest()`](xmlhttprequest/xmlhttprequest)  The constructor initializes an `XMLHttpRequest`. It must be called before any other method calls.

  
Instance properties
-------------------



*This interface also inherits properties of [`XMLHttpRequestEventTarget`](xmlhttprequesteventtarget) and of [`EventTarget`](eventtarget).*

  
[`XMLHttpRequest.readyState`](xmlhttprequest/readystate) Read only 
  Returns a number representing the state of the request.

  
[`XMLHttpRequest.response`](xmlhttprequest/response) Read only 
  Returns an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), a [`Blob`](blob), a [`Document`](document), a JavaScript object, or a string, depending on the value of [`XMLHttpRequest.responseType`](xmlhttprequest/responsetype), that contains the response entity body.

  
[`XMLHttpRequest.responseText`](xmlhttprequest/responsetext) Read only 
  Returns a string that contains the response to the request as text, or `null` if the request was unsuccessful or has not yet been sent.

  [`XMLHttpRequest.responseType`](xmlhttprequest/responsetype)  Specifies the type of the response.

  
[`XMLHttpRequest.responseURL`](xmlhttprequest/responseurl) Read only 
  Returns the serialized URL of the response or the empty string if the URL is null.

  
[`XMLHttpRequest.responseXML`](xmlhttprequest/responsexml) Read only 
  Returns a [`Document`](document) containing the response to the request, or `null` if the request was unsuccessful, has not yet been sent, or cannot be parsed as XML or HTML. Not available in [Web Workers](web_workers_api).

  
[`XMLHttpRequest.status`](xmlhttprequest/status) Read only 
  Returns the [HTTP response status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) of the request.

  
[`XMLHttpRequest.statusText`](xmlhttprequest/statustext) Read only 
  Returns a string containing the response string returned by the HTTP server. Unlike [`XMLHttpRequest.status`](xmlhttprequest/status), this includes the entire text of the response message ("`OK`", for example).

  **Note:** According to the HTTP/2 specification [RFC 7540, section 8.1.2.4: Response Pseudo-Header Fields](https://datatracker.ietf.org/doc/html/rfc7540#section-8.1.2.4), HTTP/2 does not define a way to carry the version or reason phrase that is included in an HTTP/1.1 status line.

   [`XMLHttpRequest.timeout`](xmlhttprequest/timeout)  The time in milliseconds a request can take before automatically being terminated.

  
[`XMLHttpRequest.upload`](xmlhttprequest/upload) Read only 
  A [`XMLHttpRequestUpload`](xmlhttprequestupload) representing the upload process.

  [`XMLHttpRequest.withCredentials`](xmlhttprequest/withcredentials)  Returns `true` if cross-site `Access-Control` requests should be made using credentials such as cookies or authorization headers; otherwise `false`.

  

### Non-standard properties


 
[`XMLHttpRequest.channel`](xmlhttprequest/channel) Read only 
  The channel used by the object when performing the request.

  
[`XMLHttpRequest.mozAnon`](xmlhttprequest/mozanon) Read only 
  A boolean. If true, the request will be sent without cookie and authentication headers.

  
[`XMLHttpRequest.mozSystem`](xmlhttprequest/mozsystem) Read only 
  A boolean. If true, the same origin policy will not be enforced on the request.

  [`XMLHttpRequest.mozBackgroundRequest`](xmlhttprequest/mozbackgroundrequest)  A boolean. It indicates whether or not the object represents a background service request.

  
Instance methods
----------------


 [`XMLHttpRequest.abort()`](xmlhttprequest/abort)  Aborts the request if it has already been sent.

  [`XMLHttpRequest.getAllResponseHeaders()`](xmlhttprequest/getallresponseheaders)  Returns all the response headers, separated by [CRLF](https://developer.mozilla.org/en-US/docs/Glossary/CRLF), as a string, or `null` if no response has been received.

  [`XMLHttpRequest.getResponseHeader()`](xmlhttprequest/getresponseheader)  Returns the string containing the text of the specified header, or `null` if either the response has not yet been received or the header doesn't exist in the response.

  [`XMLHttpRequest.open()`](xmlhttprequest/open)  Initializes a request.

  [`XMLHttpRequest.overrideMimeType()`](xmlhttprequest/overridemimetype)  Overrides the MIME type returned by the server.

  [`XMLHttpRequest.send()`](xmlhttprequest/send)  Sends the request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent.

  [`XMLHttpRequest.setRequestHeader()`](xmlhttprequest/setrequestheader)  Sets the value of an HTTP request header. You must call `setRequestHeader()` after [`open()`](xmlhttprequest/open), but before [`send()`](xmlhttprequest/send).

  
Events
------


 [`abort`](xmlhttprequest/abort_event)   Fired when a request has been aborted, for example because the program called [`XMLHttpRequest.abort()`](xmlhttprequest/abort). Also available via the `onabort` event handler property. 

  [`error`](xmlhttprequest/error_event)   Fired when the request encountered an error. Also available via the `onerror` event handler property. 

  [`load`](xmlhttprequest/load_event)   Fired when an `XMLHttpRequest` transaction completes successfully. Also available via the `onload` event handler property. 

  [`loadend`](xmlhttprequest/loadend_event)   Fired when a request has completed, whether successfully (after [`load`](xmlhttprequest/load_event)) or unsuccessfully (after [`abort`](xmlhttprequest/abort_event) or [`error`](xmlhttprequest/error_event)). Also available via the `onloadend` event handler property. 

  [`loadstart`](xmlhttprequest/loadstart_event)   Fired when a request has started to load data. Also available via the `onloadstart` event handler property. 

  [`progress`](xmlhttprequest/progress_event)   Fired periodically when a request receives more data. Also available via the `onprogress` event handler property. 

  [`readystatechange`](xmlhttprequest/readystatechange_event)   Fired whenever the [`readyState`](xmlhttprequest/readystate) property changes. Also available via the `onreadystatechange` event handler property. 

  [`timeout`](xmlhttprequest/timeout_event)   Fired when progress is terminated due to preset time expiring. Also available via the `ontimeout` event handler property. 

  
Specifications
--------------




| Specification |
| --- |
| [XMLHttpRequest Standard # interface-xmlhttprequest](https://xhr.spec.whatwg.org/#interface-xmlhttprequest) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `XMLHttpRequest` | 1 | 12 | 1 | 7 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `XMLHttpRequest` | 1 | 12 | 1 | 75Implemented via `ActiveXObject('Microsoft.XMLHTTP')` | 8 | 1.2 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 |
| `abort` | 1 | 12 | 1 | 5 | ≤12.1 | 1.2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `abort_event` | 1 | 12 | 3.5 | 10 | ≤12.1 | 1.3 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `authorization_removed_cross_origin` | No | No | 111 | No | No | 16.1 | No | No | 111 | No | 16.1 | No |
| `error_event` | 1 | 12 | 1 | 10 | ≤12.1 | 1.3 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `getAllResponseHeaders` | 1 | 12 | 1Starting from Firefox 49, empty headers are returned as empty strings in case the preference `network.http.keep_empty_response_headers_as_empty_string` is set to `true`, defaulting to `false`. Before Firefox 49 empty headers had been ignored. Since Firefox 50 the preference defaults to `true`. | 5 | ≤12.1 | 1.2 | 4.4 | 18 | 4Starting from Firefox 49, empty headers are returned as empty strings in case the preference `network.http.keep_empty_response_headers_as_empty_string` is set to `true`, defaulting to `false`. Before Firefox 49 empty headers had been ignored. Since Firefox 50 the preference defaults to `true`. | ≤12.1 | 1 | 1.0 |
| `getResponseHeader` | 1 | 12 | 1Starting from Firefox 49, empty headers are returned as empty strings in case the preference `network.http.keep_empty_response_headers_as_empty_string` is set to `true`, defaulting to `false`. Before Firefox 49 empty headers had been ignored. Since Firefox 50 the preference defaults to `true`. | 5 | 8 | 1.2 | 4.4 | 18 | 4Starting from Firefox 49, empty headers are returned as empty strings in case the preference `network.http.keep_empty_response_headers_as_empty_string` is set to `true`, defaulting to `false`. Before Firefox 49 empty headers had been ignored. Since Firefox 50 the preference defaults to `true`. | 10.1 | 1 | 1.0 |
| `load_event` | 1 | 12 | 1 | 9 | ≤12.1 | 1.3 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `loadend_event` | 18 | 12 | 5 | 10 | ≤12.1 | 4 | 4.4 | 18 | 5 | ≤12.1 | 3 | 1.0 |
| `loadstart_event` | 1 | 12 | 3.5 | 10 | ≤12.1 | 1.3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `open` | 1 | 12 | 1Starting in Firefox 30, synchronous requests on the main thread have been deprecated due to their negative impact on performance and the user experience. Therefore, the `async` parameter may not be `false` except in a `Worker`. | 5 | 8 | 1.2 | 4.4 | 18 | 4Starting in Firefox 30, synchronous requests on the main thread have been deprecated due to their negative impact on performance and the user experience. Therefore, the `async` parameter may not be `false` except in a `Worker`. | 10.1 | 1 | 1.0 |
| `overrideMimeType` | 1 | 12 | 1 | 115Implemented via `ActiveXObject` | ≤12.1 | 1.2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `progress_event` | 1 | 12 | 1 | 10 | ≤12.1 | 3 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `readyState` | 1 | 12 | 1 | 7 | 8 | 1.2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `readystatechange_event` | 1 | 12 | 1 | 5 | 9 | 1.2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `response` | 9 | 12 | 6 | 10 | 11.6 | 5.1 | 3 | 18 | 6 | 12 | 5 | 1.0 |
| `responseText` | 1 | 12 | 1 | 5Before Internet Explorer 10, the value of `XMLHttpRequest.responseText` could be read only once the request was complete. | 8 | 1.2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `responseType` | 31 | 12 | 6 | 10 | 1812–15 | 5.1 | 4.4.3 | 31 | 50 | 1812–14 | 5 | 2.0 |
| `responseURL` | 37 | 14 | 32 | No | 24 | 8 | 37 | 37 | 32 | 24 | 8 | 3.0 |
| `responseXML` | 1 | 12 | 1Before Firefox 51, an error parsing the received data added a `<parsererror>` node to the top of the `Document` and then returned the `Document` in whatever state it happens to be in. This was inconsistent with the specification. Starting with Firefox 51, this scenario now correctly returns `null` as per the spec. | 7 | ≤12.1 | 3 | ≤37 | 18 | 4Before Firefox 51, an error parsing the received data added a `<parsererror>` node to the top of the `Document` and then returned the `Document` in whatever state it happens to be in. This was inconsistent with the specification. Starting with Firefox 51, this scenario now correctly returns `null` as per the spec. | ≤12.1 | 1 | 1.0 |
| `send` | 1 | 12 | 1 | 5 | 8 | 1.2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `setRequestHeader` | 1 | 12 | 1 | 5 | 8 | 1.2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `status` | 1 | 12 | 1 | 7Internet Explorer version 5 and 6 supported ajax calls using `ActiveXObject()` | 8 | 1.2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `statusText` | 1 | 12 | 1 | 7Internet Explorer version 5 and 6 supported ajax calls using `ActiveXObject()` | ≤12.1 | 1.2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `timeout` | 29 | 12 | 12 | 8 | 1712–16 | 7 | 4.4 | 29 | 14 | 1812–16 | 7 | 2.0 |
| `timeout_event` | 29 | 12 | 12 | 8 | 16 | 7 | 4.4 | 29 | 14 | 16 | 7 | 1.0 |
| `upload` | 2 | 12 | 3.5 | 10 | ≤12.1 | 4 | 4.4 | 18 | 4 | ≤12.1 | 3 | 1.0 |
| `withCredentials` | 3 | 12 | 3.5Starting with Firefox 11, it's no longer supported to use the `withCredentials` attribute when performing synchronous requests. Attempting to do so throws an `NS_ERROR_DOM_INVALID_ACCESS_ERR` exception. | 10Internet Explorer versions 8 and 9 supported cross-domain requests (CORS) using [`XDomainRequest`](https://developer.mozilla.org/docs/Web/API/XDomainRequest). | 12 | 4 | ≤37 | 18 | 4Starting with Firefox 11, it's no longer supported to use the `withCredentials` attribute when performing synchronous requests. Attempting to do so throws an `NS_ERROR_DOM_INVALID_ACCESS_ERR` exception. | 12 | 3.2 | 1.0 |
| `worker_support` | 4 | 12 | 3.5 | 10 | 10.6 | 4 | 4 | 18 | 4 | 11 | 5 | 1.0 |


See also
--------


* [`XMLSerializer`](xmlserializer): Serializing a DOM tree into XML
* MDN tutorials covering `XMLHttpRequest`:
	+ [Ajax — Getting Started](https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started)
	+ [Using XMLHttpRequest](xmlhttprequest/using_xmlhttprequest)
	+ [HTML in XMLHttpRequest](xmlhttprequest/html_in_xmlhttprequest)
	+ [Fetch API](fetch_api)
* [New Tricks in XMLHttpRequest2 (2011)](https://web.dev/xhr2/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest>

AbortSignal
===========



The `AbortSignal` interface represents a signal object that allows you to communicate with a DOM request (such as a fetch request) and abort it if required via an [`AbortController`](abortcontroller) object.


 EventTarget AbortSignal

Instance properties
-------------------



*The AbortSignal interface may also inherit properties from its parent interface, [`EventTarget`](eventtarget).*

  
[`AbortSignal.aborted`](abortsignal/aborted) Read only 
  A [Boolean](https://developer.mozilla.org/en-US/docs/Glossary/Boolean) that indicates whether the request(s) the signal is communicating with is/are aborted (`true`) or not (`false`).

  
[`AbortSignal.reason`](abortsignal/reason) Read only 
  A JavaScript value providing the abort reason, once the signal has aborted.

  

Static methods
--------------


 [`AbortSignal.abort()`](abortsignal/abort)  Returns an `AbortSignal` instance that is already set as aborted.

  [`AbortSignal.timeout()`](abortsignal/timeout)  Returns an `AbortSignal` instance that will automatically abort after a specified time.

  
Instance methods
----------------



*The `AbortSignal` interface may also inherit methods from its parent interface, [`EventTarget`](eventtarget).*

  [`AbortSignal.throwIfAborted()`](abortsignal/throwifaborted)  Throws the signal's abort [`reason`](abortsignal/reason) if the signal has been aborted; otherwise it does nothing.

  

Events
------



Listen to this event using [`addEventListener()`](eventtarget/addeventlistener) or by assigning an event listener to the `oneventname` property of this interface.

  [`abort`](abortsignal/abort_event)   Invoked when the DOM requests the signal is communicating with is/are aborted. Also available via the `onabort` property. 

  

Examples
--------


### Aborting a fetch operation using an explicit signal



The following snippet shows how we might use a signal to abort downloading a video using the [Fetch API](fetch_api).

 We first create an abort controller using the [`AbortController()`](abortcontroller/abortcontroller) constructor, then grab a reference to its associated [`AbortSignal`](abortsignal) object using the [`AbortController.signal`](abortcontroller/signal) property.

  When the [fetch request](fetch) is initiated, we pass in the `AbortSignal` as an option inside the request's options object (the `{signal}` below). This associates the signal and controller with the fetch request, and allows us to abort it by calling [`AbortController.abort()`](abortcontroller/abort). Below you can see that the fetch operation is aborted in the second event listener, which triggered when the abort button (`abortBtn`) is clicked. 

 
```
const controller = new AbortController();
const signal = controller.signal;

const url = "video.mp4";
const downloadBtn = document.querySelector(".download");
const abortBtn = document.querySelector(".abort");

downloadBtn.addEventListener("click", fetchVideo);

abortBtn.addEventListener("click", () => {
  controller.abort();
  console.log("Download aborted");
});

function fetchVideo() {
  fetch(url, { signal })
    .then((response) => {
      console.log("Download complete", response);
    })
    .catch((err) => {
      console.error(`Download error: ${err.message}`);
    });
}

```
  **Note:** When `abort()` is called, the `fetch()` promise rejects with an "`AbortError`" `DOMException`.

  You can find a [full working example on GitHub](https://github.com/mdn/dom-examples/tree/main/abort-api); you can also see it [running live](https://mdn.github.io/dom-examples/abort-api/).



### Aborting a fetch operation with a timeout



 If you need to abort the operation on timeout then you can use the static [`AbortSignal.timeout()`](abortsignal/timeout) method. This returns an `AbortSignal` that will automatically timeout after a certain number of milliseconds. 

  The code snippet below shows how you would either succeed in downloading a file, or handle a timeout error after 5 seconds. Note that when there is a timeout the `fetch()` promise rejects with a "`TimeoutError`" `DOMException`. This allows code to differentiate between timeouts (for which user notification is probably required), and user aborts. 

 
```
const url = "video.mp4";

try {
  const res = await fetch(url, { signal: AbortSignal.timeout(5000) });
  const result = await res.blob();
  // …
} catch (err) {
  if (err.name === "TimeoutError") {
    console.error("Timeout: It took more than 5 seconds to get the result!");
  } else if (err.name === "AbortError") {
    console.error(
      "Fetch aborted by user action (browser stop button, closing tab, etc."
    );
  } else if (err.name === "TypeError") {
    console.error("AbortSignal.timeout() method is not supported");
  } else {
    // A network error, or some other problem.
    console.error(`Error: type: ${err.name}, message: ${err.message}`);
  }
}

```


### Aborting a fetch with timeout or explicit abort



`fetch()` isn't designed to combine multiple signals, so you can't abort a download "directly" due to either of [`AbortController.abort()`](abortcontroller/abort) being called or an `AbortSignal` timeout (though as in the preceding example, a timeout signal will abort if triggered by *inbuilt* browser mechanisms like a stop button).

  To trigger on multiple signals they must be daisy chained. The code snippet below shows how you might call [`AbortController.abort()`](abortcontroller/abort) in the handler for a separate timer. 

 
```
try {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), 5000);
  const res = await fetch(url, { signal: controller.signal });
  const body = await res.json();
} catch (e) {
  if (e.name === "AbortError") {
    // Notify the user of abort.
    // Note this will never be a timeout error!
  } else {
    // A network error, or some other problem.
    console.log(`Type: ${e.name}, Message: ${e.message}`);
  }
} finally {
  clearTimeout(timeoutId);
}

```
  **Note:** Unlike when using [`AbortSignal.timeout()`](abortsignal/timeout), there is no way to tell whether the final abort was caused by a timeout.

 

Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-AbortSignal](https://dom.spec.whatwg.org/#interface-AbortSignal) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AbortSignal` | 66 | 16 | 57 | No | 53 | 11.1 | 66 | 66 | 57 | 47 | 11.3 | 9.0 |
| `abort` | 93 | 93 | 88 | No | 79 | 15 | 93 | 93 | 88 | 66 | 15 | 17.0 |
| `abort_event` | 66 | 16 | 57 | No | 53 | 11.1 | 66 | 66 | 57 | 47 | 11.3 | 9.0 |
| `aborted` | 66 | 16 | 57 | No | 53 | 11.1 | 66 | 66 | 57 | 47 | 11.3 | 9.0 |
| `reason` | 98 | 98 | 97 | No | 84 | 15.4 | 98 | 98 | 97 | 68 | 15.4 | 18.0 |
| `throwIfAborted` | 100 | 100 | 97 | No | 86 | 15.4 | 100 | 100 | 97 | 69 | 15.4 | 19.0 |
| `timeout` | 103 | 103 | 100 | No | 89 | 16 | 103 | 103 | 100 | 71 | 16 | 20.0 |


See also
--------


* [Fetch API](fetch_api)
* [Abortable Fetch](https://developer.chrome.com/blog/abortable-fetch/) by Jake Archibald


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal>

AbsoluteOrientationSensor
=========================



The `AbsoluteOrientationSensor` interface of the [Sensor APIs](sensor_apis) describes the device's physical orientation in relation to the Earth's reference coordinate system.

 To use this sensor, the user must grant permission to the `'accelerometer'`, `'gyroscope'`, and `'magnetometer'` device sensors through the [Permissions API](permissions_api).

 This feature may be blocked by a [Permissions Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy) set on your server.


 EventTarget Sensor OrientationSensor AbsoluteOrientationSensor

Constructor
-----------


 [`AbsoluteOrientationSensor()`](absoluteorientationsensor/absoluteorientationsensor)  Creates a new `AbsoluteOrientationSensor` object.

  
Instance properties
-------------------


*No specific properties; inherits properties from its ancestors [`OrientationSensor`](orientationsensor) and [`Sensor`](sensor).*


Instance methods
----------------


*No specific methods; inherits methods from its ancestors [`OrientationSensor`](orientationsensor) and [`Sensor`](sensor).*


Events
------


*No specific events; inherits methods from its ancestor, [`Sensor`](sensor).*


Examples
--------


### Basic Example



The following example, which is loosely based on [Intel's Orientation Phone demo](https://intel.github.io/generic-sensor-demos/orientation-phone/), instantiates an `AbsoluteOrientationSensor` with a frequency of 60 times a second. On each reading it uses [`OrientationSensor.quaternion`](orientationsensor/quaternion) to rotate a visual model of a phone.

 
```
const options = { frequency: 60, referenceFrame: "device" };
const sensor = new AbsoluteOrientationSensor(options);

sensor.addEventListener("reading", () => {
  // model is a Three.js object instantiated elsewhere.
  model.quaternion.fromArray(sensor.quaternion).inverse();
});
sensor.addEventListener("error", (error) => {
  if (event.error.name === "NotReadableError") {
    console.log("Sensor is not available.");
  }
});
sensor.start();

```


### Permissions Example



Using orientation sensors requires requesting permissions for multiple device sensors. Because the [`Permissions`](permissions) interface uses promises, a good way to request permissions is to use [`Promise.all`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all).

 
```
const sensor = new AbsoluteOrientationSensor();
Promise.all([
  navigator.permissions.query({ name: "accelerometer" }),
  navigator.permissions.query({ name: "magnetometer" }),
  navigator.permissions.query({ name: "gyroscope" }),
]).then((results) => {
  if (results.every((result) => result.state === "granted")) {
    sensor.start();
    // …
  } else {
    console.log("No permissions to use AbsoluteOrientationSensor.");
  }
});

```


Specifications
--------------




| Specification |
| --- |
| [Orientation Sensor # absoluteorientationsensor-interface](https://w3c.github.io/orientation-sensor/#absoluteorientationsensor-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AbsoluteOrientationSensor` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |
| `AbsoluteOrientationSensor` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AbsoluteOrientationSensor>

AbstractRange
=============



The `AbstractRange` abstract interface is the base class upon which all [DOM](https://developer.mozilla.org/en-US/docs/Glossary/DOM) range types are defined. A **range** is an object that indicates the start and end points of a section of content within the document.

  **Note:** As an abstract interface, you will not directly instantiate an object of type `AbstractRange`. Instead, you will use the [`Range`](range) or [`StaticRange`](staticrange) interfaces. To understand the difference between those two interfaces, and how to choose which is appropriate for your needs, consult each interface's documentation.

 

Instance properties
-------------------


 
[`collapsed`](abstractrange/collapsed) Read only 
  A Boolean value which is `true` if the range is *collapsed*. A collapsed range is a range whose start position and end position are the same, resulting in a zero-character-long range.

  
[`endContainer`](abstractrange/endcontainer) Read only 
  The [`Node`](node) object in which the end of the range, as specified by the `endOffset` property, is located.

  
[`endOffset`](abstractrange/endoffset) Read only 
  An integer value indicating the offset, in characters, from the beginning of the node's contents to the beginning of the range represented by the range object. This value must be less than the length of the `endContainer` node.

  
[`startContainer`](abstractrange/startcontainer) Read only 
  The DOM [`Node`](node) in which the beginning of the range, as specified by the `startOffset` property, is located.

  
[`startOffset`](abstractrange/startoffset) Read only 
  An integer value indicating the offset, in characters, from the beginning of the node's contents to the last character of the contents referred to by the range object. This value must be less than the length of the node indicated in `startContainer`.

  
Instance methods
----------------


*The `AbstractRange` interface does provide any methods.*


Usage notes
-----------


### Range types



All ranges of content within a [`document`](document) are described using instances of interfaces based on `AbstractRange`. There are two such interfaces:

  [`Range`](range)  The `Range` interface has been around for a long time and has only recently been redefined to be based upon `AbstractRange` as the need arose to define other forms of range data. `Range` provides methods that allow you to alter the range's endpoints, as well as methods to compare ranges, detect intersections between ranges, and so forth.

  [`StaticRange`](staticrange)  A `StaticRange` is a basic range which cannot be changed once it's been created. Specifically, as the node tree mutates and changes, the range does not. This is useful when you need to specify a range that will only be used once, since it avoids the performance and resource impact of the more complex [`Range`](range) interface.

  

### Contents of elements



When trying to access the contents of an element, keep in mind that the element itself is a node, but so is any text inside it. In order to set a range endpoint within the text of an element, be sure to find the text node inside the element:

 
```
const startElem = document.querySelector("p");
const endElem = startElem.querySelector("span");
const range = document.createRange();

range.setStart(startElem, 0);
range.setEnd(endElem, endElem.childNodes[0].length / 2);
const contents = range.cloneContents();

document.body.appendChild(contents);

```
 This example creates a new range, `range`, and sets its starting point to the third child node of the first element whose class is `elementclass`. The end point is set to be the middle of the first child of the span, and then the range is used to copy the contents of the range.



### Ranges and the hierarchy of the DOM



In order to define a range of characters within a document in a way that is able to span across zero or more node boundaries, and which is as resilient as possible to changes to the DOM, you can't specify the offset to the first and last characters in the [HTML](https://developer.mozilla.org/en-US/docs/Glossary/HTML). There are a few good reasons for that.

 First, after your page is loaded, the browser isn't thinking in terms of HTML. Once it's been loaded, the page is a tree of DOM [`Node`](node) objects, so you need to specify the beginning and ending locations of a range in terms of nodes and positions within nodes.

 Second, in order to support the mutability of the DOM tree as much as possible, you need a way to represent positions relative to nodes in the tree, rather than global positions within the entire document. By defining points within the document as offsets within a given node, those positions remain consistent with the content even as nodes are added to, removed from, or moved around within the DOM tree—within reason. There are fairly obvious limitations (such as if a node is moved to be after the endpoint of a range, or if the content of a node is heavily altered), but it's far better than nothing.

 Third, using node-relative positions to define the start and end positions will generally be easier to make perform well. Rather than having to negotiate the DOM figuring out what your global offset refers to, the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) (browser) can instead go directly to the node indicated by the starting position and start from there, working its way forward until it reaches the given offset into the ending node.

 To illustrate this, consider the HTML below:

 
```
<div class="container">
  <div class="header">
    <img src="" class="sitelogo" />
    <h1>The Ultimate Website</h1>
  </div>
  <article>
    <section class="entry" id="entry1">
      <h2>Section 1: An interesting thing…</h2>
      <p>A <em>very</em> interesting thing happened on the way to the forum…</p>
      <aside class="callout">
        <h2>Aside</h2>
        <p>An interesting aside to share with you…</p>
      </aside>
    </section>
  </article>
  <pre id="log"></pre>
</div>

```
 After loading the HTML and constructing the DOM representation of the document, the resulting DOM tree looks like this:

 [![Diagram of the DOM for a simple web page]

 In this diagram, the nodes representing HTML elements are shown in green. Each row beneath them shows the next layer of depth into the DOM tree. Blue nodes are text nodes, containing the text that gets shown onscreen. Each element's contents are linked below it in the tree, potentially spawning a series of branches below as elements include other elements and text nodes.

 If you want to create a range that incorporates the contents of the [`<p>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p) element whose contents are `"A <em>very</em> interesting thing happened on the way to the forum…"`, you can do so like this:

 
```
const pRange = document.createRange();
pRange.selectNodeContents(document.querySelector("#entry1 p"));

```
 Since we wish to select the entire contents of the `<p>` element, including its descendants, this works perfectly.

 If we wish to instead copy the text "An interesting thing…" from the [`<section>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/section)'s heading (an [h2](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements) element) through the end of the letters "ve" in the [`<em>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/em) within the paragraph below it, the following code would work:

 
```
const range = document.createRange();
const startNode = document.querySelector("section h2").childNodes[0];
range.setStart(startNode, 11);

const endNode = document.querySelector("#entry1 p em").childNodes[0];
range.setEnd(endNode, 2);

const fragment = range.cloneContents();

```
 Here an interesting problem arises—we are capturing content from multiple nodes located at different levels of the DOM hierarchy, and then only part of one of them. What should the result look like?

 As it turns out, the DOM specification fortunately addresses this exact issue. For example, in this case, we're calling [`cloneContents()`](range/clonecontents) on the range to create a new [`DocumentFragment`](documentfragment) object providing a DOM subtree which replicates the contents of the specified range. To do this, `cloneContents()` constructs all the nodes needed to preserve the structure of the indicated range, but no more than necessary.

 In this example, the start of the specified range is found within the text node below the section's heading, which means that the new `DocumentFragment` will need to contain an [h2](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements) and, below it, a text node.

 The range's end is located below the [`<p>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p) element, so that will be needed within the new fragment. So will the text node containing the word "A", since that's included in the range. Finally, an `<em>` and a text node below it will be added below the `<p>` as well.

 The contents of the text nodes are then determined by the offsets into those text nodes given when calling [`setStart()`](range/setstart) and [`setEnd()`](range/setend). Given the offset of 11 into the heading's text, that node will contain "An interesting thing…". Similarly, the last text node will contain "ve", given the request for the first two characters of the ending node.

 The resulting document fragment looks like this:

  ![A DocumentFragment representing the cloned content] 

 Notice especially that the contents of this fragment are all *below* the shared common parent of the topmost nodes within it. The parent `<section>` is not needed to replicate the cloned content, so it isn't included.



Example
-------



Consider this simple HTML fragment of HTML.

 
```
<p><strong>This</strong> is a paragraph.</p>

```
 Imagine using a [`Range`](range) to extract the word "paragraph" from this. The code to do that looks like the following:

 
```
const paraNode = document.querySelector("p");
const paraTextNode = paraNode.childNodes[1];

const range = document.createRange();
range.setStart(paraTextNode, 6);
range.setEnd(paraTextNode, paraTextNode.length - 1);

const fragment = range.cloneContents();
document.body.appendChild(fragment);

```
 First we get references to the paragraph node itself as well as to the *second* child node within the paragraph. The first child is the [`<strong>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/strong) element. The second child is the text node " is a paragraph.".

 With the text node reference in hand, we create a new `Range` object by calling [`createRange()`](document/createrange) on the `Document` itself. We set the starting position of the range to the sixth character of the text node's string, and the end position to the length of the text node's string minus one. This sets the range to encompass the word "paragraph".

 We then finish up by calling [`cloneContents()`](range/clonecontents) on the `Range` to create a new [`DocumentFragment`](documentfragment) object which contains the portion of the document encompassed by the range. After that, we use [`appendChild()`](node/appendchild) to add that fragment at the end of the document's body, as obtained from [`document.body`](document/body).

 The result looks like this:




Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-abstractrange](https://dom.spec.whatwg.org/#interface-abstractrange) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AbstractRange` | 90 | 9018–79 | 69 | No | 76 | 14.1 | 90 | 90 | 79 | 64 | 14.5 | 15.0 |
| `collapsed` | 90 | 9018–79 | 69 | No | 76 | 14.1 | 90 | 90 | 79 | 64 | 14.5 | 15.0 |
| `endContainer` | 90 | 9018–79 | 69 | No | 76 | 14.1 | 90 | 90 | 79 | 64 | 14.5 | 15.0 |
| `endOffset` | 90 | 9018–79 | 69 | No | 76 | 14.1 | 90 | 90 | 79 | 64 | 14.5 | 15.0 |
| `startContainer` | 90 | 9018–79 | 69 | No | 76 | 14.1 | 90 | 90 | 79 | 64 | 14.5 | 15.0 |
| `startOffset` | 90 | 9018–79 | 69 | No | 76 | 14.1 | 90 | 90 | 79 | 64 | 14.5 | 15.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AbstractRange>

ANGLE\_instanced\_arrays
========================



The `ANGLE_instanced_arrays` extension is part of the [WebGL API](webgl_api) and allows to draw the same object, or groups of similar objects multiple times, if they share the same vertex data, primitive count and type.

 WebGL extensions are available using the [`WebGLRenderingContext.getExtension()`](webglrenderingcontext/getextension) method. For more information, see also [Using Extensions](webgl_api/using_extensions) in the [WebGL tutorial](webgl_api/tutorial).

  **Note:** This extension is only available to [WebGL1](webglrenderingcontext) contexts. In [WebGL2](webgl2renderingcontext), the functionality of this extension is available on the WebGL2 context by default and the constants and methods are available without the "`ANGLE`" suffix.

 Despite the name "ANGLE", this extension works on any device if the hardware supports it and not just on Windows when using the ANGLE library. "ANGLE" just indicates that this extension has been written by the ANGLE library authors.

 

Constants
---------



This extension exposes one new constant, which can be used in the [`gl.getVertexAttrib()`](webglrenderingcontext/getvertexattrib) method:

  `ext.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE`  Returns a [`GLint`](webgl_api/types) describing the frequency divisor used for instanced rendering when used in the [`gl.getVertexAttrib()`](webglrenderingcontext/getvertexattrib) as the `pname` parameter.

  

Instance methods
----------------



This extension exposes three new methods.

  [`ext.drawArraysInstancedANGLE()`](angle_instanced_arrays/drawarraysinstancedangle)  Behaves identically to [`gl.drawArrays()`](webglrenderingcontext/drawarrays) except that multiple instances of the range of elements are executed, and the instance advances for each iteration.

  [`ext.drawElementsInstancedANGLE()`](angle_instanced_arrays/drawelementsinstancedangle)  Behaves identically to [`gl.drawElements()`](webglrenderingcontext/drawelements) except that multiple instances of the set of elements are executed and the instance advances between each set.

  [`ext.vertexAttribDivisorANGLE()`](angle_instanced_arrays/vertexattribdivisorangle)  Modifies the rate at which generic vertex attributes advance when rendering multiple instances of primitives with [`ext.drawArraysInstancedANGLE()`](angle_instanced_arrays/drawarraysinstancedangle) and [`ext.drawElementsInstancedANGLE()`](angle_instanced_arrays/drawelementsinstancedangle).

  

Examples
--------



The following example shows how to draw a given geometry multiple times with a single draw call.

  **Warning:** The following is educational, not production level code. It should generally be avoided to construct data / buffers within the rendering loop or right before use.

  
```
// enable the extension
const ext = gl.getExtension("ANGLE\_instanced\_arrays");

// binding the geometry buffer as usual
gl.bindBuffer(gl.ARRAY\_BUFFER, geometryVertexBuffer);
gl.enableVertexAttribArray(vertexPositionAttributeLocation);
gl.vertexAttribPointer(
  vertexPositionAttributeLocation,
  3,
  gl.FLOAT,
  false,
  0,
  0
);

// build position buffer
const instancePositions = [];
for (const instance of instances) {
  instancePositions.push(
    instance.position.x,
    instance.position.y,
    instance.position.z
  );
}
const instancePositionBuffer = createWebGLBufferFromData(instancePositions);

// binding the instance position buffer as you would with any attribute
gl.bindBuffer(gl.ARRAY\_BUFFER, instancePositionBuffer);
gl.enableVertexAttribArray(instancePositionAttributeLocation);
gl.vertexAttribPointer(
  instancePositionAttributeLocation,
  3,
  gl.FLOAT,
  false,
  0,
  0
);

// mark the attribute as instanced and advance it every single(1) instance rather than every vertex
ext.vertexAttribDivisorANGLE(instancePositionAttributeLocation, 1);

// draw geometry for each instance
ext.drawArraysInstancedANGLE(
  gl.TRIANGLES,
  0,
  numGeometryVertices,
  instances.length
);

```


Specifications
--------------




| Specification |
| --- |
| [WebGL ANGLE\_instanced\_arrays Khronos Ratified Extension Specification](https://registry.khronos.org/webgl/extensions/ANGLE_instanced_arrays/)  |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ANGLE_instanced_arrays` | 3230Available only on macOS. | 12 | 47 | 11 | 1917Available only on macOS. | 8 | 4.4 | 30 | 47 | 18 | 8 | 2.0 |
| `drawArraysInstancedANGLE` | 30 | 12 | 47 | 11 | 17 | 8 | 4.4 | 30 | 47 | 18 | 8 | 2.0 |
| `drawElementsInstancedANGLE` | 30 | 12 | 47 | 11 | 17 | 8 | 4.4 | 30 | 47 | 18 | 8 | 2.0 |
| `vertexAttribDivisorANGLE` | 30 | 12 | 47 | 11 | 17 | 8 | 4.4 | 30 | 47 | 18 | 8 | 2.0 |


See also
--------


* [`WebGLRenderingContext.getExtension()`](webglrenderingcontext/getextension)
* [`WebGL2RenderingContext.drawArraysInstanced()`](webgl2renderingcontext/drawarraysinstanced)
* [`WebGL2RenderingContext.drawElementsInstanced()`](webgl2renderingcontext/drawelementsinstanced)
* [`WebGL2RenderingContext.vertexAttribDivisor()`](webgl2renderingcontext/vertexattribdivisor)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ANGLE_instanced_arrays>

Animation
=========



The `Animation` interface of the [Web Animations API](web_animations_api) represents a single animation player and provides playback controls and a timeline for an animation node or source.


 EventTarget Animation

Constructor
-----------


 [`Animation()`](animation/animation)  Creates a new `Animation` object instance.

  
Instance properties
-------------------


 [`Animation.currentTime`](animation/currenttime)  The current time value of the animation in milliseconds, whether running or paused. If the animation lacks a [`timeline`](animationtimeline), is inactive or hasn't been played yet, its value is `null`.

  [`Animation.effect`](animation/effect)  Gets and sets the [`AnimationEffect`](animationeffect) associated with this animation. This will usually be a [`KeyframeEffect`](keyframeeffect) object.

  
[`Animation.finished`](animation/finished) Read only 
  Returns the current finished Promise for this animation.

  [`Animation.id`](animation/id)  Gets and sets the `String` used to identify the animation.

  
[`Animation.pending`](animation/pending) Read only 
  Indicates whether the animation is currently waiting for an asynchronous operation such as initiating playback or pausing a running animation.

  
[`Animation.playState`](animation/playstate) Read only 
  Returns an enumerated value describing the playback state of an animation.

  [`Animation.playbackRate`](animation/playbackrate)  Gets or sets the playback rate of the animation.

  
[`Animation.ready`](animation/ready) Read only 
  Returns the current ready Promise for this animation.

  
[`Animation.replaceState`](animation/replacestate) Read only 
  Returns the replace state of the animation. This will be `active` if the animation has been replaced, or `persisted` if [`Animation.persist()`](animation/persist) has been invoked on it.

  [`Animation.startTime`](animation/starttime)  Gets or sets the scheduled time when an animation's playback should begin.

  [`Animation.timeline`](animation/timeline)  Gets or sets the [`timeline`](animationtimeline) associated with this animation.

  
Instance methods
----------------


 [`Animation.cancel()`](animation/cancel)  Clears all [`keyframeEffects`](keyframeeffect) caused by this animation and aborts its playback.

  [`Animation.commitStyles()`](animation/commitstyles)  Commits the end styling state of an animation to the element being animated, even after that animation has been removed. It will cause the end styling state to be written to the element being animated, in the form of properties inside a `style` attribute.

  [`Animation.finish()`](animation/finish)  Seeks either end of an animation, depending on whether the animation is playing or reversing.

  [`Animation.pause()`](animation/pause)  Suspends playing of an animation.

  [`animation.persist()`](animation/persist)  Explicitly persists an animation, when it would otherwise be removed due to the browser's [Automatically removing filling animations](#automatically_removing_filling_animations) behavior.

  [`Animation.play()`](animation/play)  Starts or resumes playing of an animation, or begins the animation again if it previously finished.

  [`Animation.reverse()`](animation/reverse)  Reverses playback direction, stopping at the start of the animation. If the animation is finished or unplayed, it will play from end to beginning.

  [`Animation.updatePlaybackRate()`](animation/updateplaybackrate)  Sets the speed of an animation after first synchronizing its playback position.

  
Events
------


 [`cancel`](animation/cancel_event)  Fires when the [`Animation.cancel()`](animation/cancel) method is called or when the animation enters the `"idle"` play state from another state.

  [`finish`](animation/finish_event)  Fires when the animation finishes playing.

  [`remove`](animation/remove_event)  Fires when the animation is removed (i.e., put into an `active` replace state).

  
Automatically removing filling animations
-----------------------------------------



It is possible to trigger a large number of animations on the same element. If they are indefinite (i.e., forwards-filling), this can result in a huge animations list, which could create a memory leak. For this reason, modern browsers have implemented the part of the Web Animations spec that automatically removes overriding forward filling animations, unless the developer explicitly specifies to keep them.

 You can see this in action in our simple [replace indefinite animations demo](https://mdn.github.io/dom-examples/web-animations-api/replace-indefinite-animations.html). The related JavaScript features are:

 * [`animation.commitStyles()`](animation/commitstyles) for committing the end styling state of an animation to the element being animated, even after that animation has been removed.
* The [`remove`](animation/remove_event) event on the [`Animation`](animation) interface fires when the animation is removed (i.e., put into an `active` replace state).
* [`animation.persist()`](animation/persist) for when you explicitly want an animation to be retained.
* [`animation.replaceState`](animation/replacestate) to return the replace state of the animation. This will be `active` if the animation has been removed, or `persisted` if [`persist()`](animation/persist) has been invoked.



Accessibility concerns
----------------------



Blinking and flashing animation can be problematic for people with cognitive concerns such as Attention Deficit Hyperactivity Disorder (ADHD). Additionally, certain kinds of motion can be a trigger for Vestibular disorders, epilepsy, and migraine, and Scotopic sensitivity.

 Consider providing a mechanism for pausing or disabling animation, as well as using the [Reduced Motion Media Query](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion) to create a complimentary experience for users who have expressed a preference for no animated experiences.

 * [Designing Safer Web Animation For Motion Sensitivity · An A List Apart Article](https://alistapart.com/article/designing-safer-web-animation-for-motion-sensitivity/)
* [An Introduction to the Reduced Motion Media Query | CSS-Tricks](https://css-tricks.com/introduction-reduced-motion-media-query/)
* [Responsive Design for Motion | WebKit](https://webkit.org/blog/7551/responsive-design-for-motion/)
* [MDN Understanding WCAG, Guideline 2.2 explanations](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Operable#guideline_2.2_%e2%80%94_enough_time_provide_users_enough_time_to_read_and_use_content)
* [Understanding Success Criterion 2.2.2 | W3C Understanding WCAG 2.0](https://www.w3.org/TR/UNDERSTANDING-WCAG20/time-limits-pause.html)



Specifications
--------------




| Specification |
| --- |
| [Web Animations # the-animation-interface](https://w3c.github.io/csswg-drafts/web-animations-1/#the-animation-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Animation` | 75 | 79 | 48 | No | 62 | 13.1 | 75 | 75 | 48 | 54 | 13.4 | 11.0 |
| `Animation` | 75 | 79 | 48 | No | 62 | 13.1 | 75 | 75 | 48 | 54 | 13.4 | 11.0 |
| `cancel` | 75 | 79 | 48 | No | 62 | 13.1 | 75 | 75 | 48 | 54 | 13.4 | 11.0 |
| `cancel_event` | 75 | 79 | 48 | No | 62 | 13.1 | 75 | 75 | 48 | 54 | 13.4 | 11.0 |
| `commitStyles` | 84 | 84 | 75 | No | 70 | 13.1 | 84 | 84 | 79 | 60 | 13.4 | 14.0 |
| `currentTime` | 75 | 79 | 48 | No | 62 | 13.1 | 75 | 75 | 48 | 54 | 13.4 | 11.0 |
| `effect` | 75 | 79 | 63 | No | 62 | 13.1 | 75 | 75 | 63 | 54 | 13.4 | 11.0 |
| `finish` | 75 | 79 | 48 | No | 62 | 13.1 | 75 | 75 | 48 | 54 | 13.4 | 11.0 |
| `finish_event` | 75 | 79 | 48 | No | 62 | 13.1 | 75 | 75 | 48 | 54 | 13.4 | 11.0 |
| `finished` | 84 | 84 | 63 | No | 70 | 13.1 | 84 | 84 | 63 | 60 | 13.4 | 14.0 |
| `id` | 75 | 79 | 48 | No | 62 | 13.1 | 75 | 75 | 48 | 54 | 13.4 | 11.0 |
| `pause` | 75 | 79 | 48 | No | 62 | 13.1 | 75 | 75 | 48 | 54 | 13.4 | 11.0 |
| `pending` | 76 | 79 | 59Before version 59, the pending status was reported by a `**"pending"**` value returned from [`Animation.playState`](https://developer.mozilla.org/docs/Web/API/Animation/playState). | No | 63 | 13.1 | 76 | 76 | 59Before version 59, the pending status was reported by a `**"pending"**` value returned from [`Animation.playState`](https://developer.mozilla.org/docs/Web/API/Animation/playState). | 54 | 13.4 | 12.0 |
| `persist` | 84 | 84 | 75 | No | 70 | 13.1 | 84 | 84 | 79 | 60 | 13.4 | 14.0 |
| `play` | 75 | 79 | 48 | No | 62 | 13.1 | 75 | 75 | 48 | 54 | 13.4 | 11.0 |
| `playState` | 75Before Chrome 50/Opera 37, this property returned `idle` for an animation that had not yet started. Starting with Chrome 50/Opera 37, it shows `paused`. | 79 | 48Before Firefox 59, this property returned `pending` for Animations with incomplete asynchronous operations but as of Firefox 59 this is indicated by the separate [`Animation.pending`](https://developer.mozilla.org/docs/Web/API/Animation/pending) property. This reflects recent changes to the specification. | No | 62Before Chrome 50/Opera 37, this property returned `idle` for an animation that had not yet started. Starting with Chrome 50/Opera 37, it shows `paused`. | 13.1 | 75Before Chrome 50/Opera 37, this property returned `idle` for an animation that had not yet started. Starting with Chrome 50/Opera 37, it shows `paused`. | 75Before Chrome 50/Opera 37, this property returned `idle` for an animation that had not yet started. Starting with Chrome 50/Opera 37, it shows `paused`. | 48Before Firefox 59, this property returned `pending` for Animations with incomplete asynchronous operations but as of Firefox 59 this is indicated by the separate [`Animation.pending`](https://developer.mozilla.org/docs/Web/API/Animation/pending) property. This reflects recent changes to the specification. | 54Before Chrome 50/Opera 37, this property returned `idle` for an animation that had not yet started. Starting with Chrome 50/Opera 37, it shows `paused`. | 13.4 | 11.0Before Samsung Internet 5.0/Opera 37, this property returned `idle` for an animation that had not yet started. Starting with Samsung Internet 5.0/Opera 37, it shows `paused`. |
| `playbackRate` | 75 | 79 | 48 | No | 62 | 13.1 | 75 | 75 | 48 | 54 | 13.4 | 11.0 |
| `ready` | 84 | 84 | 63 | No | 70 | 13.1 | 84 | 84 | 63 | 60 | 13.4 | 14.0 |
| `remove_event` | 84 | 84 | 75 | No | 70 | 13.1 | 84 | 84 | 79 | 60 | 13.4 | 14.0 |
| `remove_filling_animation` | 84 | 84 | 75 | No | 70 | 13.1 | 84 | 84 | 79 | 60 | 13.4 | 14.0 |
| `replaceState` | 84 | 84 | 75 | No | 70 | 13.1 | 84 | 84 | 79 | 60 | 13.4 | 14.0 |
| `reverse` | 75 | 79 | 48 | No | 62 | 13.1 | 75 | 75 | 48 | 54 | 13.4 | 11.0 |
| `startTime` | 75 | 79 | 48 | No | 62 | 13.1 | 75 | 75 | 48 | 54 | 13.4 | 11.0 |
| `timeline` | 84 | 84 | 75Currently only the getter is supported | No | 70 | 13.1Currently only the getter is supported | 84 | 84 | 79Currently only the getter is supported | 60 | 13.4Currently only the getter is supported | 14.0 |
| `updatePlaybackRate` | 76 | 79 | 60 | No | 63 | 13.1 | 76 | 76 | 60 | 54 | 13.4 | 12.0 |


See also
--------


* [Web Animations API](web_animations_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Animation>

AnimationEffect
===============



The `AnimationEffect` interface of the [Web Animations API](web_animations_api) is an interface representing animation effects.

 `AnimationEffect` is an abstract interface and so isn't directly instantiable. However, concrete interfaces such as [`KeyframeEffect`](keyframeeffect) inherit from it, and instances of these interfaces can be passed to [`Animation`](animation) objects for playing, and may also be used by [CSS Animations](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Animations) and [Transitions](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions).



Instance methods
----------------


 [`AnimationEffect.getTiming()`](animationeffect/gettiming)  Returns the object associated with the animation containing all the animation's timing values.

  [`AnimationEffect.getComputedTiming()`](animationeffect/getcomputedtiming)  Returns the calculated timing properties for this `AnimationEffect`.

  [`AnimationEffect.updateTiming()`](animationeffect/updatetiming)  Updates the specified timing properties of this `AnimationEffect`.

  
Specifications
--------------




| Specification |
| --- |
| [Web Animations # the-animationeffect-interface](https://w3c.github.io/csswg-drafts/web-animations-1/#the-animationeffect-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AnimationEffect` | 75 | 79 | 6348–63 | No | 62 | 13.1 | 75 | 75 | 6348–63 | 54 | 13.4 | 11.0 |
| `getComputedTiming` | 75 | 79 | 63 | No | 62 | 13.1 | 75 | 75 | 63 | 54 | 13.4 | 11.0 |
| `getTiming` | 75 | 79 | 63 | No | 62 | 13.1 | 75 | 75 | 63 | 54 | 13.4 | 11.0 |
| `updateTiming` | 75 | 79 | 63 | No | 62 | 13.1 | 75 | 75 | 63 | 54 | 13.4 | 11.0 |


See also
--------


* [Web Animations API](web_animations_api)
* [`Animation.effect`](animation/effect)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AnimationEffect>

AbortController
===============



The `AbortController` interface represents a controller object that allows you to abort one or more Web requests as and when desired.

 You can create a new `AbortController` object using the [`AbortController()`](abortcontroller/abortcontroller) constructor. Communicating with a DOM request is done using an [`AbortSignal`](abortsignal) object.



Constructor
-----------


 [`AbortController()`](abortcontroller)  Creates a new `AbortController` object instance.

  
Instance properties
-------------------


 
[`AbortController.signal`](abortcontroller/signal) Read only 
  Returns an [`AbortSignal`](abortsignal) object instance, which can be used to communicate with, or to abort, a DOM request.

  
Instance methods
----------------


 [`AbortController.abort()`](abortcontroller/abort)  Aborts a DOM request before it has completed. This is able to abort [fetch requests](fetch), consumption of any response bodies, and streams.

  
Examples
--------



 **Note:** There are additional examples in the [`AbortSignal`](abortsignal) reference.

  In the following snippet, we aim to download a video using the [Fetch API](fetch_api).

 We first create a controller using the [`AbortController()`](abortcontroller/abortcontroller) constructor, then grab a reference to its associated [`AbortSignal`](abortsignal) object using the [`AbortController.signal`](abortcontroller/signal) property.

 When the [fetch request](fetch) is initiated, we pass in the `AbortSignal` as an option inside the request's options object (the `{signal}` below). This associates the signal and controller with the fetch request and allows us to abort it by calling [`AbortController.abort()`](abortcontroller/abort), as seen below in the second event listener.

 
```
let controller;
const url = "video.mp4";

const downloadBtn = document.querySelector(".download");
const abortBtn = document.querySelector(".abort");

downloadBtn.addEventListener("click", fetchVideo);

abortBtn.addEventListener("click", () => {
  if (controller) {
    controller.abort();
    console.log("Download aborted");
  }
});

function fetchVideo() {
  controller = new AbortController();
  const signal = controller.signal;
  fetch(url, { signal })
    .then((response) => {
      console.log("Download complete", response);
    })
    .catch((err) => {
      console.error(`Download error: ${err.message}`);
    });
}

```
  **Note:** When `abort()` is called, the `fetch()` promise rejects with a `DOMException` named `AbortError`.

  You can find a [full working example on GitHub](https://github.com/mdn/dom-examples/tree/main/abort-api); you can also see it [running live](https://mdn.github.io/dom-examples/abort-api/).



Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-abortcontroller](https://dom.spec.whatwg.org/#interface-abortcontroller) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AbortController` | 66 | 16 | 57 | No | 53 | 12.111.1Even though `window.AbortController` is defined, it doesn't really abort `fetch` requests. See [bug 174980](https://webkit.org/b/174980). | 66 | 66 | 57 | 47 | 12.211.3Even though `window.AbortController` is defined, it doesn't really abort `fetch` requests. See [bug 174980](https://webkit.org/b/174980). | 9.0 |
| `AbortController` | 66 | 16 | 57 | No | 53 | 12.111.1Even though `window.AbortController` is defined, it doesn't really abort `fetch` requests. See [bug 174980](https://webkit.org/b/174980). | 66 | 66 | 57 | 47 | 12.211.3Even though `window.AbortController` is defined, it doesn't really abort `fetch` requests. See [bug 174980](https://webkit.org/b/174980). | 9.0 |
| `abort` | 66 | 16 | 57 | No | 53 | 12.111.1Even though `window.AbortController` is defined, it doesn't really abort `fetch` requests. See [bug 174980](https://webkit.org/b/174980). | 66 | 66 | 57 | 47 | 12.211.3Even though `window.AbortController` is defined, it doesn't really abort `fetch` requests. See [bug 174980](https://webkit.org/b/174980). | 9.0 |
| `signal` | 66 | 16 | 57 | No | 53 | 12.111.1Even though `window.AbortController` is defined, it doesn't really abort `fetch` requests. See [bug 174980](https://webkit.org/b/174980). | 66 | 66 | 57 | 47 | 12.211.3Even though `window.AbortController` is defined, it doesn't really abort `fetch` requests. See [bug 174980](https://webkit.org/b/174980). | 9.0 |


See also
--------


* [Fetch API](fetch_api)
* [Abortable Fetch](https://developer.chrome.com/blog/abortable-fetch/) by Jake Archibald


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AbortController>

Accelerometer
=============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `Accelerometer` interface of the [Sensor APIs](sensor_apis) provides on each reading the acceleration applied to the device along all three axes.

 To use this sensor, the user must grant permission to the `'accelerometer'`, device sensor through the [Permissions API](permissions_api).

 This feature may be blocked by a [Permissions Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy) set on your server.


 EventTarget Sensor Accelerometer

Constructor
-----------


 
[`Accelerometer()`](accelerometer/accelerometer)  Experimental 
  Creates a new `Accelerometer` object.

  
Instance properties
-------------------



*In addition to the properties listed below, `Accelerometer` inherits properties from its parent interfaces, [`Sensor`](sensor) and [`EventTarget`](eventtarget).*

  
[`Accelerometer.x`](accelerometer/x) Read only   Experimental 
  Returns a double containing the acceleration of the device along the device's x axis.

  
[`Accelerometer.y`](accelerometer/y) Read only   Experimental 
  Returns a double containing the acceleration of the device along the device's y axis.

  
[`Accelerometer.z`](accelerometer/z) Read only   Experimental 
  Returns a double containing the acceleration of the device along the device's z axis.

  

Instance methods
----------------


*`Accelerometer` doesn't have own methods. However, it inherits methods from its parent interfaces, [`Sensor`](sensor) and [`EventTarget`](eventtarget).*


Events
------


*`Accelerometer` doesn't have own events. However, it inherits events from its parent interface, [`Sensor`](sensor).*


Example
-------



Acceleration is typically read in the [`reading`](sensor/reading_event) event callback. In the example below this occurs sixty times a second.

 
```
const acl = new Accelerometer({ frequency: 60 });
acl.addEventListener("reading", () => {
  console.log(`Acceleration along the X-axis ${acl.x}`);
  console.log(`Acceleration along the Y-axis ${acl.y}`);
  console.log(`Acceleration along the Z-axis ${acl.z}`);
});

acl.start();

```


Specifications
--------------




| Specification |
| --- |
| [Accelerometer # accelerometer-interface](https://w3c.github.io/accelerometer/#accelerometer-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Accelerometer` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |
| `Accelerometer` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |
| `x` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |
| `y` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |
| `z` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Accelerometer>

AesCbcParams
============


The `AesCbcParams` dictionary of the [Web Crypto API](web_crypto_api) represents the object that should be passed as the `algorithm` parameter into [`SubtleCrypto.encrypt()`](subtlecrypto/encrypt), [`SubtleCrypto.decrypt()`](subtlecrypto/decrypt), [`SubtleCrypto.wrapKey()`](subtlecrypto/wrapkey), or [`SubtleCrypto.unwrapKey()`](subtlecrypto/unwrapkey), when using the [AES-CBC](subtlecrypto/encrypt#aes-cbc) algorithm.


Instance properties
-------------------


 `name`  A string. This should be set to `AES-CBC`.

  `iv`  An [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), a [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), or a [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). The initialization vector. Must be 16 bytes, unpredictable, and preferably cryptographically random. However, it need not be secret (for example, it may be transmitted unencrypted along with the ciphertext).

  
Examples
--------


See the examples for [`SubtleCrypto.encrypt()`](subtlecrypto/encrypt) and [`SubtleCrypto.decrypt()`](subtlecrypto/decrypt).


Specifications
--------------




| Specification |
| --- |
| [Web Cryptography API # dfn-AesCbcParams](https://w3c.github.io/webcrypto/#dfn-AesCbcParams) |


Browser compatibility
---------------------


See also
--------


* CBC mode is defined in section 6.2 of the [NIST SP800-38A standard](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38a.pdf#%5B%7B%22num%22%3A70%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22Fit%22%7D%5D).
* [`SubtleCrypto.encrypt()`](subtlecrypto/encrypt).
* [`SubtleCrypto.decrypt()`](subtlecrypto/decrypt).
* [`SubtleCrypto.wrapKey()`](subtlecrypto/wrapkey).
* [`SubtleCrypto.unwrapKey()`](subtlecrypto/unwrapkey).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AesCbcParams>

AesCtrParams
============



The `AesCtrParams` dictionary of the [Web Crypto API](web_crypto_api) represents the object that should be passed as the `algorithm` parameter into [`SubtleCrypto.encrypt()`](subtlecrypto/encrypt), [`SubtleCrypto.decrypt()`](subtlecrypto/decrypt), [`SubtleCrypto.wrapKey()`](subtlecrypto/wrapkey), or [`SubtleCrypto.unwrapKey()`](subtlecrypto/unwrapkey), when using the [AES-CTR](subtlecrypto/encrypt#aes-ctr) algorithm.

 AES is a block cipher, meaning that it splits the message into blocks and encrypts it a block at a time. In CTR mode, every time a block of the message is encrypted, an extra block of data is mixed in. This extra block is called the "counter block".

 A given counter block value must never be used more than once with the same key:

 * Given a message *n* blocks long, a different counter block must be used for every block.
* If the same key is used to encrypt more than one message, a different counter block must be used for all blocks across all messages.

 Typically this is achieved by splitting the initial counter block value into two concatenated parts:

 * A [nonce](https://en.wikipedia.org/wiki/Cryptographic_nonce) (that is, a number that may only be used once). The nonce part of the block stays the same for every block in the message. Each time a new message is to be encrypted, a new nonce is chosen. Nonces don't have to be secret, but they must not be reused with the same key.
* A counter. This part of the block gets incremented each time a block is encrypted.

 Essentially: the nonce should ensure that counter blocks are not reused from one message to the next, while the counter should ensure that counter blocks are not reused within a single message.

  **Note:** See [Appendix B of the NIST SP800-38A standard](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38a.pdf#%5B%7B%22num%22%3A70%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22Fit%22%7D%5D) for more information.

 

Instance properties
-------------------


 `name`  A string. This should be set to `AES-CTR`.

  `counter`  An [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), a [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), or a [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) — the initial value of the counter block. This must be 16 bytes long (the AES block size). The rightmost `length` bits of this block are used for the counter, and the rest is used for the nonce. For example, if `length` is set to 64, then the first half of `counter` is the nonce and the second half is used for the counter.

  `length`  A `Number` — the number of bits in the counter block that are used for the actual counter. The counter must be big enough that it doesn't wrap: if the message is `n` blocks and the counter is `m` bits long, then the following must be true: `n <= 2^m`. The [NIST SP800-38A](https://csrc.nist.gov/publications/detail/sp/800-38a/final) standard, which defines CTR, suggests that the counter should occupy half of the counter block (see [Appendix B.2](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38a.pdf#%5B%7B%22num%22%3A73%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22Fit%22%7D%5D)), so for AES it would be 64.

  
Examples
--------


See the examples for [`SubtleCrypto.encrypt()`](subtlecrypto/encrypt) and [`SubtleCrypto.decrypt()`](subtlecrypto/decrypt).


Specifications
--------------




| Specification |
| --- |
| [Web Cryptography API # dfn-AesCtrParams](https://w3c.github.io/webcrypto/#dfn-AesCtrParams) |


Browser compatibility
---------------------


See also
--------


* CTR mode is defined in section 6.5 of the [NIST SP800-38A standard](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38a.pdf#%5B%7B%22num%22%3A70%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22Fit%22%7D%5D).
* [`SubtleCrypto.encrypt()`](subtlecrypto/encrypt).
* [`SubtleCrypto.decrypt()`](subtlecrypto/decrypt).
* [`SubtleCrypto.wrapKey()`](subtlecrypto/wrapkey).
* [`SubtleCrypto.unwrapKey()`](subtlecrypto/unwrapkey).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AesCtrParams>

AesGcmParams
============



The `AesGcmParams` dictionary of the [Web Crypto API](web_crypto_api) represents the object that should be passed as the `algorithm` parameter into [`SubtleCrypto.encrypt()`](subtlecrypto/encrypt), [`SubtleCrypto.decrypt()`](subtlecrypto/decrypt), [`SubtleCrypto.wrapKey()`](subtlecrypto/wrapkey), or [`SubtleCrypto.unwrapKey()`](subtlecrypto/unwrapkey), when using the [AES-GCM](subtlecrypto/encrypt#aes-gcm) algorithm.

 For details of how to supply appropriate values for this parameter, see the specification for AES-GCM: [NIST SP800-38D](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf), in particular section 5.2.1.1 on Input Data.



Instance properties
-------------------


 `name`  A string. This should be set to `AES-GCM`.

  `iv`  An [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), a [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), or a [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) with the initialization vector. This must be unique for every encryption operation carried out with a given key. Put another way: never reuse an IV with the same key. The AES-GCM specification recommends that the IV should be 96 bits long, and typically contains bits from a random number generator. [Section 8.2 of the specification](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf#%5B%7B%22num%22%3A65%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22XYZ%22%7D%2C0%2C792%2Cnull%5D) outlines methods for constructing IVs. Note that the IV does not have to be secret, just unique: so it is OK, for example, to transmit it in the clear alongside the encrypted message.

  
`additionalData` Optional
  An [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), a [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), or a [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). This contains additional data that will not be encrypted but will be authenticated along with the encrypted data. If `additionalData` is given here then the same data must be given in the corresponding call to [`decrypt()`](subtlecrypto/decrypt): if the data given to the `decrypt()` call does not match the original data, the decryption will throw an exception. This gives you a way to authenticate associated data without having to encrypt it.

 The bit length of `additionalData` must be smaller than `2^64 - 1`.

 The `additionalData` property is optional and may be omitted without compromising the security of the encryption operation.

  
`tagLength` Optional
  A `Number`. This determines the size in bits of the authentication tag generated in the encryption operation and used for authentication in the corresponding decryption.

 According to the [Web Crypto specification](https://www.w3.org/TR/WebCryptoAPI/#dfn-AesGcmParams) this must have one of the following values: 32, 64, 96, 104, 112, 120, or 128. The AES-GCM specification recommends that it should be 96, 104, 112, 120 or 128, although 32 or 64 bits may be acceptable in some applications: [Appendix C of the specification](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf#%5B%7B%22num%22%3A92%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22XYZ%22%7D%2C0%2C792%2Cnull%5D) provides additional guidance here.

 `tagLength` is optional and defaults to 128 if it is not specified.

  
Examples
--------


See the examples for [`SubtleCrypto.encrypt()`](subtlecrypto/encrypt) and [`SubtleCrypto.decrypt()`](subtlecrypto/decrypt).


Specifications
--------------




| Specification |
| --- |
| [Web Cryptography API # dfn-AesGcmParams](https://w3c.github.io/webcrypto/#dfn-AesGcmParams) |


Browser compatibility
---------------------


See also
--------


* [`SubtleCrypto.encrypt()`](subtlecrypto/encrypt).
* [`SubtleCrypto.decrypt()`](subtlecrypto/decrypt).
* [`SubtleCrypto.wrapKey()`](subtlecrypto/wrapkey).
* [`SubtleCrypto.unwrapKey()`](subtlecrypto/unwrapkey).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AesGcmParams>

AesKeyGenParams
===============


The `AesKeyGenParams` dictionary of the [Web Crypto API](web_crypto_api) represents the object that should be passed as the `algorithm` parameter into [`SubtleCrypto.generateKey()`](subtlecrypto/generatekey), when generating an AES key: that is, when the algorithm is identified as any of [AES-CBC](subtlecrypto/encrypt#aes-cbc), [AES-CTR](subtlecrypto/encrypt#aes-ctr), [AES-GCM](subtlecrypto/encrypt#aes-gcm), or [AES-KW](subtlecrypto/wrapkey#aes-kw).


Instance properties
-------------------


 `name`  A string. This should be set to `AES-CBC`, `AES-CTR`, `AES-GCM`, or `AES-KW`, depending on the algorithm you want to use.

  `length`  A `Number` — the length in bits of the key to generate. This must be one of: 128, 192, or 256.

  
Examples
--------


See the examples for [`SubtleCrypto.generateKey()`](subtlecrypto/generatekey).


Specifications
--------------




| Specification |
| --- |
| [Web Cryptography API # dfn-AesKeyGenParams](https://w3c.github.io/webcrypto/#dfn-AesKeyGenParams) |


Browser compatibility
---------------------


See also
--------


* [`SubtleCrypto.generateKey()`](subtlecrypto/generatekey).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AesKeyGenParams>

AmbientLightSensor
==================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `AmbientLightSensor` interface of the [Sensor APIs](sensor_apis) returns the current light level or illuminance of the ambient light around the hosting device.

 To use this sensor, the user must grant permission to the `'ambient-light-sensor'` device sensor through the [Permissions API](permissions_api).

 This feature may be blocked by a [Permissions Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy) set on your server.


 EventTarget Sensor AmbientLightSensor

Constructor
-----------


 
[`AmbientLightSensor()`](ambientlightsensor/ambientlightsensor)  Experimental 
  Creates a new `AmbientLightSensor` object.

  
Instance properties
-------------------


 
[`AmbientLightSensor.illuminance`](ambientlightsensor/illuminance)  Experimental 
  Returns the current light level in [lux](https://en.wikipedia.org/wiki/Lux) of the ambient light level around the hosting device.

  
Instance methods
----------------


*`AmbientLightSensor` doesn't have own methods. However, it inherits methods from its parent interfaces, [`Sensor`](sensor) and [`EventTarget`](eventtarget).*


Events
------


*`AmbientLightSensor` doesn't have own events. However, it inherits events from its parent interface, [`Sensor`](sensor).*


Example
-------



```
if ("AmbientLightSensor" in window) {
  const sensor = new AmbientLightSensor();
  sensor.addEventListener("reading", (event) => {
    console.log("Current light level:", sensor.illuminance);
  });
  sensor.addEventListener("error", (event) => {
    console.log(event.error.name, event.error.message);
  });
  sensor.start();
}

```

Specifications
--------------




| Specification |
| --- |
| [Ambient Light Sensor # ambient-light-sensor-interface](https://w3c.github.io/ambient-light/#ambient-light-sensor-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AmbientLightSensor` | 56 | 79 | No | No | 43 | No | No | 56 | No | No | No | No |
| `AmbientLightSensor` | 56 | 79 | No | No | 43 | No | No | 56 | No | No | No | No |
| `illuminance` | 56In Chrome 79, this method stopped returning floats and returned integers to avoid fingerprinting. | 79In Edge 79, this method stopped returning floats and returned integers to avoid fingerprinting. | No | No | 43In Opera 66, this method stopped returning floats and returned integers to avoid fingerprinting. | No | No | 56In Chrome 79, this method stopped returning floats and returned integers to avoid fingerprinting. | No | No | No | No |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AmbientLightSensor>

AnalyserNode
============



The `AnalyserNode` interface represents a node able to provide real-time frequency and time-domain analysis information. It is an [`AudioNode`](audionode) that passes the audio stream unchanged from the input to the output, but allows you to take the generated data, process it, and create audio visualizations.

 An `AnalyserNode` has exactly one input and one output. The node works even if the output is not connected.

  ![Without modifying the audio stream, the node allows to get the frequency and time-domain data associated to it, using a FFT.] 


 EventTarget AudioNode AnalyserNode 

|  |  |
| --- | --- |
| Number of inputs | `1` |
| Number of outputs | `1` (but may be left unconnected) |
| Channel count mode | `"max"` |
| Channel count | `2` |
| Channel interpretation | `"speakers"` |



Constructor
-----------


 [`AnalyserNode()`](analysernode/analysernode)  Creates a new instance of an `AnalyserNode` object.

  
Instance properties
-------------------



*Inherits properties from its parent, [`AudioNode`](audionode)*.

  [`AnalyserNode.fftSize`](analysernode/fftsize)  An unsigned long value representing the size of the FFT ([Fast Fourier Transform](https://en.wikipedia.org/wiki/Fast_Fourier_transform)) to be used to determine the frequency domain.

  
[`AnalyserNode.frequencyBinCount`](analysernode/frequencybincount) Read only 
  An unsigned long value half that of the FFT size. This generally equates to the number of data values you will have to play with for the visualization.

  [`AnalyserNode.minDecibels`](analysernode/mindecibels)  A double value representing the minimum power value in the scaling range for the FFT analysis data, for conversion to unsigned byte values — basically, this specifies the minimum value for the range of results when using `getByteFrequencyData()`.

  [`AnalyserNode.maxDecibels`](analysernode/maxdecibels)  A double value representing the maximum power value in the scaling range for the FFT analysis data, for conversion to unsigned byte values — basically, this specifies the maximum value for the range of results when using `getByteFrequencyData()`.

  [`AnalyserNode.smoothingTimeConstant`](analysernode/smoothingtimeconstant)  A double value representing the averaging constant with the last analysis frame — basically, it makes the transition between values over time smoother.

  

Instance methods
----------------



*Inherits methods from its parent, [`AudioNode`](audionode)*.

  [`AnalyserNode.getFloatFrequencyData()`](analysernode/getfloatfrequencydata)  Copies the current frequency data into a [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) array passed into it.

  [`AnalyserNode.getByteFrequencyData()`](analysernode/getbytefrequencydata)  Copies the current frequency data into a [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) (unsigned byte array) passed into it.

  [`AnalyserNode.getFloatTimeDomainData()`](analysernode/getfloattimedomaindata)  Copies the current waveform, or time-domain, data into a [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) array passed into it.

  [`AnalyserNode.getByteTimeDomainData()`](analysernode/getbytetimedomaindata)  Copies the current waveform, or time-domain, data into a [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) (unsigned byte array) passed into it.

  

Examples
--------


 **Note:** See the guide [Visualizations with Web Audio API](web_audio_api/visualizations_with_web_audio_api) for more information on creating audio visualizations.

 
### Basic usage



 The following example shows basic usage of an [`AudioContext`](audiocontext) to create an `AnalyserNode`, then [`requestAnimationFrame`](window/requestanimationframe) and [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. For more complete applied examples/information, check out our [Voice-change-O-matic](https://mdn.github.io/webaudio-examples/voice-change-o-matic/) demo (see [app.js lines 108-193](https://github.com/mdn/webaudio-examples/tree/main/voice-change-o-matic/scripts/app.js#L108-L193) for relevant code). 

 
```
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();

// …

const analyser = audioCtx.createAnalyser();
analyser.fftSize = 2048;

const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
analyser.getByteTimeDomainData(dataArray);

// Connect the source to be analysed
source.connect(analyser);

// Get a canvas defined with ID "oscilloscope"
const canvas = document.getElementById("oscilloscope");
const canvasCtx = canvas.getContext("2d");

// draw an oscilloscope of the current audio source

function draw() {
  requestAnimationFrame(draw);

  analyser.getByteTimeDomainData(dataArray);

  canvasCtx.fillStyle = "rgb(200, 200, 200)";
  canvasCtx.fillRect(0, 0, canvas.width, canvas.height);

  canvasCtx.lineWidth = 2;
  canvasCtx.strokeStyle = "rgb(0, 0, 0)";

  canvasCtx.beginPath();

  const sliceWidth = (canvas.width \* 1.0) / bufferLength;
  let x = 0;

  for (let i = 0; i < bufferLength; i++) {
    const v = dataArray[i] / 128.0;
    const y = (v \* canvas.height) / 2;

    if (i === 0) {
      canvasCtx.moveTo(x, y);
    } else {
      canvasCtx.lineTo(x, y);
    }

    x += sliceWidth;
  }

  canvasCtx.lineTo(canvas.width, canvas.height / 2);
  canvasCtx.stroke();
}

draw();

```


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # AnalyserNode](https://webaudio.github.io/web-audio-api/#AnalyserNode) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AnalyserNode` | 55 | 79 | 53 | No | 42 | 14.1 | 55 | 55 | 53 | 42 | 14.5 | 6.0 |
| `AnalyserNode` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `fftSize` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `frequencyBinCount` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `getByteFrequencyData` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `getByteTimeDomainData` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `getFloatFrequencyData` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `getFloatTimeDomainData` | 35 | 12 | 30 | No | 22 | 14.1 | 37 | 35 | 30 | 22 | 14.5 | 3.0 |
| `maxDecibels` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `minDecibels` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `smoothingTimeConstant` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode>

AnimationEvent
==============



The `AnimationEvent` interface represents events providing information related to [animations](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Animations/Using_CSS_animations).


 Event AnimationEvent

Constructor
-----------


 [`AnimationEvent()`](animationevent/animationevent)  Creates an `AnimationEvent` event with the given parameters.

  
Instance properties
-------------------



*Also inherits properties from its parent [`Event`](event)*.

  
[`AnimationEvent.animationName`](animationevent/animationname) Read only 
  A string containing the value of the [`animation-name`](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-name) that generated the animation.

  
[`AnimationEvent.elapsedTime`](animationevent/elapsedtime) Read only 
  A `float` giving the amount of time the animation has been running, in seconds, when this event fired, excluding any time the animation was paused. For an `animationstart` event, `elapsedTime` is `0.0` unless there was a negative value for [`animation-delay`](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-delay), in which case the event will be fired with `elapsedTime` containing `(-1 * delay)`.

  
[`AnimationEvent.pseudoElement`](animationevent/pseudoelement) Read only 
  A string, starting with `'::'`, containing the name of the [pseudo-element](https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements) the animation runs on. If the animation doesn't run on a pseudo-element but on the element, an empty string: `''`.

  

Instance methods
----------------


*Inherits methods from its parent, [`Event`](event)*.


Specifications
--------------




| Specification |
| --- |
| [CSS Animations Level 1 # interface-animationevent](https://w3c.github.io/csswg-drafts/css-animations/#interface-animationevent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AnimationEvent` | 43 | 14 | 23 | No | 30 | 96 | 43 | 43 | 23 | 30 | 96 | 4.0 |
| `AnimationEvent` | 431–70 | 12 | 5 | 10 | 3015–5712.1–1512–15 | 94 | 43≤37–70 | 4318–70 | 5 | 3014–4912.1–1412–14 | 93.2 | 4.01.0–10.0 |
| `animationName` | 43 | 12 | 5 | 10 | 30 | 9 | 43 | 43 | 5 | 30 | 9 | 4.0 |
| `elapsedTime` | 43 | 12 | 5 | 10 | 30 | 9 | 43 | 43 | 5 | 30 | 9 | 4.0 |
| `pseudoElement` | 68 | 79 | 23 | No | 55 | 13.1 | 68 | 68 | 23 | 48 | 13.4 | 10.0 |


See also
--------


* [Using CSS animations](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Animations/Using_CSS_animations)
* Animation-related CSS properties and at-rules: [`animation`](https://developer.mozilla.org/en-US/docs/Web/CSS/animation), [`animation-composition`](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-composition), [`animation-delay`](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-delay), [`animation-direction`](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-direction), [`animation-duration`](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-duration), [`animation-fill-mode`](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-fill-mode), [`animation-iteration-count`](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-iteration-count), [`animation-name`](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-name), [`animation-play-state`](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-play-state), [`animation-timing-function`](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-timing-function), [`@keyframes`](https://developer.mozilla.org/en-US/docs/Web/CSS/@keyframes).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent>

AnimationPlaybackEvent
======================



The AnimationPlaybackEvent interface of the [Web Animations API](web_animations_api) represents animation events.

 As animations play, they report changes to their [`playState`](animation/playstate) through animation events.


 Event AnimationPlaybackEvent

Constructor
-----------


 [`AnimationPlaybackEvent()`](animationplaybackevent/animationplaybackevent)  Constructs a new `AnimationPlaybackEvent` object instance.

  
Instance properties
-------------------


 
[`AnimationPlaybackEvent.currentTime`](animationplaybackevent/currenttime) Read only 
  The current time of the animation that generated the event.

  
[`AnimationPlaybackEvent.timelineTime`](animationplaybackevent/timelinetime) Read only 
  The time value of the timeline of the animation that generated the event.

  
Specifications
--------------




| Specification |
| --- |
| [Web Animations # the-animationplaybackevent-interface](https://w3c.github.io/csswg-drafts/web-animations-1/#the-animationplaybackevent-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AnimationPlaybackEvent` | 84 | 84 | 63 | No | 70 | 13.1 | 84 | 84 | 63 | 60 | 13.4 | 14.0 |
| `AnimationPlaybackEvent` | 84 | 84 | 63 | No | 70 | 13.1 | 84 | 84 | 63 | 60 | 13.4 | 14.0 |
| `currentTime` | 84 | 84 | 63 | No | 70 | 13.1 | 84 | 84 | 63 | 60 | 13.4 | 14.0 |
| `timelineTime` | 84 | 84 | 63 | No | 70 | 13.1 | 84 | 84 | 63 | 60 | 13.4 | 14.0 |


See also
--------


* [Web Animations API](web_animations_api)
* [`Animation.playState`](animation/playstate)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AnimationPlaybackEvent>

AnimationTimeline
=================


The `AnimationTimeline` interface of the [Web Animations API](web_animations_api) represents the timeline of an animation. This interface exists to define timeline features (inherited by [`DocumentTimeline`](documenttimeline) and future timeline types) and is not itself directly used by developers. Anywhere you see `AnimationTimeline`, you should use `DocumentTimeline` or any other timeline type instead.


Instance properties
-------------------


 
[`AnimationTimeline.currentTime`](animationtimeline/currenttime) Read only 
  Returns the time value in milliseconds for this timeline or `null` if this timeline is inactive.

  
Specifications
--------------




| Specification |
| --- |
| [Web Animations # the-animationtimeline-interface](https://w3c.github.io/csswg-drafts/web-animations-1/#the-animationtimeline-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AnimationTimeline` | 84 | 84 | 75 | No | 70 | 13.1 | 84 | 84 | 79 | 60 | 13.4 | 14.0 |
| `currentTime` | 84 | 84 | 75 | No | 70 | 13.1 | 84 | 84 | 79 | 60 | 13.4 | 14.0 |


See also
--------


* [Web Animations API](web_animations_api)
* [`DocumentTimeline`](documenttimeline)
* [`Document.timeline`](document/timeline)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AnimationTimeline>

Attr
====



The `Attr` interface represents one of an element's attributes as an object. In most situations, you will directly retrieve the attribute value as a string (e.g., [`Element.getAttribute()`](element/getattribute)), but certain functions (e.g., [`Element.getAttributeNode()`](element/getattributenode)) or means of iterating return `Attr` instances.


 EventTarget Node Attr The core idea of an object of type `Attr` is the association between a *name* and a *value*. An attribute may also be part of a *namespace* and, in this case, it also has a URI identifying the namespace, and a prefix that is an abbreviation for the namespace.

 The name is deemed *local* when it ignores the eventual namespace prefix and deemed *qualified* when it includes the prefix of the namespace, if any, separated from the local name by a colon (`:`). We have three cases: an attribute outside of a namespace, an attribute inside a namespace without a prefix defined, an attribute inside a namespace with a prefix:

 

| Attribute | Namespace name | Namespace prefix | Attribute local name | Attribute qualified name |
| --- | --- | --- | --- | --- |
| `myAttr` | *none* | *none* | `myAttr` | `myAttr` |
| `myAttr` | `mynamespace` | *none* | `myAttr` | `myAttr` |
| `myAttr` | `mynamespace` | `myns` | `myAttr` | `myns:myAttr` |

  **Note:** This interface represents only attributes present in the tree representation of the [`Element`](element), being a SVG, an HTML or a MathML element. It doesn't represent the *property* of an interface associated with such element, such as [`HTMLTableElement`](htmltableelement) for a [`<table>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table) element. (See [this article](https://developer.mozilla.org/en-US/docs/Glossary/Attribute) for more information about attributes and how they are *reflected* into properties.)

 

Instance properties
-------------------



*This interface also inherits the properties of its parent interfaces, [`Node`](node) and [`EventTarget`](eventtarget).*

  
[`localName`](attr/localname) Read only 
  A string representing the local part of the qualified name of the attribute.

  
[`name`](attr/name) Read only 
  The attribute's *qualified name*. If the attribute is not in a namespace, it will be the same as [`localName`](attr/localname) property.

  
[`namespaceURI`](attr/namespaceuri) Read only 
  A string representing the URI of the namespace of the attribute, or `null` if there is no namespace.

  
[`ownerElement`](attr/ownerelement) Read only 
  The [`Element`](element) the attribute belongs to.

  
[`prefix`](attr/prefix) Read only 
  A string representing the namespace prefix of the attribute, or `null` if a namespace without prefix or no namespace are specified.

  
[`specified`](attr/specified) Read only   Deprecated 
  This property always returns `true`.

  [`value`](attr/value)  The attribute's value, a string that can be set and get using this property.

  

Instance methods
----------------


*This interface has no specific methods, but inherits the methods of its parent interfaces, [`Node`](node) and [`EventTarget`](eventtarget).*


Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-attr](https://dom.spec.whatwg.org/#interface-attr) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Attr` | 1 | 12 | 1 | 5.5 | 8 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `localName` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `name` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `namespaceURI` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `ownerElement` | 1 | 12 | 1 | 8 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `prefix` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `specified` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `value` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* Other nodes are [`CDATASection`](cdatasection), [`CharacterData`](characterdata), [`Comment`](comment), [`Document`](document), [`Element`](element), [`ProcessingInstruction`](processinginstruction), and [`Text`](text).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Attr>

AudioBuffer
===========



The `AudioBuffer` interface represents a short audio asset residing in memory, created from an audio file using the [`AudioContext.decodeAudioData()`](baseaudiocontext/decodeaudiodata) method, or from raw data using [`AudioContext.createBuffer()`](baseaudiocontext/createbuffer). Once put into an AudioBuffer, the audio can then be played by being passed into an [`AudioBufferSourceNode`](audiobuffersourcenode).

 Objects of these types are designed to hold small audio snippets, typically less than 45 s. For longer sounds, objects implementing the [`MediaElementAudioSourceNode`](mediaelementaudiosourcenode) are more suitable. The buffer contains the audio signal waveform encoded as a series of amplitudes in the following format: non-interleaved IEEE754 32-bit linear PCM with a nominal range between `-1` and `+1`, that is, a 32-bit floating point buffer, with each sample between -1.0 and 1.0. If the [`AudioBuffer`](audiobuffer) has multiple channels, they are stored in separate buffers.



Constructor
-----------


 [`AudioBuffer()`](audiobuffer/audiobuffer)  Creates and returns a new `AudioBuffer` object instance.

  
Instance properties
-------------------


 
[`AudioBuffer.sampleRate`](audiobuffer/samplerate) Read only 
  Returns a float representing the sample rate, in samples per second, of the PCM data stored in the buffer.

  
[`AudioBuffer.length`](audiobuffer/length) Read only 
  Returns an integer representing the length, in sample-frames, of the PCM data stored in the buffer.

  
[`AudioBuffer.duration`](audiobuffer/duration) Read only 
  Returns a double representing the duration, in seconds, of the PCM data stored in the buffer.

  
[`AudioBuffer.numberOfChannels`](audiobuffer/numberofchannels) Read only 
  Returns an integer representing the number of discrete audio channels described by the PCM data stored in the buffer.

  
Instance methods
----------------


 [`AudioBuffer.getChannelData()`](audiobuffer/getchanneldata)  Returns a [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) containing the PCM data associated with the channel, defined by the `channel` parameter (with `0` representing the first channel).

  [`AudioBuffer.copyFromChannel()`](audiobuffer/copyfromchannel)  Copies the samples from the specified channel of the `AudioBuffer` to the `destination` array.

  [`AudioBuffer.copyToChannel()`](audiobuffer/copytochannel)  Copies the samples to the specified channel of the `AudioBuffer`, from the `source` array.

  
Example
-------



The following simple example shows how to create an `AudioBuffer` and fill it with random white noise. You can find the full source code at our [webaudio-examples](https://github.com/mdn/webaudio-examples) repository; a [running live](https://mdn.github.io/webaudio-examples/audio-buffer/) version is also available.

 
```
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();

// Create an empty three-second stereo buffer at the sample rate of the AudioContext
const myArrayBuffer = audioCtx.createBuffer(
  2,
  audioCtx.sampleRate \* 3,
  audioCtx.sampleRate
);

// Fill the buffer with white noise;
// just random values between -1.0 and 1.0
for (let channel = 0; channel < myArrayBuffer.numberOfChannels; channel++) {
  // This gives us the actual array that contains the data
  const nowBuffering = myArrayBuffer.getChannelData(channel);
  for (let i = 0; i < myArrayBuffer.length; i++) {
    // Math.random() is in [0; 1.0]
    // audio needs to be in [-1.0; 1.0]
    nowBuffering[i] = Math.random() \* 2 - 1;
  }
}

// Get an AudioBufferSourceNode.
// This is the AudioNode to use when we want to play an AudioBuffer
const source = audioCtx.createBufferSource();

// set the buffer in the AudioBufferSourceNode
source.buffer = myArrayBuffer;

// connect the AudioBufferSourceNode to the
// destination so we can hear the sound
source.connect(audioCtx.destination);

// start the source playing
source.start();

```


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # AudioBuffer](https://webaudio.github.io/web-audio-api/#AudioBuffer) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AudioBuffer` | 55The `context` parameter was supported up until version 57, but has now been removed. | 79 | 53 | No | 42The `context` parameter was supported up until version 44, but has now been removed. | 14.1 | 55The `context` parameter was supported up until version 57, but has now been removed. | 55The `context` parameter was supported up until version 57, but has now been removed. | 53 | 42The `context` parameter was supported up until version 44, but has now been removed. | 14.5 | 6.0The `context` parameter was supported up until Samsung Internet 7.0, but has now been removed. |
| `AudioBuffer` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `copyFromChannel` | 43 | 13 | 27 | No | 30 | 14.1 | 43 | 43 | 27 | 30 | 14.5 | 4.0 |
| `copyToChannel` | 43 | 13 | 27 | No | 30 | 14.1 | 43 | 43 | 27 | 30 | 14.5 | 4.0 |
| `duration` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `getChannelData` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `length` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `numberOfChannels` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `sampleRate` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AudioBuffer>

AudioBufferSourceNode
=====================



The `AudioBufferSourceNode` interface is an [`AudioScheduledSourceNode`](audioscheduledsourcenode) which represents an audio source consisting of in-memory audio data, stored in an [`AudioBuffer`](audiobuffer).

 This interface is especially useful for playing back audio which has particularly stringent timing accuracy requirements, such as for sounds that must match a specific rhythm and can be kept in memory rather than being played from disk or the network. To play sounds which require accurate timing but must be streamed from the network or played from disk, use a [`AudioWorkletNode`](audioworkletnode) to implement its playback.


 EventTarget AudioNode AudioScheduledSourceNode AudioBufferSourceNode An `AudioBufferSourceNode` has no inputs and exactly one output, which has the same number of channels as the `AudioBuffer` indicated by its [`buffer`](audiobuffersourcenode/buffer) property. If there's no buffer set—that is, if `buffer` is `null`—the output contains a single channel of silence (every sample is 0).

 An `AudioBufferSourceNode` can only be played once; after each call to [`start()`](audioscheduledsourcenode/start), you have to create a new node if you want to play the same sound again. Fortunately, these nodes are very inexpensive to create, and the actual `AudioBuffer`s can be reused for multiple plays of the sound. Indeed, you can use these nodes in a "fire and forget" manner: create the node, call `start()` to begin playing the sound, and don't even bother to hold a reference to it. It will automatically be garbage-collected at an appropriate time, which won't be until sometime after the sound has finished playing.

 Multiple calls to [`stop()`](audioscheduledsourcenode/stop) are allowed. The most recent call replaces the previous one, if the `AudioBufferSourceNode` has not already reached the end of the buffer.

  ![The AudioBufferSourceNode takes the content of an AudioBuffer and m] 

 

|  |  |
| --- | --- |
| Number of inputs | `0` |
| Number of outputs | `1` |
| Channel count | defined by the associated [`AudioBuffer`](audiobuffer) |



Constructor
-----------


 [`AudioBufferSourceNode()`](audiobuffersourcenode/audiobuffersourcenode)  Creates and returns a new `AudioBufferSourceNode` object. As an alternative, you can use the [`BaseAudioContext.createBufferSource()`](baseaudiocontext/createbuffersource) factory method; see [Creating an AudioNode](audionode#creating_an_audionode).

  
Instance properties
-------------------



*Inherits properties from its parent, [`AudioScheduledSourceNode`](audioscheduledsourcenode)*.

  [`AudioBufferSourceNode.buffer`](audiobuffersourcenode/buffer)  An [`AudioBuffer`](audiobuffer) that defines the audio asset to be played, or when set to the value `null`, defines a single channel of silence (in which every sample is 0.0).

  [`AudioBufferSourceNode.detune`](audiobuffersourcenode/detune)  A [k-rate](audioparam#k-rate) [`AudioParam`](audioparam) representing detuning of playback in [cents](https://en.wikipedia.org/wiki/Cent_%28music%29). This value is compounded with `playbackRate` to determine the speed at which the sound is played. Its default value is `0` (meaning no detuning), and its nominal range is -∞ to ∞.

  [`AudioBufferSourceNode.loop`](audiobuffersourcenode/loop)  A Boolean attribute indicating if the audio asset must be replayed when the end of the [`AudioBuffer`](audiobuffer) is reached. Its default value is `false`.

  
[`AudioBufferSourceNode.loopStart`](audiobuffersourcenode/loopstart) Optional
  A floating-point value indicating the time, in seconds, at which playback of the [`AudioBuffer`](audiobuffer) must begin when `loop` is `true`. Its default value is `0` (meaning that at the beginning of each loop, playback begins at the start of the audio buffer).

  
[`AudioBufferSourceNode.loopEnd`](audiobuffersourcenode/loopend) Optional
  A floating-point number indicating the time, in seconds, at which playback of the [`AudioBuffer`](audiobuffer) stops and loops back to the time indicated by `loopStart`, if `loop` is `true`. The default value is `0`.

  [`AudioBufferSourceNode.playbackRate`](audiobuffersourcenode/playbackrate)  A [k-rate](audioparam#k-rate) [`AudioParam`](audioparam) that defines the speed factor at which the audio asset will be played, where a value of 1.0 is the sound's natural sampling rate. Since no pitch correction is applied on the output, this can be used to change the pitch of the sample. This value is compounded with `detune` to determine the final playback rate.

  

Instance methods
----------------



*Inherits methods from its parent, [`AudioScheduledSourceNode`](audioscheduledsourcenode), and overrides the following method:*.

  [`start()`](audiobuffersourcenode/start)  Schedules playback of the audio data contained in the buffer, or begins playback immediately. Additionally allows the start offset and play duration to be set.

  

Event handlers
--------------


*Inherits event handlers from its parent, [`AudioScheduledSourceNode`](audioscheduledsourcenode)*.


Examples
--------



In this example, we create a two-second buffer, fill it with white noise, and then play it using an `AudioBufferSourceNode`. The comments should clearly explain what is going on.

  **Note:** You can also [run the code live](https://mdn.github.io/webaudio-examples/audio-buffer/), or [view the source](https://github.com/mdn/webaudio-examples/blob/master/audio-buffer/index.html).

  
```
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();

// Create an empty three-second stereo buffer at the sample rate of the AudioContext
const myArrayBuffer = audioCtx.createBuffer(
  2,
  audioCtx.sampleRate \* 3,
  audioCtx.sampleRate
);

// Fill the buffer with white noise;
//just random values between -1.0 and 1.0
for (let channel = 0; channel < myArrayBuffer.numberOfChannels; channel++) {
  // This gives us the actual ArrayBuffer that contains the data
  const nowBuffering = myArrayBuffer.getChannelData(channel);
  for (let i = 0; i < myArrayBuffer.length; i++) {
    // Math.random() is in [0; 1.0]
    // audio needs to be in [-1.0; 1.0]
    nowBuffering[i] = Math.random() \* 2 - 1;
  }
}

// Get an AudioBufferSourceNode.
// This is the AudioNode to use when we want to play an AudioBuffer
const source = audioCtx.createBufferSource();
// set the buffer in the AudioBufferSourceNode
source.buffer = myArrayBuffer;
// connect the AudioBufferSourceNode to the
// destination so we can hear the sound
source.connect(audioCtx.destination);
// start the source playing
source.start();

```
  **Note:** For a `decodeAudioData()` example, see the [`AudioContext.decodeAudioData()`](baseaudiocontext/decodeaudiodata) page.

 

Specifications
--------------




| Specification |
| --- |
| [Web Audio API # AudioBufferSourceNode](https://webaudio.github.io/web-audio-api/#AudioBufferSourceNode) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AudioBufferSourceNode` | 55 | 79 | 53 | No | 42 | 14.1 | 55 | 55 | 53 | 42 | 14.5 | 6.0 |
| `AudioBufferSourceNode` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `buffer` | 14 | 12 | 25Firefox currently handles the value `null` incorrectly. Instead of producing a node that generates a single channel of silence, the node becomes unusable and will be ignored if you attempt to connect it to anything. | No | 15 | 6 | 4.4.3 | 18 | 25Firefox currently handles the value `null` incorrectly. Instead of producing a node that generates a single channel of silence, the node becomes unusable and will be ignored if you attempt to connect it to anything. | 14 | 6 | 1.0 |
| `detune` | 44 | 13 | 40 | No | 31 | 14.1 | 44 | 44 | 40 | 32 | 14.5 | 4.0 |
| `loop` | 15 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `loopEnd` | 24 | 12 | 25 | No | 15 | 7 | 4.4.3 | 25 | 25 | 14 | 7 | 1.5 |
| `loopStart` | 24 | 12 | 25 | No | 15 | 7 | 4.4.3 | 25 | 25 | 14 | 7 | 1.5 |
| `playbackRate` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `start` | 24 | 12 | 25 | No | 15 | 7 | 4.4.3 | 25 | 25 | 14 | 7 | 1.5 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)
* [Web Audio API](web_audio_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AudioBufferSourceNode>

AudioContext
============



The `AudioContext` interface represents an audio-processing graph built from audio modules linked together, each represented by an [`AudioNode`](audionode).

 An audio context controls both the creation of the nodes it contains and the execution of the audio processing, or decoding. You need to create an `AudioContext` before you do anything else, as everything happens inside a context. It's recommended to create one AudioContext and reuse it instead of initializing a new one each time, and it's OK to use a single `AudioContext` for several different audio sources and pipeline concurrently.


 EventTarget BaseAudioContext AudioContext

Constructor
-----------


 [`AudioContext()`](audiocontext/audiocontext)  Creates and returns a new `AudioContext` object.

  
Instance properties
-------------------



*Also inherits properties from its parent interface, [`BaseAudioContext`](baseaudiocontext).*

  
[`AudioContext.baseLatency`](audiocontext/baselatency) Read only 
  Returns the number of seconds of processing latency incurred by the [`AudioContext`](audiocontext) passing the audio from the [`AudioDestinationNode`](audiodestinationnode) to the audio subsystem.

  
[`AudioContext.outputLatency`](audiocontext/outputlatency) Read only 
  Returns an estimation of the output latency of the current audio context.

  
[`AudioContext.sinkId`](audiocontext/sinkid) Read only   Experimental 
  Returns the sink ID of the current output audio device.

  

Instance methods
----------------



*Also inherits methods from its parent interface, [`BaseAudioContext`](baseaudiocontext).*

  [`AudioContext.close()`](audiocontext/close)  Closes the audio context, releasing any system audio resources that it uses.

  [`AudioContext.createMediaElementSource()`](audiocontext/createmediaelementsource)  Creates a [`MediaElementAudioSourceNode`](mediaelementaudiosourcenode) associated with an [`HTMLMediaElement`](htmlmediaelement). This can be used to play and manipulate audio from [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) or [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) elements.

  [`AudioContext.createMediaStreamSource()`](audiocontext/createmediastreamsource)  Creates a [`MediaStreamAudioSourceNode`](mediastreamaudiosourcenode) associated with a [`MediaStream`](mediastream) representing an audio stream which may come from the local computer microphone or other sources.

  [`AudioContext.createMediaStreamDestination()`](audiocontext/createmediastreamdestination)  Creates a [`MediaStreamAudioDestinationNode`](mediastreamaudiodestinationnode) associated with a [`MediaStream`](mediastream) representing an audio stream which may be stored in a local file or sent to another computer.

  [`AudioContext.createMediaStreamTrackSource()`](audiocontext/createmediastreamtracksource)  Creates a [`MediaStreamTrackAudioSourceNode`](mediastreamtrackaudiosourcenode) associated with a [`MediaStream`](mediastream) representing an media stream track.

  [`AudioContext.getOutputTimestamp()`](audiocontext/getoutputtimestamp)  Returns a new `AudioTimestamp` object containing two audio timestamp values relating to the current audio context.

  [`AudioContext.resume()`](audiocontext/resume)  Resumes the progression of time in an audio context that has previously been suspended/paused.

  
[`AudioContext.setSinkId()`](audiocontext/setsinkid)  Experimental 
  Sets the output audio device for the `AudioContext`.

  [`AudioContext.suspend()`](audiocontext/suspend)  Suspends the progression of time in the audio context, temporarily halting audio hardware access and reducing CPU/battery usage in the process.

  

Events
------


 
[`sinkchange`](audiocontext/sinkchange_event)  Experimental 
  Fired when the output audio device (and therefore, the [`AudioContext.sinkId`](audiocontext/sinkid)) has changed.

  
Examples
--------



Basic audio context declaration:

 
```
const audioCtx = new AudioContext();

const oscillatorNode = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
const finish = audioCtx.destination;
// etc.

```


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # AudioContext](https://webaudio.github.io/web-audio-api/#AudioContext) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AudioContext` | 35["Before Chrome 66, each tab is limited to 6 audio contexts in Chrome; attempting to create more will throw a `DOMException`. For details see [Per-tab audio context limitation in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Per-tab_audio_context_limitation_in_Chrome).", "If `latencyHint` isn't valid, Chrome throws a `TypeError` exception. See [Non-standard exceptions in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Non-standard_exceptions_in_Chrome) for details."]14–57 | 12 | 25 | No | 22["Before Opera 53, each tab is limited to 6 audio contexts in Opera; attempting to create more will throw a `DOMException`. For details see [Per-tab audio context limitation in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Per-tab_audio_context_limitation_in_Chrome).", "If `latencyHint` isn't valid, Opera throws a `TypeError` exception. See [Non-standard exceptions in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Non-standard_exceptions_in_Chrome) for details."]15–44 | 14.16 | 37["Before WebView 66, each tab is limited to 6 audio contexts in WebView; attempting to create more will throw a `DOMException`. For details see [Per-tab audio context limitation in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Per-tab_audio_context_limitation_in_Chrome).", "If `latencyHint` isn't valid, WebView throws a `TypeError` exception. See [Non-standard exceptions in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Non-standard_exceptions_in_Chrome) for details."]≤37–57 | 35["Before Chrome 66, each tab is limited to 6 audio contexts in Chrome; attempting to create more will throw a `DOMException`. For details see [Per-tab audio context limitation in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Per-tab_audio_context_limitation_in_Chrome).", "If `latencyHint` isn't valid, Chrome throws a `TypeError` exception. See [Non-standard exceptions in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Non-standard_exceptions_in_Chrome) for details."]18–57 | 25 | 22["Before Opera Android 47, each tab is limited to 6 audio contexts in Opera; attempting to create more will throw a `DOMException`. For details see [Per-tab audio context limitation in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Per-tab_audio_context_limitation_in_Chrome).", "If `latencyHint` isn't valid, Opera throws a `TypeError` exception. See [Non-standard exceptions in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Non-standard_exceptions_in_Chrome) for details."]14–43 | 14.56 | 3.0["Before Samsung Internet 9.0, each tab is limited to 6 audio contexts in Samsung Internet; attempting to create more will throw a `DOMException`. For details see [Per-tab audio context limitation in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Per-tab_audio_context_limitation_in_Chrome).", "If `latencyHint` isn't valid, Samsung Internet throws a `TypeError` exception. See [Non-standard exceptions in Chrome](https://developer.mozilla.org/docs/Web/API/AudioContext/AudioContext#Non-standard_exceptions_in_Chrome) for details."]1.0–7.0 |
| `AudioContext` | 3514–57 | 12 | 25 | No | 2215–44 | 14.16–14.1 | 374.4–57 | 3518–57 | 25 | 2214–43 | 14.56–14.5 | 3.01.0–7.0 |
| `baseLatency` | 58 | 79 | 70 | No | 45 | 14.1 | 58 | 58 | 79 | 43 | 14.5 | 7.0 |
| `close` | 42 | 14 | 40 | No | 29 | 9 | 42 | 42 | 40 | 29 | 9 | 4.0 |
| `createMediaElementSource` | 15 | 12 | 25 | No | 15 | 6 | ≤37 | 18 | 25 | 14 | 6 | 1.0 |
| `createMediaStreamDestination` | 25 | 79 | 25 | No | 15 | 11 | ≤37 | 25 | 25 | 14 | 11 | 1.5 |
| `createMediaStreamSource` | 22 | 12 | 25 | No | 15 | 11 | ≤37 | 25 | 25 | 14 | 11 | 1.5 |
| `createMediaStreamTrackSource` | No | No | 68Firefox 68 implements the updated standard's definition of the "first" audio track; now the first track is the one whose ID comes first lexicographically. | No | No | No | No | No | 68Firefox 68 implements the updated standard's definition of the "first" audio track; now the first track is the one whose ID comes first lexicographically. | No | No | No |
| `getOutputTimestamp` | 57 | 79 | 70 | No | 44 | 14.1 | 57 | 57 | 79 | 43 | 14.5 | 7.0 |
| `outputLatency` | 102 | 102 | 70 | No | 88 | No | 102 | 102 | 79 | 70 | No | 19.0 |
| `resume` | 41 | 14 | 40 | No | 28 | 9 | 41 | 41 | 40 | 28 | 9 | 4.0 |
| `setSinkId` | 110 | 110 | No | No | 96 | No | 110 | 110 | No | 74 | No | No |
| `sinkId` | 110 | 110 | No | No | 96 | No | 110 | 110 | No | 74 | No | No |
| `sinkchange_event` | 110 | 110 | No | No | 96 | No | 110 | 110 | No | 74 | No | No |
| `suspend` | 41 | 14 | 40 | No | 28 | 9 | 41 | 41 | 40 | 28 | 9 | 4.0 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)
* [`OfflineAudioContext`](offlineaudiocontext)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AudioContext>

AudioEncoder
============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `AudioEncoder` interface of the [WebCodecs API](webcodecs_api) encodes [`AudioData`](audiodata) objects.


 EventTarget AudioEncoder

Constructor
-----------


 
[`AudioEncoder()`](audioencoder/audioencoder)  Experimental 
  Creates a new `AudioEncoder` object.

  
Instance properties
-------------------



*Inherits properties from its parent, [`EventTarget`](eventtarget).*

  
[`AudioEncoder.encodeQueueSize`](audioencoder/encodequeuesize) Read only   Experimental 
  An integer representing the number of encode queue requests.

  
[`AudioEncoder.state`](audioencoder/state) Read only   Experimental 
  Represents the state of the underlying codec and whether it is configured for encoding.

  

### Events


 
[`dequeue`](audioencoder/dequeue_event)  Experimental 
  Fires to signal a decrease in [`AudioEncoder.encodeQueueSize`](audioencoder/encodequeuesize).

  
Static methods
--------------


 
[`AudioEncoder.isConfigSupported()`](audioencoder/isconfigsupported)  Experimental 
  Returns a promise indicating whether the provided `AudioEncoderConfig` is supported.

  
Instance methods
----------------



*Inherits methods from its parent, [`EventTarget`](eventtarget).*

  
[`AudioEncoder.configure()`](audioencoder/configure)  Experimental 
  Enqueues a control message to configure the audio encoder for encoding chunks.

  
[`AudioEncoder.encode()`](audioencoder/encode)  Experimental 
  Enqueues a control message to encode a given [`AudioData`](audiodata) objects.

  
[`AudioEncoder.flush()`](audioencoder/flush)  Experimental 
  Returns a promise that resolves once all pending messages in the queue have been completed.

  
[`AudioEncoder.reset()`](audioencoder/reset)  Experimental 
  Resets all states including configuration, control messages in the control message queue, and all pending callbacks.

  
[`AudioEncoder.close()`](audioencoder/close)  Experimental 
  Ends all pending work and releases system resources.

  

Specifications
--------------




| Specification |
| --- |
| [WebCodecs # audioencoder-interface](https://w3c.github.io/webcodecs/#audioencoder-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AudioEncoder` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `AudioEncoder` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `close` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `configure` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `dequeue_event` | 106 | 106 | No | No | 92 | No | 106 | 106 | No | 72 | No | 20.0 |
| `encode` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `encodeQueueSize` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `flush` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `isConfigSupported` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `reset` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `state` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AudioEncoder>

AudioListener
=============



The `AudioListener` interface represents the position and orientation of the unique person listening to the audio scene, and is used in [audio spatialization](web_audio_api/web_audio_spatialization_basics). All [`PannerNode`](pannernode)s spatialize in relation to the `AudioListener` stored in the [`BaseAudioContext.listener`](baseaudiocontext/listener) attribute.

 It is important to note that there is only one listener per context and that it isn't an [`AudioNode`](audionode).

  ![We see the position, up and front vectors of an AudioListener, with the up and front vectors at 90° from the other.] 



Instance properties
-------------------



 **Note:** The position, forward, and up value are set and retrieved using different syntaxes. Retrieval is done by accessing, for example, `AudioListener.positionX`, while setting the same property is done with `AudioListener.positionX.value`. This is why these values are not marked read only, which is how they appear in the specification's IDL.

   [`AudioListener.positionX`](audiolistener/positionx)  Represents the horizontal position of the listener in a right-hand cartesian coordinate system. The default is 0.

  [`AudioListener.positionY`](audiolistener/positiony)  Represents the vertical position of the listener in a right-hand cartesian coordinate system. The default is 0.

  [`AudioListener.positionZ`](audiolistener/positionz)  Represents the longitudinal (back and forth) position of the listener in a right-hand cartesian coordinate system. The default is 0.

  [`AudioListener.forwardX`](audiolistener/forwardx)  Represents the horizontal position of the listener's forward direction in the same cartesian coordinate system as the position (`positionX`, `positionY`, and `positionZ`) values. The forward and up values are linearly independent of each other. The default is 0.

  [`AudioListener.forwardY`](audiolistener/forwardy)  Represents the vertical position of the listener's forward direction in the same cartesian coordinate system as the position (`positionX`, `positionY`, and `positionZ`) values. The forward and up values are linearly independent of each other. The default is 0.

  [`AudioListener.forwardZ`](audiolistener/forwardz)  Represents the longitudinal (back and forth) position of the listener's forward direction in the same cartesian coordinate system as the position (`positionX`, `positionY`, and `positionZ`) values. The forward and up values are linearly independent of each other. The default is -1.

  [`AudioListener.upX`](audiolistener/upx)  Represents the horizontal position of the top of the listener's head in the same cartesian coordinate system as the position (`positionX`, `positionY`, and `positionZ`) values. The forward and up values are linearly independent of each other. The default is 0.

  [`AudioListener.upY`](audiolistener/upy)  Represents the vertical position of the top of the listener's head in the same cartesian coordinate system as the position (`positionX`, `positionY`, and `positionZ`) values. The forward and up values are linearly independent of each other. The default is 1.

  [`AudioListener.upZ`](audiolistener/upz)  Represents the longitudinal (back and forth) position of the top of the listener's head in the same cartesian coordinate system as the position (`positionX`, `positionY`, and `positionZ`) values. The forward and up values are linearly independent of each other. The default is 0.

  

Instance methods
----------------



 
[`AudioListener.setOrientation()`](audiolistener/setorientation)  Deprecated 
  Sets the orientation of the listener.

  
[`AudioListener.setPosition()`](audiolistener/setposition)  Deprecated 
  Sets the position of the listener.

    **Note:** Although these methods are deprecated they are currently the only way to set the orientation and position in Firefox.

 

Deprecated features
-------------------



 
[`AudioListener.dopplerFactor`](audiolistener/dopplerfactor)  Deprecated 
  A double value representing the amount of pitch shift to use when rendering a [doppler effect](https://en.wikipedia.org/wiki/Doppler_effect).

  
[`AudioListener.speedOfSound`](audiolistener/speedofsound)  Deprecated 
  A double value representing the speed of sound, in *meters per second*.

   In a previous version of the specification, the `dopplerFactor` and `speedOfSound` properties and the `setPosition()` method could be used to control the doppler effect applied to [`AudioBufferSourceNode`](audiobuffersourcenode)s connected downstream — these would be pitched up and down according to the relative speed of the [`PannerNode`](pannernode) and the [`AudioListener`](audiolistener). These features had a number of problems:

 * Only [`AudioBufferSourceNode`](audiobuffersourcenode)s were pitched up or down, not other source nodes.
* The behavior to adopt when an [`AudioBufferSourceNode`](audiobuffersourcenode) was connected to multiple [`PannerNode`](pannernode)s was unclear.
* Because the velocity of the panner and the listener were not [`AudioParam`](audioparam)s, the pitch modification could not be smoothly applied, resulting in audio glitches.

 Because of these issues, these properties and methods have been removed.

 The `setOrientation()` and `setPosition()` methods have been replaced by setting their property value equivalents. For example `setPosition(x, y, z)` can be achieved by setting `positionX.value`, `positionY.value`, and `positionZ.value` respectively.



Example
-------


See [`BaseAudioContext.createPanner()`](baseaudiocontext/createpanner#examples) for example code.


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # AudioListener](https://webaudio.github.io/web-audio-api/#AudioListener) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AudioListener` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `dopplerFactor` | 14–56 | 12–79 | 25–63 | No | 15–43 | 6–14.1 | ≤37–56 | 18–56 | 25–63 | 14–43 | 6–14.5 | 1.0–6.0 |
| `forwardX` | 52 | 79 | NoSupports a deprecated way of setting orientation - the `setOrientation()` method. | No | 39 | 14.1 | 52 | 52 | NoSupports a deprecated way of setting orientation - the `setOrientation()` method. | 41 | 14.5 | 6.0 |
| `forwardY` | 52 | 79 | NoSupports a deprecated way of setting orientation - the `setOrientation()` method. | No | 39 | 14.1 | 52 | 52 | NoSupports a deprecated way of setting orientation - the `setOrientation()` method. | 41 | 14.5 | 6.0 |
| `forwardZ` | 52 | 79 | NoSupports a deprecated way of setting orientation - the `setOrientation()` method. | No | 39 | 14.1 | 52 | 52 | NoSupports a deprecated way of setting orientation - the `setOrientation()` method. | 41 | 14.5 | 6.0 |
| `positionX` | 52 | 79 | NoSupports a deprecated way of setting orientation - the `setOrientation()` method. | No | 39 | 14.1 | 52 | 52 | NoSupports a deprecated way of setting orientation - the `setOrientation()` method. | 41 | 14.5 | 6.0 |
| `positionY` | 52 | 79 | NoSupports a deprecated way of setting orientation - the `setOrientation()` method. | No | 39 | 14.1 | 52 | 52 | NoSupports a deprecated way of setting orientation - the `setOrientation()` method. | 41 | 14.5 | 6.0 |
| `positionZ` | 52 | 79 | NoSupports a deprecated way of setting orientation - the `setOrientation()` method. | No | 39 | 14.1 | 52 | 52 | NoSupports a deprecated way of setting orientation - the `setOrientation()` method. | 41 | 14.5 | 6.0 |
| `setOrientation` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `setPosition` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `speedOfSound` | 14–56 | 12–79 | 25–63 | No | 15–43 | 6–14.1 | ≤37–56 | 18–56 | 25–63 | 14–43 | 6–14.5 | 1.0–6.0 |
| `upX` | 52 | 79 | NoSupports a deprecated way of setting orientation - the `setOrientation()` method. | No | 39 | 14.1 | 52 | 52 | NoSupports a deprecated way of setting orientation - the `setOrientation()` method. | 41 | 14.5 | 6.0 |
| `upY` | 52 | 79 | NoSupports a deprecated way of setting orientation - the `setOrientation()` method. | No | 39 | 14.1 | 52 | 52 | NoSupports a deprecated way of setting orientation - the `setOrientation()` method. | 41 | 14.5 | 6.0 |
| `upZ` | 52 | 79 | NoSupports a deprecated way of setting orientation - the `setOrientation()` method. | No | 39 | 14.1 | 52 | 52 | NoSupports a deprecated way of setting orientation - the `setOrientation()` method. | 41 | 14.5 | 6.0 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AudioListener>

AudioData
=========



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `AudioData` interface of the [WebCodecs API](webcodecs_api) represents an audio sample.

 `AudioData` is a [transferable object](web_workers_api/transferable_objects).



Description
-----------



An audio track consists of a stream of audio samples, each sample representing a captured moment of sound. An `AudioData` object is a representation of such a sample. Working alongside the interfaces of the [Insertable Streams API](insertable_streams_for_mediastreamtrack_api), you can break a stream into individual `AudioData` objects with [`MediaStreamTrackProcessor`](mediastreamtrackprocessor), or construct an audio track from a stream of frames with [`MediaStreamTrackGenerator`](mediastreamtrackgenerator).

  **Note:** Find out more about audio on the web in [Digital audio concepts](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Audio_concepts).

 

### The media resource


An `AudioData` object contains a reference to an attached **media resource**. This media resource contains the actual audio sample data described by the object. A media resource is maintained by the user agent until it is no longer referenced by an `AudioData` object, for example when [`AudioData.close()`](audiodata/close) is called.


### Planes and audio format



To return the sample format of an `AudioData` use the [`AudioData.format`](audiodata/format) property. The format may be described as **interleaved** or **planar**. In interleaved formats, the audio samples from the different channels are laid out in a single buffer, described as a **plane**. This plane contains a number of elements equal to [`AudioData.numberOfFrames`](audiodata/numberofframes) \* [`AudioData.numberOfChannels`](audiodata/numberofchannels).

 In planar format, the number of planes is equal to [`AudioData.numberOfChannels`](audiodata/numberofchannels), and each plane is a buffer containing a number of elements equal to [`AudioData.numberOfFrames`](audiodata/numberofframes).



Constructor
-----------


 
[`AudioData()`](audiodata/audiodata)  Experimental 
  Creates a new `AudioData` object.

  
Instance properties
-------------------


 
[`AudioData.format`](audiodata/format) Read only   Experimental 
  Returns the sample format of the audio.

  
[`AudioData.sampleRate`](audiodata/samplerate) Read only   Experimental 
  Returns the sample rate of the audio in Hz.

  
[`AudioData.numberOfFrames`](audiodata/numberofframes) Read only   Experimental 
  Returns the number of frames.

  
[`AudioData.numberOfChannels`](audiodata/numberofchannels) Read only   Experimental 
  Returns the number of audio channels.

  
[`AudioData.duration`](audiodata/duration) Read only   Experimental 
  Returns the duration of the audio in microseconds.

  
[`AudioData.timestamp`](audiodata/timestamp) Read only   Experimental 
  Returns the timestamp of the audio in microseconds.

  
Instance methods
----------------


 
[`AudioData.allocationSize()`](audiodata/allocationsize)  Experimental 
  Returns the number of bytes required to hold the sample as filtered by options passed into the method.

  
[`AudioData.copyTo()`](audiodata/copyto)  Experimental 
  Copies the samples from the specified plane of the `AudioData` object to the destination.

  
[`AudioData.clone()`](audiodata/clone)  Experimental 
  Creates a new `AudioData` object with reference to the same media resource as the original.

  
[`AudioData.close()`](audiodata/close)  Experimental 
  Clears all states and releases the reference to the media resource.

  
Specifications
--------------




| Specification |
| --- |
| [WebCodecs # audiodata-interface](https://w3c.github.io/webcodecs/#audiodata-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AudioData` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `AudioData` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `allocationSize` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `clone` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `close` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `copyTo` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `duration` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `format` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `numberOfChannels` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `numberOfFrames` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `sampleRate` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `timestamp` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AudioData>

AudioDecoder
============



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `AudioDecoder` interface of the [WebCodecs API](webcodecs_api) decodes chunks of audio.


 EventTarget AudioDecoder

Constructor
-----------


 
[`AudioDecoder()`](audiodecoder/audiodecoder)  Experimental 
  Creates a new `AudioDecoder` object.

  
Instance properties
-------------------



*Inherits properties from its parent, [`EventTarget`](eventtarget).*

  
[`AudioDecoder.decodeQueueSize`](audiodecoder/decodequeuesize) Read only   Experimental 
  An integer representing the number of decode queue requests.

  
[`AudioDecoder.state`](audiodecoder/state) Read only   Experimental 
  Represents the state of the underlying codec and whether it is configured for decoding.

  

### Events


 
[`dequeue`](audiodecoder/dequeue_event)  Experimental 
  Fires to signal a decrease in [`AudioDecoder.decodeQueueSize`](audiodecoder/decodequeuesize).

  
Static methods
--------------


 
[`AudioDecoder.isConfigSupported()`](audiodecoder/isconfigsupported)  Experimental 
  Returns a promise indicating whether the provided `AudioDecoderConfig` is supported.

  
Instance methods
----------------



*Inherits methods from its parent, [`EventTarget`](eventtarget).*

  
[`AudioDecoder.configure()`](audiodecoder/configure)  Experimental 
  Enqueues a control message to configure the audio decoder for decoding chunks.

  
[`AudioDecoder.decode()`](audiodecoder/decode)  Experimental 
  Enqueues a control message to decode a given chunk of audio.

  
[`AudioDecoder.flush()`](audiodecoder/flush)  Experimental 
  Returns a promise that resolves once all pending messages in the queue have been completed.

  
[`AudioDecoder.reset()`](audiodecoder/reset)  Experimental 
  Resets all states including configuration, control messages in the control message queue, and all pending callbacks.

  
[`AudioDecoder.close()`](audiodecoder/close)  Experimental 
  Ends all pending work and releases system resources.

  

Specifications
--------------




| Specification |
| --- |
| [WebCodecs # audiodecoder-interface](https://w3c.github.io/webcodecs/#audiodecoder-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AudioDecoder` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `AudioDecoder` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `close` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `configure` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `decode` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `decodeQueueSize` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `dequeue_event` | 106 | 106 | No | No | 92 | No | 106 | 106 | No | 72 | No | 20.0 |
| `flush` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `isConfigSupported` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `reset` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `state` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AudioDecoder>

AudioDestinationNode
====================



The `AudioDestinationNode` interface represents the end destination of an audio graph in a given context — usually the speakers of your device. It can also be the node that will "record" the audio data when used with an `OfflineAudioContext`.

 `AudioDestinationNode` has no output (as it *is* the output, no more `AudioNode` can be linked after it in the audio graph) and one input. The number of channels in the input must be between `0` and the `maxChannelCount` value or an exception is raised.

 The `AudioDestinationNode` of a given `AudioContext` can be retrieved using the [`AudioContext.destination`](baseaudiocontext/destination) property.


 EventTarget AudioNode AudioDestinationNode 

|  |  |
| --- | --- |
| Number of inputs | `1` |
| Number of outputs | `0` |
| Channel count mode | `"explicit"` |
| Channel count | `2` |
| Channel interpretation | `"speakers"` |



Instance properties
-------------------



*Inherits properties from its parent, [`AudioNode`](audionode)*.

  [`AudioDestinationNode.maxChannelCount`](audiodestinationnode/maxchannelcount)  An `unsigned long` defining the maximum number of channels that the physical device can handle.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`AudioNode`](audionode)*.


Example
-------



There is no complex set up for using an `AudioDestinationNode` — by default, this represents the output of the user's system (e.g. their speakers), so you can get it hooked up inside an audio graph using only a few lines of code:

 
```
const audioCtx = new AudioContext();
const source = audioCtx.createMediaElementSource(myMediaElement);
source.connect(gainNode);
gainNode.connect(audioCtx.destination);

```
 To see a more complete implementation, check out one of our MDN Web Audio examples, such as [Voice-change-o-matic](https://mdn.github.io/webaudio-examples/voice-change-o-matic/) or [Violent Theremin](https://github.com/mdn/webaudio-examples/tree/master/violent-theremin).



Specifications
--------------




| Specification |
| --- |
| [Web Audio API # AudioDestinationNode](https://webaudio.github.io/web-audio-api/#AudioDestinationNode) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AudioDestinationNode` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `maxChannelCount` | 27 | 12 | 25 | No | 15 | 14.17–14.1This property always returns `0`. | ≤37 | 27 | 25 | 15 | 14.57–14.5This property always returns `0`. | 1.5 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AudioDestinationNode>

AudioTrack
==========



The `AudioTrack` interface represents a single audio track from one of the HTML media elements, [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) or [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video).

 The most common use for accessing an `AudioTrack` object is to toggle its [`enabled`](audiotrack/enabled) property in order to mute and unmute the track.



Instance properties
-------------------


 [`enabled`](audiotrack/enabled)  A Boolean value which controls whether or not the audio track's sound is enabled. Setting this value to `false` mutes the track's audio.

  
[`id`](audiotrack/id) Read only 
  A string which uniquely identifies the track within the media. This ID can be used to locate a specific track within an audio track list by calling [`AudioTrackList.getTrackById()`](audiotracklist/gettrackbyid). The ID can also be used as the fragment part of the URL if the media supports seeking by media fragment per the [Media Fragments URI specification](https://www.w3.org/TR/media-frags/).

  
[`kind`](audiotrack/kind) Read only 
  A string specifying the category into which the track falls. For example, the main audio track would have a `kind` of `"main"`.

  
[`label`](audiotrack/label) Read only 
  A string providing a human-readable label for the track. For example, an audio commentary track for a movie might have a `label` of `"Commentary with director John Q. Public and actors John Doe and Jane Eod."` This string is empty if no label is provided.

  
[`language`](audiotrack/language) Read only 
  A string specifying the audio track's primary language, or an empty string if unknown. The language is specified as a BCP 47 ([RFC 5646](https://datatracker.ietf.org/doc/html/rfc5646)) language code, such as `"en-US"` or `"pt-BR"`.

  
[`sourceBuffer`](audiotrack/sourcebuffer) Read only 
  The [`SourceBuffer`](sourcebuffer) that created the track. Returns null if the track was not created by a [`SourceBuffer`](sourcebuffer) or the [`SourceBuffer`](sourcebuffer) has been removed from the [`MediaSource.sourceBuffers`](mediasource/sourcebuffers) attribute of its parent media source.

  
Usage notes
-----------



To get an `AudioTrack` for a given media element, use the element's [`audioTracks`](htmlmediaelement/audiotracks) property, which returns an [`AudioTrackList`](audiotracklist) object from which you can get the individual tracks contained in the media:

 
```
const el = document.querySelector("video");
const tracks = el.audioTracks;

```
 You can then access the media's individual tracks using either array syntax or functions such as [`forEach()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach).

 This first example gets the first audio track on the media:

 
```
const firstTrack = tracks[0];

```
 The next example scans through all of the media's audio tracks, enabling any that are in the user's preferred language (taken from a variable `userLanguage`) and disabling any others.

 
```
tracks.forEach((track) => {
  track.enabled = track.language === userLanguage;
});

```
 The [`language`](audiotrack/language) is in standard ([RFC 5646](https://datatracker.ietf.org/doc/html/rfc5646)) format. For US English, this would be `"en-US"`, for example.



Example
-------


See [`AudioTrack.label`](audiotrack/label#examples) for a simple example that shows how to get an array of track kinds and labels for a specified media element, filtered by kind.


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # audiotrack](https://html.spec.whatwg.org/multipage/media.html#audiotrack) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AudioTrack` | 37 | 7912–79 | 33 | 10 | 24 | 8 | No | 37 | No | No | 8 | No |
| `enabled` | 37 | 7912–79 | 33 | 10 | 24 | 8 | No | 37 | No | No | 8 | No |
| `id` | 37 | 7912–79 | 33 | 10 | 24 | 8 | No | 37 | No | No | 8 | No |
| `kind` | 37 | 7912–79 | 33 | 10 | 24 | 8 | No | 37 | No | No | 8 | No |
| `label` | 37 | 7912–79 | 33 | 10 | 24 | 8 | No | 37 | No | No | 8 | No |
| `language` | 37 | 7912–79 | 33 | 10 | 24 | 8 | No | 37 | No | No | 8 | No |
| `sourceBuffer` | 51 | 7912–79 | No | 11 | 38 | 8 | No | 51 | No | No | 13Exposed in Mobile Safari on iPad but not on iPhone. | No |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AudioTrack>

AudioTrackList
==============



The `AudioTrackList` interface is used to represent a list of the audio tracks contained within a given HTML media element, with each track represented by a separate [`AudioTrack`](audiotrack) object in the list.

 Retrieve an instance of this object with [`HTMLMediaElement.audioTracks`](htmlmediaelement/audiotracks). The individual tracks can be accessed using array syntax.


 EventTarget AudioTrackList

Instance properties
-------------------



*This interface also inherits properties from its parent interface, [`EventTarget`](eventtarget).*

  
[`length`](audiotracklist/length) Read only 
  The number of tracks in the list.

  

Instance methods
----------------



*This interface also inherits methods from its parent interface, [`EventTarget`](eventtarget).*

  [`getTrackById()`](audiotracklist/gettrackbyid)  Returns the [`AudioTrack`](audiotrack) found within the `AudioTrackList` whose [`id`](audiotrack/id) matches the specified string. If no match is found, `null` is returned.

  

Events
------


 [`addtrack`](audiotracklist/addtrack_event)  Fired when a new audio track has been added to the media element.

  [`change`](audiotracklist/change_event)  Fired when a track has been enabled or disabled.

  [`removetrack`](audiotracklist/removetrack_event)  Fired when a new audio track has been removed from the media element.

  
Usage notes
-----------


In addition to being able to obtain direct access to the audio tracks present on a media element, `AudioTrackList` lets you set event handlers on the [`addtrack`](audiotracklist/addtrack_event) and [`removetrack`](audiotracklist/removetrack_event) events, so that you can detect when tracks are added to or removed from the media element's stream. See the [`addtrack`](audiotracklist/addtrack_event) and [`removetrack`](audiotracklist/removetrack_event) events for details and examples.


Examples
--------


### Getting a media element's audio track list



To get a media element's [`AudioTrackList`](audiotracklist), use its [`audioTracks`](htmlmediaelement/audiotracks) property.

 
```
const audioTracks = document.querySelector("video").audioTracks;

```


### Monitoring track count changes



In this example, we have an app that displays information about the number of channels available. To keep it up to date, handlers for the [`addtrack`](audiotracklist/addtrack_event) and [`removetrack`](audiotracklist/removetrack_event) events are set up.

 
```
audioTracks.onaddtrack = updateTrackCount;
audioTracks.onremovetrack = updateTrackCount;

function updateTrackCount(event) {
  trackCount = audioTracks.length;
  drawTrackCountIndicator(trackCount);
}

```


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # audiotracklist-and-videotracklist-objects](https://html.spec.whatwg.org/multipage/media.html#audiotracklist-and-videotracklist-objects) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AudioTrackList` | 37 | 7912–79 | 33 | 10 | 24 | 7 | No | 37 | No | No | 7 | No |
| `addtrack_event` | 37 | 7912–79 | 33 | 10 | 24 | 7 | No | 37 | No | No | 7 | No |
| `change_event` | 37 | 7912–79 | 33 | 10 | 24 | 7 | No | 37 | No | No | 7 | No |
| `getTrackById` | 37 | 7912–79 | 33 | 10 | 24 | 7 | No | 37 | No | No | 7 | No |
| `length` | 37 | 7912–79 | 33 | 10 | 24 | 7 | No | 37 | No | No | 7 | No |
| `removetrack_event` | 37 | 7912–79 | 33 | 10 | 24 | 7 | No | 37 | No | No | 7 | No |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AudioTrackList>

AudioWorklet
============



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `AudioWorklet` interface of the [Web Audio API](web_audio_api) is used to supply custom audio processing scripts that execute in a separate thread to provide very low latency audio processing.

 The worklet's code is run in the [`AudioWorkletGlobalScope`](audioworkletglobalscope) global execution context, using a separate Web Audio thread which is shared by the worklet and other audio nodes.

 Access the audio context's instance of `AudioWorklet` through the [`BaseAudioContext.audioWorklet`](baseaudiocontext/audioworklet) property.


 Worklet AudioWorklet

Instance properties
-------------------


*The `AudioWorklet` interface does not define any properties of its own, but does inherit properties of [`Worklet`](worklet).*


Instance methods
----------------


*This interface inherits methods from [`Worklet`](worklet). The `AudioWorklet` interface does not define any methods of its own.*


Events
------


*`AudioWorklet` has no events to which it responds.*


Examples
--------


See [`AudioWorkletNode`](audioworkletnode) for complete examples of custom audio node creation.


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # AudioWorklet](https://webaudio.github.io/web-audio-api/#AudioWorklet) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AudioWorklet` | 66 | 79 | 76 | No | 53 | 14.1 | 66 | 66 | 79 | 47 | 14.5 | 9.0 |


See also
--------


* [`AudioWorkletGlobalScope`](audioworkletglobalscope) — the global execution context of an `AudioWorklet`
* [Web Audio API](web_audio_api)
* [Using the Web Audio API](web_audio_api/using_web_audio_api)
* [Using AudioWorklet](web_audio_api/using_audioworklet)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AudioWorklet>

AudioNode
=========



The `AudioNode` interface is a generic interface for representing an audio processing module.

 Examples include:

 * an audio source (e.g. an HTML [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) or [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) element, an [`OscillatorNode`](oscillatornode), etc.),
* the audio destination,
* intermediate processing module (e.g. a filter like [`BiquadFilterNode`](biquadfilternode) or [`ConvolverNode`](convolvernode)), or
* volume control (like [`GainNode`](gainnode))


 EventTarget AudioNode  **Note:** An `AudioNode` can be target of events, therefore it implements the [`EventTarget`](eventtarget) interface.

 

Instance properties
-------------------


 
[`AudioNode.context`](audionode/context) Read only 
  Returns the associated [`BaseAudioContext`](baseaudiocontext), that is the object representing the processing graph the node is participating in.

  
[`AudioNode.numberOfInputs`](audionode/numberofinputs) Read only 
  Returns the number of inputs feeding the node. Source nodes are defined as nodes having a `numberOfInputs` property with a value of `0`.

  
[`AudioNode.numberOfOutputs`](audionode/numberofoutputs) Read only 
  Returns the number of outputs coming out of the node. Destination nodes — like [`AudioDestinationNode`](audiodestinationnode) — have a value of `0` for this attribute.

  [`AudioNode.channelCount`](audionode/channelcount)  Represents an integer used to determine how many channels are used when [up-mixing and down-mixing](web_audio_api/basic_concepts_behind_web_audio_api#up-mixing_and_down-mixing) connections to any inputs to the node. Its usage and precise definition depend on the value of [`AudioNode.channelCountMode`](audionode/channelcountmode).

  [`AudioNode.channelCountMode`](audionode/channelcountmode)  Represents an enumerated value describing the way channels must be matched between the node's inputs and outputs.

  [`AudioNode.channelInterpretation`](audionode/channelinterpretation)   Represents an enumerated value describing the meaning of the channels. This interpretation will define how audio [up-mixing and down-mixing](web_audio_api/basic_concepts_behind_web_audio_api#up-mixing_and_down-mixing) will happen. The possible values are `"speakers"` or `"discrete"`. 

  
Instance methods
----------------



*Also implements methods from the interface* [`EventTarget`](eventtarget).

  [`AudioNode.connect()`](audionode/connect)  Allows us to connect the output of this node to be input into another node, either as audio data or as the value of an [`AudioParam`](audioparam).

  [`AudioNode.disconnect()`](audionode/disconnect)  Allows us to disconnect the current node from another one it is already connected to.

  

Description
-----------


### The audio routing graph



 ![AudioNodes participating in an AudioContext create an audio routing graph.] 

 Each `AudioNode` has inputs and outputs, and multiple audio nodes are connected to build a *processing graph*. This graph is contained in an [`AudioContext`](audiocontext), and each audio node can only belong to one audio context.

 A *source node* has zero inputs but one or multiple outputs, and can be used to generate sound. On the other hand, a *destination node* has no outputs; instead, all its inputs are directly played back on the speakers (or whatever audio output device the audio context uses). In addition, there are *processing nodes* which have inputs and outputs. The exact processing done varies from one `AudioNode` to another but, in general, a node reads its inputs, does some audio-related processing, and generates new values for its outputs, or lets the audio pass through (for example in the [`AnalyserNode`](analysernode), where the result of the processing is accessed separately).

 The more nodes in a graph, the higher the latency will be. For example, if your graph has a latency of 500ms, when the source node plays a sound, it will take half a second until that sound can be heard on your speakers (or even longer because of latency in the underlying audio device). Therefore, if you need to have interactive audio, keep the graph as small as possible, and put user-controlled audio nodes at the end of a graph. For example, a volume control (`GainNode`) should be the last node so that volume changes take immediate effect.

 Each input and output has a given amount of *channels*. For example, mono audio has one channel, while stereo audio has two channels. The Web Audio API will up-mix or down-mix the number of channels as required; check the Web Audio spec for details.

 For a list of all audio nodes, see the [Web Audio API](web_audio_api) homepage.



### Creating an `AudioNode`



There are two ways to create an `AudioNode`: via the *constructor* and via the *factory method*.

 
```
// constructor
const analyserNode = new AnalyserNode(audioCtx, {
  fftSize: 2048,
  maxDecibels: -25,
  minDecibels: -60,
  smoothingTimeConstant: 0.5,
});

```
 
```
// factory method
const analyserNode = audioCtx.createAnalyser();
analyserNode.fftSize = 2048;
analyserNode.maxDecibels = -25;
analyserNode.minDecibels = -60;
analyserNode.smoothingTimeConstant = 0.5;

```
 You are free to use either constructors or factory methods, or mix both, however there are advantages to using the constructors:

 * All parameters can be set during construction time and don't need to be set individually.
* You can [sub-class an audio node](https://github.com/WebAudio/web-audio-api/issues/251). While the actual processing is done internally by the browser and cannot be altered, you could write a wrapper around an audio node to provide custom properties and methods.
* Slightly better performance: In both Chrome and Firefox, the factory methods call the constructors internally.

 *Brief history:* The first version of the Web Audio spec only defined the factory methods. After a [design review in October 2013](https://github.com/WebAudio/web-audio-api/issues/250), it was decided to add constructors because they have numerous benefits over factory methods. The constructors were added to the spec from August to October 2016. Factory methods continue to be included in the spec and are not deprecated.



Example
-------



This simple snippet of code shows the creation of some audio nodes, and how the `AudioNode` properties and methods can be used. You can find examples of such usage on any of the examples linked to on the [Web Audio API](web_audio_api) landing page (for example [Violent Theremin](https://github.com/mdn/webaudio-examples/tree/master/violent-theremin)).

 
```
const audioCtx = new AudioContext();

const oscillator = new OscillatorNode(audioCtx);
const gainNode = new GainNode(audioCtx);

oscillator.connect(gainNode).connect(audioCtx.destination);

oscillator.context;
oscillator.numberOfInputs;
oscillator.numberOfOutputs;
oscillator.channelCount;

```


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # AudioNode](https://webaudio.github.io/web-audio-api/#AudioNode) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AudioNode` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `channelCount` | 27 | 12 | 25 | No | 15 | 7 | ≤37 | 27 | 25 | 15 | 7 | 1.5 |
| `channelCountMode` | 27 | 12 | 25 | No | 15 | 7 | ≤37 | 27 | 25 | 15 | 7 | 1.5 |
| `channelInterpretation` | 27 | 12 | 25 | No | 15 | 7 | ≤37 | 27 | 25 | 15 | 7 | 1.5 |
| `connect` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `context` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `disconnect` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `numberOfInputs` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `numberOfOutputs` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AudioNode>

AudioParam
==========



The Web Audio API's `AudioParam` interface represents an audio-related parameter, usually a parameter of an [`AudioNode`](audionode) (such as [`GainNode.gain`](gainnode/gain)).

 An `AudioParam` can be set to a specific value or a change in value, and can be scheduled to happen at a specific time and following a specific pattern.

 Each `AudioParam` has a list of events, initially empty, that define when and how values change. When this list is not empty, changes using the `AudioParam.value` attributes are ignored. This list of events allows us to schedule changes that have to happen at very precise times, using arbitrary timeline-based automation curves. The time used is the one defined in [`AudioContext.currentTime`](baseaudiocontext/currenttime).



AudioParam types
----------------


There are two `AudioParam` kinds: *a-rate* and *k-rate* parameters. Each [`AudioNode`](audionode) defines which of its parameters are *a-rate* or *k-rate* in the spec.


### a-rate


An *a-rate* `AudioParam` takes the current audio parameter value for each [sample frame](web_audio_api/basic_concepts_behind_web_audio_api#audio_buffers.3a_frames.2c_samples_and_channels) of the audio signal.


### k-rate


A *k-rate* `AudioParam` uses the same initial audio parameter value for the whole block processed; that is, 128 sample frames. In other words, the same value applies to every frame in the audio as it's processed by the node.


Instance properties
-------------------


 
[`AudioParam.defaultValue`](audioparam/defaultvalue) Read only 
  Represents the initial value of the attribute as defined by the specific [`AudioNode`](audionode) creating the `AudioParam`.

  
[`AudioParam.maxValue`](audioparam/maxvalue) Read only 
  Represents the maximum possible value for the parameter's nominal (effective) range.

  
[`AudioParam.minValue`](audioparam/minvalue) Read only 
  Represents the minimum possible value for the parameter's nominal (effective) range.

  [`AudioParam.value`](audioparam/value)  Represents the parameter's current value as of the current time; initially set to the value of [`defaultValue`](audioparam/defaultvalue).

  
Instance methods
----------------


 [`AudioParam.setValueAtTime()`](audioparam/setvalueattime)  Schedules an instant change to the value of the `AudioParam` at a precise time, as measured against [`AudioContext.currentTime`](baseaudiocontext/currenttime). The new value is given by the `value` parameter.

  [`AudioParam.linearRampToValueAtTime()`](audioparam/linearramptovalueattime)  Schedules a gradual linear change in the value of the `AudioParam`. The change starts at the time specified for the *previous* event, follows a linear ramp to the new value given in the `value` parameter, and reaches the new value at the time given in the `endTime` parameter.

  [`AudioParam.exponentialRampToValueAtTime()`](audioparam/exponentialramptovalueattime)  Schedules a gradual exponential change in the value of the `AudioParam`. The change starts at the time specified for the *previous* event, follows an exponential ramp to the new value given in the `value` parameter, and reaches the new value at the time given in the `endTime` parameter.

  [`AudioParam.setTargetAtTime()`](audioparam/settargetattime)  Schedules the start of a change to the value of the `AudioParam`. The change starts at the time specified in `startTime` and exponentially moves towards the value given by the `target` parameter. The exponential decay rate is defined by the `timeConstant` parameter, which is a time measured in seconds.

  [`AudioParam.setValueCurveAtTime()`](audioparam/setvaluecurveattime)  Schedules the values of the `AudioParam` to follow a set of values, defined by an array of floating-point numbers scaled to fit into the given interval, starting at a given start time and spanning a given duration of time.

  [`AudioParam.cancelScheduledValues()`](audioparam/cancelscheduledvalues)  Cancels all scheduled future changes to the `AudioParam`.

  [`AudioParam.cancelAndHoldAtTime()`](audioparam/cancelandholdattime)  Cancels all scheduled future changes to the `AudioParam` but holds its value at a given time until further changes are made using other methods.

  
Examples
--------



First, a basic example showing a [`GainNode`](gainnode) having its `gain` value set. `gain` is an example of an *a-rate* `AudioParam`, as the value can potentially be set differently for each sample frame of the audio.

 
```
const audioCtx = new AudioContext();

const gainNode = audioCtx.createGain();
gainNode.gain.value = 0;

```
 Next, an example showing a [`DynamicsCompressorNode`](dynamicscompressornode) having some param values manipulated. These are examples of *k-rate* `AudioParam` types, as the values are set for the entire audio block at once.

 
```
const compressor = audioCtx.createDynamicsCompressor();
compressor.threshold.setValueAtTime(-50, audioCtx.currentTime);
compressor.knee.setValueAtTime(40, audioCtx.currentTime);
compressor.ratio.setValueAtTime(12, audioCtx.currentTime);
compressor.attack.setValueAtTime(0, audioCtx.currentTime);
compressor.release.setValueAtTime(0.25, audioCtx.currentTime);

```


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # AudioParam](https://webaudio.github.io/web-audio-api/#AudioParam) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AudioParam` | 14 | 12 | 25 | No | 15 | 6 | ≤37 | 18 | 25 | 14 | 6 | 1.0 |
| `automationRate` | 68 | 79 | No | No | 55 | 14 | 68 | 68 | No | 48 | 14 | 10.0 |
| `cancelAndHoldAtTime` | 57 | 79 | No | No | 44 | 14.1 | 57 | 57 | No | 43 | 14.5 | 7.0 |
| `cancelScheduledValues` | 14 | 12 | 25 | No | 15 | 6 | ≤37 | 18 | 25 | 14 | 6 | 1.0 |
| `defaultValue` | 14 | 12 | 25 | No | 15 | 6 | ≤37 | 18 | 25 | 14 | 6 | 1.0 |
| `exponentialRampToValueAtTime` | 14 | 12 | 25Does not work (see [bug 1171438](https://bugzil.la/1171438) and [bug 1567777](https://bugzil.la/1567777)). | No | 15 | 6 | ≤37 | 18This sets the target volume at the specified time, but it doesn’t ramp to it, causing this function to behave like `setValueAtTime()`. | 25Does not work (see [bug 1171438](https://bugzil.la/1171438) and [bug 1567777](https://bugzil.la/1567777)). | 14 | 6 | 1.0 |
| `linearRampToValueAtTime` | 14 | 12 | 25Does not work (see [bug 1171438](https://bugzil.la/1171438) and [bug 1567777](https://bugzil.la/1567777)). | No | 15 | 6 | ≤37 | 18This sets the target volume at the specified time, but it doesn’t ramp to it, causing this function to behave like `setValueAtTime()`. | 25Does not work (see [bug 1171438](https://bugzil.la/1171438) and [bug 1567777](https://bugzil.la/1567777)). | 14 | 6 | 1.0 |
| `maxValue` | 52 | 79 | 53 | No | 39 | 6 | 52 | 52 | 53 | 41 | 6 | 6.0 |
| `minValue` | 52 | 79 | 53 | No | 39 | 6 | 52 | 52 | 53 | 41 | 6 | 6.0 |
| `setTargetAtTime` | 14 | 12 | 25 | No | 15 | 6 | ≤37 | 18 | 25 | 14 | 6 | 1.0 |
| `setValueAtTime` | 14 | 12 | 25 | No | 15 | 6 | ≤37 | 18 | 25 | 14 | 6 | 1.0 |
| `setValueCurveAtTime` | 14 | 12 | 25 | No | 15 | 6 | ≤37 | 18 | 25 | 14 | 6 | 1.0 |
| `value` | 14 | 12 | 25Before Firefox 69, `value` did not take into account scheduled or gradiated changes to the parameter's value; instead, only explicitly set values were returned. | No | 15 | 6 | ≤37 | 18 | 25Firefox for Android does not currently take into account scheduled or gradiated changes to the parameter's value; only the initial value or the most recent explicitly set value is returned. | 14 | 6 | 1.0 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AudioParam>

AudioParamDescriptor
====================



The `AudioParamDescriptor` dictionary of the [Web Audio API](web_audio_api) specifies properties for [`AudioParam`](audioparam) objects.

 It is used to create custom `AudioParam`s on an [`AudioWorkletNode`](audioworkletnode). If the underlying [`AudioWorkletProcessor`](audioworkletprocessor) has a [`parameterDescriptors`](audioworkletprocessor/parameterdescriptors) static getter, then the returned array of objects based on this dictionary is used internally by `AudioWorkletNode` constructor to populate its [`parameters`](audioworkletnode/parameters) property accordingly.



Instance properties
-------------------


 `name`  The string which represents the name of the `AudioParam`. Under this name the `AudioParam` will be available in the [`parameters`](audioworkletnode/parameters) property of the node, and under this name the [`AudioWorkletProcessor.process`](audioworkletprocessor/process) method will acquire the calculated values of this `AudioParam`.

  
`automationRate` Optional
  Either [`"a-rate"`](audioparam#a-rate), or [`"k-rate"`](audioparam#k-rate) string which represents an automation rate of this `AudioParam`. Defaults to `"a-rate"`.

  
`minValue` Optional
  A `float` which represents minimum value of the `AudioParam`. Defaults to `-3.4028235e38`.

  
`maxValue` Optional
  A `float` which represents maximum value of the `AudioParam`. Defaults to `3.4028235e38`.

  
`defaultValue` Optional
  A `float` which represents initial value of the `AudioParam`. Defaults to `0`.

  
Examples
--------



The code fragment below shows a descriptor of this type being returned by a static [`parameterDescriptors`](audioworkletprocessor/parameterdescriptors) method defined in a custom `AudioWorkletProcessor` (this is part of the more complete example in [AudioWorkletNode.parameters](audioworkletnode/parameters#examples)).

 
```
// white-noise-processor.js
class WhiteNoiseProcessor extends AudioWorkletProcessor {
  static get parameterDescriptors() {
    return [
      {
        name: "customGain",
        defaultValue: 1,
        minValue: 0,
        maxValue: 1,
        automationRate: "a-rate",
      },
    ];
  }

  // …
}

```


Specifications
--------------



**No specification found**No specification data found for `api.AudioParamDescriptor`.  
[Check for problems with this page](#on-github) or contribute a missing `spec_url` to [mdn/browser-compat-data](https://github.com/mdn/browser-compat-data). Also make sure the specification is included in [w3c/browser-specs](https://github.com/w3c/browser-specs).



Browser compatibility
---------------------


See also
--------


* [Web Audio API](web_audio_api)
* [Using the Web Audio API](web_audio_api/using_web_audio_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AudioParamDescriptor>

AudioParamMap
=============


The Web Audio API interface `AudioParamMap` represents a set of multiple audio parameters, each described as a mapping of a string identifying the parameter to the [`AudioParam`](audioparam) object representing its value.


Instance properties
-------------------



The `AudioParamMap` object is accessed as a [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) in which each parameter is identified by a name string which is mapped to an `AudioParam` containing the value of that parameter. In addition, there are the following properties available:

  `size`  ?

  

Instance methods
----------------


 `entries()`  ?

  `forEach()`  ?

  `has()`  ?

  `keys()`  ?

  `values()`  ?

  
Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@iterator` | 66 | 79 | 76 | No | 53 | 14.1 | 66 | 66 | 79 | 47 | 14.5 | 9.0 |
| `AudioParamMap` | 66 | 79 | 76 | No | 53 | 14.1 | 66 | 66 | 79 | 47 | 14.5 | 9.0 |
| `entries` | 66 | 79 | 76 | No | 53 | 14.1 | 66 | 66 | 79 | 47 | 14.5 | 9.0 |
| `forEach` | 66 | 79 | 76 | No | 53 | 14.1 | 66 | 66 | 79 | 47 | 14.5 | 9.0 |
| `get` | 66 | 79 | 76 | No | 53 | 14.1 | 66 | 66 | 79 | 47 | 14.5 | 9.0 |
| `has` | 66 | 79 | 76 | No | 53 | 14.1 | 66 | 66 | 79 | 47 | 14.5 | 9.0 |
| `keys` | 66 | 79 | 76 | No | 53 | 14.1 | 66 | 66 | 79 | 47 | 14.5 | 9.0 |
| `size` | 66 | 79 | 76 | No | 53 | 14.1 | 66 | 66 | 79 | 47 | 14.5 | 9.0 |
| `values` | 66 | 79 | 76 | No | 53 | 14.1 | 66 | 66 | 79 | 47 | 14.5 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AudioParamMap>

AudioProcessingEvent
====================



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The `AudioProcessingEvent` interface of the [Web Audio API](web_audio_api) represents events that occur when a [`ScriptProcessorNode`](scriptprocessornode) input buffer is ready to be processed.

 An `audioprocess` event with this interface is fired on a [`ScriptProcessorNode`](scriptprocessornode) when audio processing is required. During audio processing, the input buffer is read and processed to produce output audio data, which is then written to the output buffer.

  **Warning:** This feature has been deprecated and should be replaced by an [`AudioWorklet`](audioworklet).

 
 Event AudioProcessingEvent

Constructor
-----------


 
[`AudioProcessingEvent()`](audioprocessingevent/audioprocessingevent)  Deprecated 
  Creates a new `AudioProcessingEvent` object.

  
Instance properties
-------------------



*Also implements the properties inherited from its parent, [`Event`](event)*.

  
[`playbackTime`](audioprocessingevent/playbacktime) Read only   Deprecated 
   A double representing the time when the audio will be played, as defined by the time of [`AudioContext.currentTime`](baseaudiocontext/currenttime). 

  
[`inputBuffer`](audioprocessingevent/inputbuffer) Read only   Deprecated 
   An [`AudioBuffer`](audiobuffer) that is the buffer containing the input audio data to be processed. The number of channels is defined as a parameter `numberOfInputChannels`, of the factory method [`AudioContext.createScriptProcessor()`](baseaudiocontext/createscriptprocessor). Note that the returned `AudioBuffer` is only valid in the scope of the event handler. 

  
[`outputBuffer`](audioprocessingevent/outputbuffer) Read only   Deprecated 
   An [`AudioBuffer`](audiobuffer) that is the buffer where the output audio data should be written. The number of channels is defined as a parameter, `numberOfOutputChannels`, of the factory method [`AudioContext.createScriptProcessor()`](baseaudiocontext/createscriptprocessor). Note that the returned `AudioBuffer` is only valid in the scope of the event handler. 

  

Examples
--------



 The following example shows how to use of a `ScriptProcessorNode` to take a track loaded via [`AudioContext.decodeAudioData()`](baseaudiocontext/decodeaudiodata), process it, adding a bit of white noise to each audio sample of the input track (buffer) and play it through the [`AudioDestinationNode`](audiodestinationnode). For each channel and each sample frame, the `scriptNode.onaudioprocess` function takes the associated `audioProcessingEvent` and uses it to loop through each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. 

   **Note:** For a full working example, see our [script-processor-node](https://mdn.github.io/webaudio-examples/script-processor-node/) GitHub repo. (You can also access the [source code](https://github.com/mdn/webaudio-examples/blob/master/script-processor-node/index.html).) 

  
```
const myScript = document.querySelector("script");
const myPre = document.querySelector("pre");
const playButton = document.querySelector("button");

// Create AudioContext and buffer source
const audioCtx = new AudioContext();
const source = audioCtx.createBufferSource();

// Create a ScriptProcessorNode with a bufferSize of 4096 and a single input and output channel
const scriptNode = audioCtx.createScriptProcessor(4096, 1, 1);
console.log(scriptNode.bufferSize);

// load in an audio track via XHR and decodeAudioData

function getData() {
  request = new XMLHttpRequest();
  request.open("GET", "viper.ogg", true);
  request.responseType = "arraybuffer";
  request.onload = () => {
    const audioData = request.response;

    audioCtx.decodeAudioData(
      audioData,
      (buffer) => {
        myBuffer = buffer;
        source.buffer = myBuffer;
      },
      (e) => console.error(`Error with decoding audio data: ${e.err}`)
    );
  };
  request.send();
}

// Give the node a function to process audio events
scriptNode.onaudioprocess = (audioProcessingEvent) => {
  // The input buffer is the song we loaded earlier
  const inputBuffer = audioProcessingEvent.inputBuffer;

  // The output buffer contains the samples that will be modified and played
  const outputBuffer = audioProcessingEvent.outputBuffer;

  // Loop through the output channels (in this case there is only one)
  for (let channel = 0; channel < outputBuffer.numberOfChannels; channel++) {
    const inputData = inputBuffer.getChannelData(channel);
    const outputData = outputBuffer.getChannelData(channel);

    // Loop through the 4096 samples
    for (let sample = 0; sample < inputBuffer.length; sample++) {
      // make output equal to the same as the input
      outputData[sample] = inputData[sample];

      // add noise to each output sample
      outputData[sample] += (Math.random() \* 2 - 1) \* 0.2;
    }
  }
};

getData();

// Wire up the play button
playButton.onclick = () => {
  source.connect(scriptNode);
  scriptNode.connect(audioCtx.destination);
  source.start();
};

// When the buffer source stops playing, disconnect everything
source.onended = () => {
  source.disconnect(scriptNode);
  scriptNode.disconnect(audioCtx.destination);
};

```


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AudioProcessingEvent` | 57 | 79 | No | No | 44 | 14.1 | 57 | 57 | No | 43 | 14.5 | 7.0 |
| `AudioProcessingEvent` | 14 | 12 | 25 | No | 15 | 6 | 4.4 | 18 | 25 | 14 | 6 | 1.0 |
| `inputBuffer` | 14 | 12 | 25 | No | 15 | 6 | 4.4 | 18 | 25 | 14 | 6 | 1.0 |
| `outputBuffer` | 14 | 12 | 25 | No | 15 | 6 | 4.4 | 18 | 25 | 14 | 6 | 1.0 |
| `playbackTime` | 14 | 12 | 25 | No | 15 | 6 | ≤37 | 18 | 25 | 14 | 6 | 1.0 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AudioProcessingEvent>

AudioScheduledSourceNode
========================



The `AudioScheduledSourceNode` interface—part of the Web Audio API—is a parent interface for several types of audio source node interfaces which share the ability to be started and stopped, optionally at specified times. Specifically, this interface defines the [`start()`](audioscheduledsourcenode/start) and [`stop()`](audioscheduledsourcenode/stop) methods, as well as the [`ended`](audioscheduledsourcenode/ended_event) event.

  **Note:** You can't create an `AudioScheduledSourceNode` object directly. Instead, use an interface which extends it, such as [`AudioBufferSourceNode`](audiobuffersourcenode), [`OscillatorNode`](oscillatornode) or [`ConstantSourceNode`](constantsourcenode).

  Unless stated otherwise, nodes based upon `AudioScheduledSourceNode` output silence when not playing (that is, before `start()` is called and after `stop()` is called). Silence is represented, as always, by a stream of samples with the value zero (0).


 EventTarget AudioNode AudioScheduledSourceNode

Instance properties
-------------------


*Inherits properties from its parent interface, [`AudioNode`](audionode).*


Instance methods
----------------



*Inherits methods from its parent interface, [`AudioNode`](audionode), and adds the following methods:*

  [`start()`](audioscheduledsourcenode/start)  Schedules the node to begin playing the constant sound at the specified time. If no time is specified, the node begins playing immediately.

  [`stop()`](audioscheduledsourcenode/stop)  Schedules the node to stop playing at the specified time. If no time is specified, the node stops playing at once.

  

Events
------



Listen to these events using [`addEventListener()`](eventtarget/addeventlistener) or by assigning an event listener to the `oneventname` property of this interface:

  [`ended`](audioscheduledsourcenode/ended_event)  Fired when the source node has stopped playing, either because it's reached a predetermined stop time, the full duration of the audio has been performed, or because the entire buffer has been played.

  

Specifications
--------------




| Specification |
| --- |
| [Web Audio API # AudioScheduledSourceNode](https://webaudio.github.io/web-audio-api/#AudioScheduledSourceNode) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AudioScheduledSourceNode` | 5714–57The `AudioScheduledSourceNode` interface itself is not present, but some of its members are available on the [`AudioBufferSourceNode`](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode), [`ConstantSourceNode`](https://developer.mozilla.org/docs/Web/API/ConstantSourceNode) and [`OscillatorNode`](https://developer.mozilla.org/docs/Web/API/OscillatorNode) interfaces. | 7912–79The `AudioScheduledSourceNode` interface itself is not present, but some of its members are available on the [`AudioBufferSourceNode`](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode), [`ConstantSourceNode`](https://developer.mozilla.org/docs/Web/API/ConstantSourceNode) and [`OscillatorNode`](https://developer.mozilla.org/docs/Web/API/OscillatorNode) interfaces. | 5325–53The `AudioScheduledSourceNode` interface itself is not present, but some of its members are available on the [`AudioBufferSourceNode`](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode), [`ConstantSourceNode`](https://developer.mozilla.org/docs/Web/API/ConstantSourceNode) and [`OscillatorNode`](https://developer.mozilla.org/docs/Web/API/OscillatorNode) interfaces. | No | 4415–44The `AudioScheduledSourceNode` interface itself is not present, but some of its members are available on the [`AudioBufferSourceNode`](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode), [`ConstantSourceNode`](https://developer.mozilla.org/docs/Web/API/ConstantSourceNode) and [`OscillatorNode`](https://developer.mozilla.org/docs/Web/API/OscillatorNode) interfaces. | 146–14The `AudioScheduledSourceNode` interface itself is not present, but some of its members are available on the [`AudioBufferSourceNode`](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode), [`ConstantSourceNode`](https://developer.mozilla.org/docs/Web/API/ConstantSourceNode) and [`OscillatorNode`](https://developer.mozilla.org/docs/Web/API/OscillatorNode) interfaces. | 57≤37–57The `AudioScheduledSourceNode` interface itself is not present, but some of its members are available on the [`AudioBufferSourceNode`](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode), [`ConstantSourceNode`](https://developer.mozilla.org/docs/Web/API/ConstantSourceNode) and [`OscillatorNode`](https://developer.mozilla.org/docs/Web/API/OscillatorNode) interfaces. | 5718–57The `AudioScheduledSourceNode` interface itself is not present, but some of its members are available on the [`AudioBufferSourceNode`](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode), [`ConstantSourceNode`](https://developer.mozilla.org/docs/Web/API/ConstantSourceNode) and [`OscillatorNode`](https://developer.mozilla.org/docs/Web/API/OscillatorNode) interfaces. | 5325–53The `AudioScheduledSourceNode` interface itself is not present, but some of its members are available on the [`AudioBufferSourceNode`](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode), [`ConstantSourceNode`](https://developer.mozilla.org/docs/Web/API/ConstantSourceNode) and [`OscillatorNode`](https://developer.mozilla.org/docs/Web/API/OscillatorNode) interfaces. | 4314–43The `AudioScheduledSourceNode` interface itself is not present, but some of its members are available on the [`AudioBufferSourceNode`](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode), [`ConstantSourceNode`](https://developer.mozilla.org/docs/Web/API/ConstantSourceNode) and [`OscillatorNode`](https://developer.mozilla.org/docs/Web/API/OscillatorNode) interfaces. | 146–14The `AudioScheduledSourceNode` interface itself is not present, but some of its members are available on the [`AudioBufferSourceNode`](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode), [`ConstantSourceNode`](https://developer.mozilla.org/docs/Web/API/ConstantSourceNode) and [`OscillatorNode`](https://developer.mozilla.org/docs/Web/API/OscillatorNode) interfaces. | 7.01.0–7.0The `AudioScheduledSourceNode` interface itself is not present, but some of its members are available on the [`AudioBufferSourceNode`](https://developer.mozilla.org/docs/Web/API/AudioBufferSourceNode), [`ConstantSourceNode`](https://developer.mozilla.org/docs/Web/API/ConstantSourceNode) and [`OscillatorNode`](https://developer.mozilla.org/docs/Web/API/OscillatorNode) interfaces. |
| `ended_event` | 30 | 12 | 25 | No | 17 | 7 | ≤37 | 30 | 25 | 18 | 7 | 2.0 |
| `start` | 24 | 12 | 25 | No | 15 | 7 | 4.4 | 25 | 25 | 14 | 7 | 1.5 |
| `stop` | 24 | 12 | 25 | No | 15 | 7 | 4.4 | 25 | 25 | 14 | 7 | 1.5 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)
* [`AudioNode`](audionode)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AudioScheduledSourceNode>

AudioSinkInfo
=============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `AudioSinkInfo` interface of the [Web Audio API](web_audio_api) represents information describing an [`AudioContext`](audiocontext)'s sink ID, retrieved via [`AudioContext.sinkId`](audiocontext/sinkid).



Instance properties
-------------------


 
[`type`](audiosinkinfo/type) Read only   Experimental 
  Returns the type of the audio output device.

  
Examples
--------



If a new [`AudioContext`](audiocontext) is created with a `sinkId` value of `{ type: 'none' }`, calling [`AudioContext.sinkId`](audiocontext/sinkid) later in the code will return a `AudioSinkInfo` object containing `type: 'none'`. This is currently the only value available.

 
```
audioCtx = new window.AudioContext({
  sinkId: { type: "none" },
});

// ...

audioCtx.sinkId;

```


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # AudioSinkInfo](https://webaudio.github.io/web-audio-api/#AudioSinkInfo) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AudioSinkInfo` | 110 | 110 | No | No | 96 | No | 110 | 110 | No | 74 | No | No |
| `type` | 110 | 110 | No | No | 96 | No | 110 | 110 | No | 74 | No | No |


See also
--------


* [SetSinkId test example](https://set-sink-id.glitch.me/)
* [`AudioContext.setSinkId()`](audiocontext/setsinkid)
* [`AudioContext.sinkId`](audiocontext/sinkid)
* [`sinkchange`](audiocontext/sinkchange_event)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AudioSinkInfo>

AudioWorkletGlobalScope
=======================



The `AudioWorkletGlobalScope` interface of the [Web Audio API](web_audio_api) represents a global execution context for user-supplied code, which defines custom [`AudioWorkletProcessor`](audioworkletprocessor)-derived classes.

 Each [`BaseAudioContext`](baseaudiocontext) has a single [`AudioWorklet`](audioworklet) available under the [`audioWorklet`](baseaudiocontext/audioworklet) property, which runs its code in a single `AudioWorkletGlobalScope`.

 As the global execution context is shared across the current `BaseAudioContext`, it's possible to define any other variables and perform any actions allowed in worklets — apart from defining `AudioWorkletProcessor` derived classes.


 WorkletGlobalScope AudioWorkletGlobalScope

Instance properties
-------------------



*This interface also inherits properties defined on its parent interface, [`WorkletGlobalScope`](workletglobalscope).*

  
[`currentFrame`](audioworkletglobalscope/currentframe) Read only 
  Returns an integer that represents the ever-increasing current sample-frame of the audio block being processed. It is incremented by 128 (the size of a render quantum) after the processing of each audio block.

  
[`currentTime`](audioworkletglobalscope/currenttime) Read only 
  Returns a double that represents the ever-increasing context time of the audio block being processed. It is equal to the [`currentTime`](baseaudiocontext/currenttime) property of the [`BaseAudioContext`](baseaudiocontext) the worklet belongs to.

  
[`sampleRate`](audioworkletglobalscope/samplerate) Read only 
  Returns a float that represents the sample rate of the associated [`BaseAudioContext`](baseaudiocontext).

  

Instance methods
----------------



*This interface also inherits methods defined on its parent interface, [`WorkletGlobalScope`](workletglobalscope).*

  [`registerProcessor()`](audioworkletglobalscope/registerprocessor)  Registers a class derived from the [`AudioWorkletProcessor`](audioworkletprocessor) interface. The class can then be used by creating an [`AudioWorkletNode`](audioworkletnode), providing its registered name.

  

Examples
--------



In this example we output all global properties into the console in the constructor of a custom [`AudioWorkletProcessor`](audioworkletprocessor).

 First we need to define the processor, and register it. Note that this should be done in a separate file.

 
```
// AudioWorkletProcessor defined in : test-processor.js
class TestProcessor extends AudioWorkletProcessor {
  constructor() {
    super();

    // Logs the current sample-frame and time at the moment of instantiation.
    // They are accessible from the AudioWorkletGlobalScope.
    console.log(currentFrame);
    console.log(currentTime);
  }

  // The process method is required - output silence,
  // which the outputs are already filled with.
  process(inputs, outputs, parameters) {
    return true;
  }
}

// Logs the sample rate, that is not going to change ever,
// because it's a read-only property of a BaseAudioContext
// and is set only during its instantiation.
console.log(sampleRate);

// You can declare any variables and use them in your processors
// for example it may be an ArrayBuffer with a wavetable
const usefulVariable = 42;
console.log(usefulVariable);

registerProcessor("test-processor", TestProcessor);

```
 Next, in our main scripts file we'll load the processor, create an instance of [`AudioWorkletNode`](audioworkletnode) — passing the name of the processor to it — and connect the node to an audio graph. We should see the output of [`console.log()`](console/log) calls in the console:

 
```
const audioContext = new AudioContext();
await audioContext.audioWorklet.addModule("test-processor.js");
const testNode = new AudioWorkletNode(audioContext, "test-processor");
testNode.connect(audioContext.destination);

```


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # AudioWorkletGlobalScope](https://webaudio.github.io/web-audio-api/#AudioWorkletGlobalScope) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AudioWorkletGlobalScope` | 66 | 79 | 76 | No | 53 | 14.1 | 66 | 66 | No | 47 | 14.5 | 9.0 |
| `currentFrame` | 66 | 79 | 76 | No | 53 | 14.1 | 66 | 66 | No | 47 | 14.5 | 9.0 |
| `currentTime` | 66 | 79 | 76 | No | 53 | 14.1 | 66 | 66 | No | 47 | 14.5 | 9.0 |
| `registerProcessor` | 66 | 79 | 76 | No | 53 | 14.1 | 66 | 66 | No | 47 | 14.5 | 9.0 |
| `sampleRate` | 66 | 79 | 76 | No | 53 | 14.1 | 66 | 66 | No | 47 | 14.5 | 9.0 |


See also
--------


* [Web Audio API](web_audio_api)
* [Using the Web Audio API](web_audio_api/using_web_audio_api)
* [Using AudioWorklet](web_audio_api/using_audioworklet)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AudioWorkletGlobalScope>

AudioWorkletNode
================



 **Note:** Although the interface is available outside [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts), the [`BaseAudioContext.audioWorklet`](baseaudiocontext/audioworklet) property is not, thus custom [`AudioWorkletProcessor`](audioworkletprocessor)s cannot be defined outside them.

  The `AudioWorkletNode` interface of the [Web Audio API](web_audio_api) represents a base class for a user-defined [`AudioNode`](audionode), which can be connected to an audio routing graph along with other nodes. It has an associated [`AudioWorkletProcessor`](audioworkletprocessor), which does the actual audio processing in a Web Audio rendering thread.


 EventTarget AudioNode AudioWorkletNode

Constructor
-----------


 [`AudioWorkletNode()`](audioworkletnode/audioworkletnode)  Creates a new instance of an `AudioWorkletNode` object.

  
Instance properties
-------------------



*Also Inherits properties from its parent, [`AudioNode`](audionode)*.

  
[`AudioWorkletNode.port`](audioworkletnode/port) Read only 
  Returns a [`MessagePort`](messageport) used for bidirectional communication between the node and its associated [`AudioWorkletProcessor`](audioworkletprocessor). The other end is available under the [`port`](audioworkletprocessor/port) property of the processor.

  
[`AudioWorkletNode.parameters`](audioworkletnode/parameters) Read only 
  Returns an [`AudioParamMap`](audioparammap) — a collection of [`AudioParam`](audioparam) objects. They are instantiated during the creation of the underlying `AudioWorkletProcessor`. If the `AudioWorkletProcessor` has a static [`parameterDescriptors`](audioworkletprocessor/parameterdescriptors) getter, the [`AudioParamDescriptor`](audioparamdescriptor) array returned from it is used to create `AudioParam` objects on the `AudioWorkletNode`. With this mechanism it is possible to make your own `AudioParam` objects accessible from your `AudioWorkletNode`. You can then use their values in the associated `AudioWorkletProcessor`.

  

### Events


 [`processorerror`](audioworkletnode/processorerror_event)  Fired when an error is thrown in associated [`AudioWorkletProcessor`](audioworkletprocessor). Once fired, the processor and consequently the node will output silence throughout its lifetime.

  
Instance methods
----------------



*Also inherits methods from its parent, [`AudioNode`](audionode)*.

 *The `AudioWorkletNode` interface does not define any methods of its own.*



Examples
--------



In this example we create a custom `AudioWorkletNode` that outputs random noise.

 First, we need to define a custom [`AudioWorkletProcessor`](audioworkletprocessor), which will output random noise, and register it. Note that this should be done in a separate file.

 
```
// random-noise-processor.js
class RandomNoiseProcessor extends AudioWorkletProcessor {
  process(inputs, outputs, parameters) {
    const output = outputs[0];
    output.forEach((channel) => {
      for (let i = 0; i < channel.length; i++) {
        channel[i] = Math.random() \* 2 - 1;
      }
    });
    return true;
  }
}

registerProcessor("random-noise-processor", RandomNoiseProcessor);

```
 Next, in our main script file we'll load the processor, create an instance of `AudioWorkletNode` passing it the name of the processor, and connect the node to an audio graph.

 
```
const audioContext = new AudioContext();
await audioContext.audioWorklet.addModule("random-noise-processor.js");
const randomNoiseNode = new AudioWorkletNode(
  audioContext,
  "random-noise-processor"
);
randomNoiseNode.connect(audioContext.destination);

```


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # AudioWorkletNode](https://webaudio.github.io/web-audio-api/#AudioWorkletNode) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AudioWorkletNode` | 66 | 79 | 76 | No | 53 | 14.1 | 66 | 66 | 79 | 47 | 14.5 | 9.0 |
| `AudioWorkletNode` | 66 | 79 | 76 | No | 53 | 14.1 | 66 | 66 | 79 | 47 | 14.5 | 9.0 |
| `parameters` | 66 | 79 | 76 | No | 53 | 14.1 | 66 | 66 | 79 | 47 | 14.5 | 9.0 |
| `port` | 66 | 79 | 76 | No | 53 | 14.1 | 66 | 66 | 79 | 47 | 14.5 | 9.0 |
| `processorerror_event` | 66 | 79 | 76 | No | 53 | 14.1 | 66 | 66 | 79 | 47 | 14.5 | 9.0 |


See also
--------


* [Web Audio API](web_audio_api)
* [Using the Web Audio API](web_audio_api/using_web_audio_api)
* [Using AudioWorklet](web_audio_api/using_audioworklet)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AudioWorkletNode>

AudioWorkletProcessor
=====================


The `AudioWorkletProcessor` interface of the [Web Audio API](web_audio_api) represents an audio processing code behind a custom [`AudioWorkletNode`](audioworkletnode). It lives in the [`AudioWorkletGlobalScope`](audioworkletglobalscope) and runs on the Web Audio rendering thread. In turn, an [`AudioWorkletNode`](audioworkletnode) based on it runs on the main thread.


Constructor
-----------



 **Note:** The `AudioWorkletProcessor` and classes that derive from it cannot be instantiated directly from a user-supplied code. Instead, they are created only internally by the creation of an associated [`AudioWorkletNode`](audioworkletnode)s. The constructor of the deriving class is getting called with an options object, so you can perform a custom initialization procedures — see constructor page for details.

   [`AudioWorkletProcessor()`](audioworkletprocessor/audioworkletprocessor)  Creates a new instance of an `AudioWorkletProcessor` object.

  

Instance properties
-------------------


 
[`port`](audioworkletprocessor/port) Read only 
  Returns a [`MessagePort`](messageport) used for bidirectional communication between the processor and the [`AudioWorkletNode`](audioworkletnode) which it belongs to. The other end is available under the [`port`](audioworkletnode/port) property of the node.

  
Instance methods
----------------


*The `AudioWorkletProcessor` interface does not define any methods of its own. However, you must provide a [`process()`](audioworkletprocessor/process) method, which is called in order to process the audio stream.*


Events
------


*The `AudioWorkletProcessor` interface doesn't respond to any events.*


Usage notes
-----------


### Deriving classes



To define custom audio processing code you have to derive a class from the `AudioWorkletProcessor` interface. Although not defined on the interface, the deriving class must have the [`process`](audioworkletprocessor/process) method. This method gets called for each block of 128 sample-frames and takes input and output arrays and calculated values of custom [`AudioParam`](audioparam)s (if they are defined) as parameters. You can use inputs and audio parameter values to fill the outputs array, which by default holds silence.

 Optionally, if you want custom [`AudioParam`](audioparam)s on your node, you can supply a [`parameterDescriptors`](audioworkletprocessor/parameterdescriptors) property as a *static getter* on the processor. The array of [`AudioParamDescriptor`](audioparamdescriptor)-based objects returned is used internally to create the [`AudioParam`](audioparam)s during the instantiation of the `AudioWorkletNode`.

 The resulting `AudioParam`s reside in the [`parameters`](audioworkletnode/parameters) property of the node and can be automated using standard methods such as [`linearRampToValueAtTime`](audioparam/linearramptovalueattime). Their calculated values will be passed into the [`process()`](audioworkletprocessor/process) method of the processor for you to shape the node output accordingly.



### Processing audio



An example algorithm of creating a custom audio processing mechanism is:

 1. Create a separate file;
2. In the file:
	1. Extend the `AudioWorkletProcessor` class (see ["Deriving classes" section](#deriving_classes)) and supply your own [`process()`](audioworkletprocessor/process) method in it;
	2. Register the processor using [`AudioWorkletGlobalScope.registerProcessor()`](audioworkletglobalscope/registerprocessor) method;
3. Load the file using [`addModule()`](worklet/addmodule) method on your audio context's [`audioWorklet`](baseaudiocontext/audioworklet) property;
4. Create an [`AudioWorkletNode`](audioworkletnode) based on the processor. The processor will be instantiated internally by the `AudioWorkletNode` constructor.
5. Connect the node to the other nodes.



Examples
--------



In the example below we create a custom [`AudioWorkletNode`](audioworkletnode) that outputs white noise.

 First, we need to define a custom `AudioWorkletProcessor`, which will output white noise, and register it. Note that this should be done in a separate file.

 
```
// white-noise-processor.js
class WhiteNoiseProcessor extends AudioWorkletProcessor {
  process(inputs, outputs, parameters) {
    const output = outputs[0];
    output.forEach((channel) => {
      for (let i = 0; i < channel.length; i++) {
        channel[i] = Math.random() \* 2 - 1;
      }
    });
    return true;
  }
}

registerProcessor("white-noise-processor", WhiteNoiseProcessor);

```
 Next, in our main script file we'll load the processor, create an instance of [`AudioWorkletNode`](audioworkletnode), passing it the name of the processor, then connect the node to an audio graph.

 
```
const audioContext = new AudioContext();
await audioContext.audioWorklet.addModule("white-noise-processor.js");
const whiteNoiseNode = new AudioWorkletNode(
  audioContext,
  "white-noise-processor"
);
whiteNoiseNode.connect(audioContext.destination);

```


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # AudioWorkletProcessor](https://webaudio.github.io/web-audio-api/#AudioWorkletProcessor) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AudioWorkletProcessor` | 64 | 79 | 76 | No | 51 | 14.1 | 64 | 64 | 79 | 47 | 14.5 | 9.0 |
| `AudioWorkletProcessor` | 64 | 79 | 76 | No | 51 | 14.1 | 64 | 64 | 79 | 47 | 14.5 | 9.0 |
| `port` | 64 | 79 | 76 | No | 51 | 14.1 | 64 | 64 | 79 | 47 | 14.5 | 9.0 |


See also
--------


* [Web Audio API](web_audio_api)
* [Using the Web Audio API](web_audio_api/using_web_audio_api)
* [Using AudioWorklet](web_audio_api/using_audioworklet)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AudioWorkletProcessor>

AuthenticatorAttestationResponse
================================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `AuthenticatorAttestationResponse` interface of the [Web Authentication API](web_authentication_api) is returned by [`CredentialsContainer.create()`](credentialscontainer/create) when a [`PublicKeyCredential`](publickeycredential) is passed, and provides a cryptographic root of trust for the new key pair that has been generated. This response should be sent to the relying party's server to complete the creation of the credential.

 This interface inherits from [`AuthenticatorResponse`](authenticatorresponse).


 AuthenticatorResponse AuthenticatorAttestationResponse  **Note:** This interface is restricted to top-level contexts. Use from within an [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe) element will not have any effect.

 

Instance properties
-------------------



*Also inherits properties from its parent, [`AuthenticatorResponse`](authenticatorresponse).*

  
[`AuthenticatorAttestationResponse.attestationObject`](authenticatorattestationresponse/attestationobject) Secure context Read only 
  An [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing authenticator data and an attestation statement for a newly-created key pair.

  

Instance methods
----------------


 
[`AuthenticatorAttestationResponse.getTransports()`](authenticatorattestationresponse/gettransports) Secure context
  Returns an [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of strings describing which transport methods (e.g., `usb`, `nfc`) are believed to be supported with the authenticator. The array may be empty if the information is not available.

  
Examples
--------



```
const publicKey = {
  challenge: new Uint8Array([
    21, 31, 105 /\* 29 more random bytes generated by the server \*/,
  ]),
  rp: {
    name: "Example CORP",
    id: "login.example.com",
  },
  user: {
    id: new Uint8Array(16),
    name: "jdoe@example.com",
    displayName: "John Doe",
  },
  pubKeyCredParams: [
    {
      type: "public-key",
      alg: -7,
    },
  ],
};

navigator.credentials
  .create({ publicKey })
  .then((newCredentialInfo) => {
    const response = newCredentialInfo.response;
    // Do something with the response
    // (sending it back to the relying party server maybe?)
  })
  .catch((err) => console.error(err));

```

Specifications
--------------




| Specification |
| --- |
| [Web Authentication: An API for accessing Public Key Credentials - Level 3 # authenticatorattestationresponse](https://w3c.github.io/webauthn/#authenticatorattestationresponse) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AuthenticatorAttestationResponse` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 48 | 13 | 10.0 |
| `attestationObject` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 48 | 13 | 10.0 |
| `getAuthenticatorData` | 85 | 85 | No | No | 71 | 16 | No | 85 | No | 60 | 16 | 14.0 |
| `getPublicKey` | 85 | 85 | No | No | 71 | 16 | No | 85 | No | 60 | 16 | 14.0 |
| `getPublicKeyAlgorithm` | 85 | 85 | No | No | 71 | 16 | No | 85 | No | 60 | 16 | 14.0 |
| `getTransports` | 74 | 79 | No | No | 62 | 16 | No | 74 | No | 53 | 16 | 11.0 |


See also
--------


* [`AuthenticatorAssertionResponse`](authenticatorassertionresponse): the interface for the type of response given when retrieving an existing credential
* [`AuthenticatorResponse`](authenticatorresponse): the parent interface


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorAttestationResponse>

BackgroundFetchEvent
====================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `BackgroundFetchEvent` interface of the [Background Fetch API](background_fetch_api) is the event type for background fetch events dispatched on the [`service worker global scope`](serviceworkerglobalscope).

 It is the event type passed to `onbackgroundfetchabort` and `onbackgroundfetchclick`.


 Event ExtendableEvent BackgroundFetchEvent

Constructor
-----------


 
[`BackgroundFetchEvent()`](backgroundfetchevent/backgroundfetchevent)  Experimental 
  Creates a new `BackgroundFetchEvent` object. This constructor is not typically used, as the browser creates these objects itself and provides them to background fetch event callbacks.

  
Instance properties
-------------------



*Inherits properties from its ancestor, [`Event`](event)*.

  
[`BackgroundFetchEvent.registration`](backgroundfetchevent/registration) Read only   Experimental 
  Returns the [`BackgroundFetchRegistration`](backgroundfetchregistration) that the event was initialized to.

  

### Event handlers


None.


Instance methods
----------------


None.


Examples
--------



In this example, if the user clicks on the user interface displaying the download progress, a new window will open. The current [`BackgroundFetchRegistration`](backgroundfetchregistration) is returned by calling `event.registration`.

 
```
addEventListener("backgroundfetchclick", (event) => {
  const bgFetch = event.registration;

  if (bgFetch.result === "success") {
    clients.openWindow("/latest-podcasts");
  } else {
    clients.openWindow("/download-progress");
  }
});

```


Specifications
--------------




| Specification |
| --- |
| [Background Fetch # background-fetch-event](https://wicg.github.io/background-fetch/#background-fetch-event) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `BackgroundFetchEvent` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `BackgroundFetchEvent` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `registration` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/BackgroundFetchEvent>

AuthenticatorAssertionResponse
==============================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `AuthenticatorAssertionResponse` interface of the [Web Authentication API](web_authentication_api) is returned by [`CredentialsContainer.get()`](credentialscontainer/get) when a [`PublicKeyCredential`](publickeycredential) is passed, and provides proof to a service that it has a key pair and that the authentication request is valid and approved.

 This interface inherits from [`AuthenticatorResponse`](authenticatorresponse).


 AuthenticatorResponse AuthenticatorAssertionResponse  **Note:** This interface is restricted to top-level contexts. Use from within an [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe) element will not have any effect.

 

Instance properties
-------------------



*Also inherits properties from its parent, [`AuthenticatorResponse`](authenticatorresponse).*

  
[`AuthenticatorAssertionResponse.authenticatorData`](authenticatorassertionresponse/authenticatordata) Secure context Read only 
  An [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing information from the authenticator such as the Relying Party ID Hash (rpIdHash), a signature counter, test of user presence and user verification flags, and any extensions processed by the authenticator.

  
[`AuthenticatorAssertionResponse.signature`](authenticatorassertionresponse/signature) Secure context Read only 
  An assertion signature over [`AuthenticatorAssertionResponse.authenticatorData`](authenticatorassertionresponse/authenticatordata) and [`AuthenticatorResponse.clientDataJSON`](authenticatorresponse/clientdatajson). The assertion signature is created with the private key of keypair that was created during the [`navigator.credentials.create()`](credentialscontainer/create) call and verified using the public key of that same keypair.

  
[`AuthenticatorAssertionResponse.userHandle`](authenticatorassertionresponse/userhandle) Secure context Read only 
  An [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing an opaque user identifier.

  

Instance methods
----------------


None.


Examples
--------



```
const options = {
  challenge: new Uint8Array([
    /\* bytes sent from the server \*/
  ]),
};

navigator.credentials
  .get({ publicKey: options })
  .then((credentialInfoAssertion) => {
    const assertionResponse = credentialInfoAssertion.response;
    // Do something specific with the response

    // send assertion response back to the server
    // to proceed with the control of the credential
  })
  .catch((err) => console.error(err));

```

Specifications
--------------




| Specification |
| --- |
| [Web Authentication: An API for accessing Public Key Credentials - Level 3 # iface-authenticatorassertionresponse](https://w3c.github.io/webauthn/#iface-authenticatorassertionresponse) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AuthenticatorAssertionResponse` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 48 | 13 | 10.0 |
| `authenticatorData` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 48 | 13 | 10.0 |
| `signature` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 48 | 13 | 10.0 |
| `userHandle` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 48 | 13 | 10.0 |


See also
--------


* [`AuthenticatorAttestationResponse`](authenticatorattestationresponse): the interface for the type of response given when creating a new credential
* [`AuthenticatorResponse`](authenticatorresponse): the parent interface


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorAssertionResponse>

AuthenticatorResponse
=====================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `AuthenticatorResponse` interface of the [Web Authentication API](web_authentication_api) is the base interface for interfaces that provide a cryptographic root of trust for a key pair. The child interfaces include information from the browser such as the challenge origin and either may be returned from [`PublicKeyCredential.response`](publickeycredential/response).



Interfaces based on AuthenticatorResponse
-----------------------------------------



Below is a list of interfaces based on the AuthenticatorResponse interface.

 * [`AuthenticatorAssertionResponse`](authenticatorassertionresponse)
* [`AuthenticatorAttestationResponse`](authenticatorattestationresponse)



Instance properties
-------------------


 [`AuthenticatorResponse.clientDataJSON`](authenticatorresponse/clientdatajson)  A [JSON](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON) string in an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), representing the client data that was passed to [`CredentialsContainer.create()`](credentialscontainer/create) or [`CredentialsContainer.get()`](credentialscontainer/get).

  
Instance methods
----------------


None.


Examples
--------


### Getting an AuthenticatorAssertionResponse



```
const options = {
  challenge: new Uint8Array([
    /\* bytes sent from the server \*/
  ]),
};

navigator.credentials
  .get({ publicKey: options })
  .then((credentialInfoAssertion) => {
    const assertionResponse = credentialInfoAssertion.response;
    // send assertion response back to the server
    // to proceed with the control of the credential
  })
  .catch((err) => console.error(err));

```

### Getting an AuthenticatorAttestationResponse



```
const publicKey = {
  challenge: new Uint8Array([
    21, 31, 105 /\* 29 more random bytes generated by the server \*/,
  ]),
  rp: {
    name: "Example CORP",
    id: "login.example.com",
  },
  user: {
    id: new Uint8Array(16),
    name: "jdoe@example.com",
    displayName: "John Doe",
  },
  pubKeyCredParams: [
    {
      type: "public-key",
      alg: -7,
    },
  ],
};

navigator.credentials
  .create({ publicKey })
  .then((newCredentialInfo) => {
    const attestationResponse = newCredentialInfo.response;
  })
  .catch((err) => console.error(err));

```

Specifications
--------------




| Specification |
| --- |
| [Web Authentication: An API for accessing Public Key Credentials - Level 3 # authenticatorresponse](https://w3c.github.io/webauthn/#authenticatorresponse) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `AuthenticatorResponse` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 48 | 13 | 10.0 |
| `clientDataJSON` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 48 | 13 | 10.0 |


See also
--------


* [`AuthenticatorAttestationResponse`](authenticatorattestationresponse)
* [`AuthenticatorAssertionResponse`](authenticatorassertionresponse)
* [`PublicKeyCredential.response`](publickeycredential/response)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/AuthenticatorResponse>

BackgroundFetchManager
======================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `BackgroundFetchManager` interface of the [Background Fetch API](background_fetch_api) is a map where the keys are background fetch IDs and the values are [`BackgroundFetchRegistration`](backgroundfetchregistration) objects.



Instance properties
-------------------


None.


Instance methods
----------------


 
[`fetch()`](backgroundfetchmanager/fetch)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with a [`BackgroundFetchRegistration`](backgroundfetchregistration) object for a supplied array of URLs and [`Request`](request) objects.

  
[`get()`](backgroundfetchmanager/get)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with the [`BackgroundFetchRegistration`](backgroundfetchregistration) associated with the provided `id` or [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) if the `id` is not found.

  
[`getIds()`](backgroundfetchmanager/getids)  Experimental 
  Returns the IDs of all registered background fetches.

  
Examples
--------



The example below shows how to get an instance of [`BackgroundFetchManager`](backgroundfetchmanager) from a [`ServiceWorkerRegistration`](serviceworkerregistration) object and calls `fetch()` to download an audio file in the background.

 
```
navigator.serviceWorker.ready.then(async (swReg) => {
  const bgFetch = await swReg.backgroundFetch.fetch(
    "my-fetch",
    ["/ep-5.mp3", "ep-5-artwork.jpg"],
    {
      title: "Episode 5: Interesting things.",
      icons: [
        {
          sizes: "300x300",
          src: "/ep-5-icon.png",
          type: "image/png",
        },
      ],
      downloadTotal: 60 \* 1024 \* 1024,
    }
  );
});

```


Specifications
--------------




| Specification |
| --- |
| [Background Fetch # background-fetch-manager](https://wicg.github.io/background-fetch/#background-fetch-manager) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `BackgroundFetchManager` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `fetch` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `get` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `getIds` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/BackgroundFetchManager>

BackgroundFetchRecord
=====================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `BackgroundFetchRecord` interface of the [Background Fetch API](background_fetch_api) represents an individual request and response.

 A `BackgroundFetchRecord` is created by the [`BackgroundFetchManager.fetch()`](backgroundfetchmanager/fetch) method, therefore there is no constructor for this interface.

 There will be one `BackgroundFetchRecord` for each resource requested by `fetch()`.



Instance properties
-------------------


 
[`request`](backgroundfetchrecord/request) Read only   Experimental 
  Returns a [`Request`](request).

  
[`responseReady`](backgroundfetchrecord/responseready) Read only   Experimental 
  Returns a promise that resolves with a [`Response`](response).

  
Examples
--------



In this example an individual `BackgroundFetchRecord` is returned using [`BackgroundFetchManager.fetch()`](backgroundfetchmanager/fetch). The [`BackgroundFetchRecord.request`](backgroundfetchrecord/request) and [`BackgroundFetchRecord.responseReady`](backgroundfetchrecord/responseready) are returned and logged to the console.

 
```
bgFetch.match("/ep-5.mp3").then(async (record) => {
  if (!record) {
    console.log("No record found");
    return;
  }

  console.log(`Here's the request`, record.request);
  const response = await record.responseReady;
  console.log(`And here's the response`, response);
});

```


Specifications
--------------




| Specification |
| --- |
| [Background Fetch # background-fetch-record-interface](https://wicg.github.io/background-fetch/#background-fetch-record-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `BackgroundFetchRecord` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `request` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `responseReady` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/BackgroundFetchRecord>

BackgroundFetchRegistration
===========================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `BackgroundFetchRegistration` interface of the [Background Fetch API](background_fetch_api) represents an individual background fetch.

 A `BackgroundFetchRegistration` instance is returned by the [`BackgroundFetchManager.fetch()`](backgroundfetchmanager/fetch) or [`BackgroundFetchManager.get()`](backgroundfetchmanager/get) methods, and therefore there has no constructor.


 EventTarget BackgroundFetchRegistration

Instance properties
-------------------



The following properties are available synchronously, as convenience properties copied from those in the `BackgroundFetchRegistration` instance.

  
[`BackgroundFetchRegistration.id`](backgroundfetchregistration/id) Read only   Experimental 
  A string containing the background fetch's ID.

  
[`BackgroundFetchRegistration.uploadTotal`](backgroundfetchregistration/uploadtotal) Read only   Experimental 
  A [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) containing the total number of bytes to be uploaded.

  
[`BackgroundFetchRegistration.uploaded`](backgroundfetchregistration/uploaded) Read only   Experimental 
  A [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) containing the size in bytes successfully sent, initially `0`.

  
[`BackgroundFetchRegistration.downloadTotal`](backgroundfetchregistration/downloadtotal) Read only   Experimental 
  A [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) containing the total size in bytes of this download. This is the value set when the background fetch was registered, or `0`.

  
[`BackgroundFetchRegistration.downloaded`](backgroundfetchregistration/downloaded) Read only   Experimental 
  A [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) containing the size in bytes that has been downloaded, initially `0`.

  
[`BackgroundFetchRegistration.result`](backgroundfetchregistration/result) Read only   Experimental 
  Returns an empty string initially, on completion either the string `"success"` or `"failure"`.

  
[`BackgroundFetchRegistration.failureReason`](backgroundfetchregistration/failurereason) Read only   Experimental 
  One of the following strings:

  `""`  The background fetch has not completed, or was successful.

  `"aborted"`  The operation was cancelled by the user, or [`abort()`](backgroundfetchregistration/abort) was called.

  `"bad-status"`  A response had a not-ok status (a status outside the range 200-299).

  `"fetch-error"`  A fetch failed for other reasons, for example CORS, or a network failure.

  `"quota-exceeded"`  Storage quota was reached during the operation.

  `"download-total-exceeded"`  The provided `downloadTotal` was exceeded. This value was set when the background fetch was registered.

    
[`BackgroundFetchRegistration.recordsAvailable`](backgroundfetchregistration/recordsavailable) Read only   Experimental 
  A [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean) indicating whether the `recordsAvailable` flag is set.

  

Instance methods
----------------


 
[`BackgroundFetchRegistration.abort()`](backgroundfetchregistration/abort)  Experimental 
  Aborts the background fetch. Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with `true` if the fetch was successfully aborted.

  
[`BackgroundFetchRegistration.match()`](backgroundfetchregistration/match)  Experimental 
  Returns a single [`BackgroundFetchRecord`](backgroundfetchrecord) object which is the first match for the arguments.

  
[`BackgroundFetchRegistration.matchAll()`](backgroundfetchregistration/matchall)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with an array of [`BackgroundFetchRecord`](backgroundfetchrecord) objects containing requests and responses.

  
Events
------



Listen to these events using [`addEventListener()`](eventtarget/addeventlistener) or by assigning an event listener to the `oneventname` property of this interface.

  
[`progress`](backgroundfetchregistration/progress_event)  Experimental 
   Fired when there is a change to any of the following properties: [`uploaded`](backgroundfetchregistration/uploaded), [`downloaded`](backgroundfetchregistration/downloaded), [`result`](backgroundfetchregistration/result) or [`failureReason`](backgroundfetchregistration/failurereason). 

  

Examples
--------



The following code creates a `BackGroundFetchRegistration` as `bgFetch`, with an `id` of `"my-fetch"`.

 
```
navigator.serviceWorker.ready.then(async (swReg) => {
  const bgFetch = await swReg.backgroundFetch.fetch(
    "my-fetch",
    ["/ep-5.mp3", "ep-5-artwork.jpg"],
    {
      title: "Episode 5: Interesting things.",
      icons: [
        {
          sizes: "300x300",
          src: "/ep-5-icon.png",
          type: "image/png",
        },
      ],
      downloadTotal: 60 \* 1024 \* 1024,
    }
  );
});

```
 Logging the [`id`](backgroundfetchregistration/id) to the console returns `"my-fetch"`.

 
```
console.log(bgFetch.id); // "my-fetch"

```
 The [`match()`](backgroundfetchregistration/match) method can be used to find a particular [`BackgroundFetchRecord`](backgroundfetchrecord) from those that are part of the registration.

 
```
bgFetch.match("/ep-5.mp3").then(async (record) => {
  if (!record) {
    console.log("No record found");
    return;
  }

  console.log(`Here's the request`, record.request);
  const response = await record.responseReady;
  console.log(`And here's the response`, response);
});

```


Specifications
--------------




| Specification |
| --- |
| [Background Fetch # background-fetch-registration](https://wicg.github.io/background-fetch/#background-fetch-registration) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `BackgroundFetchRegistration` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `abort` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `downloadTotal` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `downloaded` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `failureReason` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `id` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `match` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `matchAll` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `progress_event` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `recordsAvailable` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `result` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `uploadTotal` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `uploaded` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/BackgroundFetchRegistration>

BackgroundFetchUpdateUIEvent
============================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `BackgroundFetchUpdateUIEvent` interface of the [Background Fetch API](background_fetch_api) is an event type for the [`backgroundfetchsuccess`](serviceworkerglobalscope/backgroundfetchsuccess_event) and [`backgroundfetchfail`](serviceworkerglobalscope/backgroundfetchfail_event) events, and provides a method for updating the title and icon of the app to inform a user of the success or failure of a background fetch.


 Event ExtendableEvent BackgroundFetchEvent BackgroundFetchUpdateUIEvent

Constructor
-----------


 
[`BackgroundFetchUpdateUIEvent()`](backgroundfetchupdateuievent/backgroundfetchupdateuievent)  Experimental 
  Creates a new `BackgroundFetchUIEvent` object. This constructor is not typically used, as the browser creates these objects itself for the [`backgroundfetchsuccess`](serviceworkerglobalscope/backgroundfetchsuccess_event) and [`backgroundfetchfail`](serviceworkerglobalscope/backgroundfetchfail_event) events.

  
Instance properties
-------------------


*This interface doesn't implement any specific properties, but inherits properties from [`Event`](event), and [`BackgroundFetchEvent`](backgroundfetchevent).*


Instance methods
----------------


 
[`BackgroundFetchUpdateUIEvent.updateUI()`](backgroundfetchupdateuievent/updateui)  Experimental 
  Updates the title and icon in the user interface to show the status of a background fetch. Resolves with a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).

  
Examples
--------



In this example, the `backgroundfetchsuccess` event is listened for, indicating that a fetch has completed successfully. The [`updateUI()`](backgroundfetchupdateuievent/updateui) method is then called, with a message to let the user know the episode they downloaded is ready.

 
```
addEventListener("backgroundfetchsuccess", (event) => {
  const bgFetch = event.registration;

  event.waitUntil(
    (async () => {
      // Create/open a cache.
      const cache = await caches.open("downloads");
      // Get all the records.
      const records = await bgFetch.matchAll();
      // Copy each request/response across.
      const promises = records.map(async (record) => {
        const response = await record.responseReady;
        await cache.put(record.request, response);
      });

      // Wait for the copying to complete.
      await Promise.all(promises);

      // Update the progress notification.
      event.updateUI({ title: "Episode 5 ready to listen!" });
    })()
  );
});

```


Specifications
--------------




| Specification |
| --- |
| [Background Fetch # background-fetch-update-ui-event](https://wicg.github.io/background-fetch/#background-fetch-update-ui-event) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `BackgroundFetchUpdateUIEvent` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `BackgroundFetchUpdateUIEvent` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |
| `updateUI` | 74 | 79 | No | No | 62 | No | No | 74 | No | 53 | No | 11.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/BackgroundFetchUpdateUIEvent>

BarcodeDetector
===============



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `BarcodeDetector` interface of the [`Barcode Detection API`](barcode_detection_api) allows detection of linear and two dimensional barcodes in images.



Constructors
------------


 
[`BarcodeDetector.BarcodeDetector()`](barcodedetector/barcodedetector)  Experimental 
  Creates and returns a `BarcodeDetector` object, with optional `barcodeDetectorOptions`

  
Static methods
--------------


 
[`getSupportedFormats()`](barcodedetector/getsupportedformats)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which fulfills with an [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of supported [barcode format types](barcode_detection_api#supported_barcode_formats).

  
Instance methods
----------------


 
[`detect()`](barcodedetector/detect)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which fulfills with an array of `detectedBarcode` objects with the following properties:

 * `boundingBox`: A [`DOMRectReadOnly`](domrectreadonly), which returns the dimensions of a rectangle representing the extent of a detected barcode, aligned with the image.
* `cornerPoints`: The x and y co-ordinates of the four corner points of the detected barcode relative to the image, starting with the top left and working clockwise. This may not be square due to perspective distortions within the image.
* `format`: The detected barcode format. (For a full list of formats see the [landing page])
* `rawValue`: A string decoded from the barcode data.

  
Examples
--------


### Creating A Detector



This example creates a new barcode detector object, with specified supported formats and tests for browser compatibility.

 
```
// create new detector
const barcodeDetector = new BarcodeDetector({
  formats: ["code\_39", "codabar", "ean\_13"],
});

// check compatibility
if (barcodeDetector) {
  console.log("Barcode Detector supported!");
} else {
  console.log("Barcode Detector is not supported by this browser.");
}

```


### Getting Supported Formats



The following example calls the `getSupportFormat()` static method and logs the results to the console.

 
```
// check supported types
BarcodeDetector.getSupportedFormats().then((supportedFormats) => {
  supportedFormats.forEach((format) => console.log(format));
});

```


### Detect Barcodes



This example uses the `detect()` method to detect the barcodes within the given image. These are iterated over and the barcode data is logged to the console.

 
```
barcodeDetector
  .detect(imageEl)
  .then((barcodes) => {
    barcodes.forEach((barcode) => console.log(barcode.rawValue));
  })
  .catch((err) => {
    console.log(err);
  });

```


Specifications
--------------




| Specification |
| --- |
| [Accelerated Shape Detection in Images # barcode-detection-api](https://wicg.github.io/shape-detection-api/#barcode-detection-api) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `BarcodeDetector` | 88Supported on Chrome OS and macOS only.83–88Supported on macOS only. | 83Supported on macOS only. | No | No | 69Supported on macOS only. | No | 83 | 83 | No | 59 | No | 13.0 |
| `BarcodeDetector` | 88Supported on Chrome OS and macOS only.83–88Supported on macOS only. | 83Supported on macOS only. | No | No | 69Supported on macOS only. | No | 83 | 83 | No | 59 | No | 13.0 |
| `detect` | 88Supported on Chrome OS and macOS only.83–88Supported on macOS only. | 83Supported on macOS only. | No | No | 69Supported on macOS only. | No | 83 | 83 | No | 59 | No | 13.0 |
| `getSupportedFormats` | 88Supported on Chrome OS and macOS only.83–88Supported on macOS only. | 83Supported on macOS only. | No | No | 69Supported on macOS only. | No | 83 | 83 | No | 59 | No | 13.0 |


See also
--------


* [barcodefaq.com: A website with information about different barcodes and examples of the different types.](https://www.barcodefaq.com/)
* [Accelerated Shape Detection in Images](https://web.dev/shape-detection/#barcodedetector)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/BarcodeDetector>

BarProp
=======



The `BarProp` interface of the [`Document Object Model`](document_object_model) represents the web browser user interface elements that are exposed to scripts in web pages. Each of the following interface elements are represented by a `BarProp` object.

  [`Window.locationbar`](window/locationbar)  The browser location bar.

  [`Window.menubar`](window/menubar)  The browser menu bar.

  [`Window.personalbar`](window/personalbar)  The browser personal bar.

  [`Window.scrollbars`](window/scrollbars)  The browser scrollbars.

  [`Window.statusbar`](window/statusbar)  The browser status bar.

  [`Window.toolbar`](window/toolbar)  The browser toolbar.

   The `BarProp` interface is not accessed directly, but via one of these elements.



Instance properties
-------------------


 
[`BarProp.visible`](barprop/visible) Read only 
  A [`Boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean), which is true if the bar represented by the used interface element is visible.

  
Examples
--------



The following example prints a `BarProp` object to the console that represents the location bar.

 
```
console.log(window.locationbar);

```


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # barprop](https://html.spec.whatwg.org/multipage/window-object.html#barprop) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `BarProp` | 1 | 12 | 1 | No | 15 | 3 | ≤37 | 18 | 4 | 14 | 1 | 1.0 |
| `visible` | 1 | 12 | 1 | No | 15 | 3 | ≤37 | 18 | 4 | 14 | 1 | 1.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/BarProp>

BiquadFilterNode
================



The `BiquadFilterNode` interface represents a simple low-order filter, and is created using the [`BaseAudioContext/createBiquadFilter`](baseaudiocontext/createbiquadfilter) method. It is an [`AudioNode`](audionode) that can represent different kinds of filters, tone control devices, and graphic equalizers. A `BiquadFilterNode` always has exactly one input and one output.


 EventTarget AudioNode BiquadFilterNode 

|  |  |
| --- | --- |
| Number of inputs | `1` |
| Number of outputs | `1` |
| Channel count mode | `"max"` |
| Channel count | `2` (not used in the default count mode) |
| Channel interpretation | `"speakers"` |



Constructor
-----------


 [`BiquadFilterNode()`](biquadfilternode/biquadfilternode)  Creates a new instance of a `BiquadFilterNode` object.

  
Instance properties
-------------------



*Inherits properties from its parent, [`AudioNode`](audionode)*.

  **Note:** Though the `AudioParam` objects returned are read-only, the values they represent are not.

   
[`BiquadFilterNode.frequency`](biquadfilternode/frequency) Read only 
  An [a-rate](audioparam#a-rate) [`AudioParam`](audioparam), a double representing a frequency in the current filtering algorithm measured in hertz (Hz).

  
[`BiquadFilterNode.detune`](biquadfilternode/detune) Read only 
  An [a-rate](audioparam#a-rate) [`AudioParam`](audioparam) representing detuning of the frequency in [cents](https://en.wikipedia.org/wiki/Cent_%28music%29).

  
[`BiquadFilterNode.Q`](biquadfilternode/q) Read only 
  An [a-rate](audioparam#a-rate) [`AudioParam`](audioparam), a double representing a [Q factor](https://en.wikipedia.org/wiki/Q_factor), or *quality factor*.

  
[`BiquadFilterNode.gain`](biquadfilternode/gain) Read only 
  An [a-rate](audioparam#a-rate) [`AudioParam`](audioparam), a double representing the [gain](https://en.wikipedia.org/wiki/Gain) used in the current filtering algorithm.

  [`BiquadFilterNode.type`](biquadfilternode/type)  A string value defining the kind of filtering algorithm the node is implementing.

 

 The meaning of the different parameters depending on the type of the filter (detune has the same meaning regardless, so isn't listed below) | `type` | Description | `frequency` | `Q` | `gain` |
| --- | --- | --- | --- | --- |
| `lowpass` |  Standard second-order resonant lowpass filter with 12dB/octave rolloff. Frequencies below the cutoff pass through; frequencies above it are attenuated.  | The cutoff frequency. |  Indicates how peaked the frequency is around the cutoff. The greater the value is, the greater is the peak.  | *Not used* |
| `highpass` |  Standard second-order resonant highpass filter with 12dB/octave rolloff. Frequencies below the cutoff are attenuated; frequencies above it pass through.  | The cutoff frequency. |  Indicates how peaked the frequency is around the cutoff. The greater the value, the greater the peak.  | *Not used* |
| `bandpass` |  Standard second-order bandpass filter. Frequencies outside the given range of frequencies are attenuated; the frequencies inside it pass through.  | The center of the range of frequencies. |  Controls the width of the frequency band. The greater the `Q` value, the smaller the frequency band.  | *Not used* |
| `lowshelf` |  Standard second-order lowshelf filter. Frequencies lower than the frequency get a boost, or an attenuation; frequencies over it are unchanged.  | The upper limit of the frequencies getting a boost or an attenuation. | *Not used* | The boost, in dB, to be applied; if negative, it will be an attenuation. |
| `highshelf` |  Standard second-order highshelf filter. Frequencies higher than the frequency get a boost or an attenuation; frequencies lower than it are unchanged.  | The lower limit of the frequencies getting a boost or an attenuation. | *Not used* | The boost, in dB, to be applied; if negative, it will be an attenuation. |
| `peaking` |  Frequencies inside the range get a boost or an attenuation; frequencies outside it are unchanged.  | The middle of the frequency range getting a boost or an attenuation. |  Controls the width of the frequency band. The greater the `Q` value, the smaller the frequency band.  | The boost, in dB, to be applied; if negative, it will be an attenuation. |
| `notch` |  Standard [notch](https://en.wikipedia.org/wiki/Band-stop_filter) filter, also called a *band-stop* or *band-rejection* filter. It is the opposite of a bandpass filter: frequencies outside the give range of frequencies pass through; frequencies inside it are attenuated.  | The center of the range of frequencies. |  Controls the width of the frequency band. The greater the `Q` value, the smaller the frequency band.  | *Not used* |
| `allpass` |  Standard second-order [allpass](https://en.wikipedia.org/wiki/All-pass_filter#Digital_Implementation) filter. It lets all frequencies through, but changes the phase-relationship between the various frequencies.  |  The frequency with the maximal [group delay](https://en.wikipedia.org/wiki/Group_delay_and_phase_delay), that is, the frequency where the center of the phase transition occurs.  |  Controls how sharp the transition is at the medium frequency. The larger this parameter is, the sharper and larger the transition will be.  | *Not used* |

  

Instance methods
----------------



*Inherits methods from its parent, [`AudioNode`](audionode)*.

  [`BiquadFilterNode.getFrequencyResponse()`](biquadfilternode/getfrequencyresponse)  From the current filter parameter settings this method calculates the frequency response for frequencies specified in the provided array of frequencies.

  

Example
-------


See [`AudioContext.createBiquadFilter`](baseaudiocontext/createbiquadfilter#examples) for example code that shows how to use an `AudioContext` to create a Biquad filter node.


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # BiquadFilterNode](https://webaudio.github.io/web-audio-api/#BiquadFilterNode) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `BiquadFilterNode` | 55 | 79 | 53 | No | 42 | 14.1 | 55 | 55 | 53 | 42 | 14.5 | 6.0 |
| `Q` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `BiquadFilterNode` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `detune` | 25 | 12 | 25 | No | 15 | 7 | ≤37 | 25 | 25 | 14 | 7 | 1.5 |
| `frequency` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `gain` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `getFrequencyResponse` | 17 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `type` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/BiquadFilterNode>

BlobEvent
=========



The `BlobEvent` interface represents events associated with a [`Blob`](blob). These blobs are typically, but not necessarily, associated with media content.


 Event BlobEvent

Constructor
-----------


 [`BlobEvent()`](blobevent/blobevent)  Creates a `BlobEvent` event with the given parameters.

  
Instance properties
-------------------



*Inherits properties from its parent [`Event`](event)*.

  
[`BlobEvent.data`](blobevent/data) Read only 
  A [`Blob`](blob) representing the data associated with the event. The event was fired on the [`EventTarget`](eventtarget) because of something happening on that specific [`Blob`](blob).

  
[`BlobEvent.timecode`](blobevent/timecode) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) indicating the difference between the timestamp of the first chunk in data and the timestamp of the first chunk in the first BlobEvent produced by this recorder. Note that the timecode in the first produced BlobEvent does not need to be zero.

  

Instance methods
----------------


*No specific method; inherits methods from its parent [`Event`](event).*


Specifications
--------------




| Specification |
| --- |
| [MediaStream Recording # blobevent-section](https://w3c.github.io/mediacapture-record/#blobevent-section) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `BlobEvent` | 49 | 79 | 21 | No | 36 | 14 | 49 | 49 | 21 | 36 | 14 | 5.0 |
| `BlobEvent` | 49 | 79 | 21 | No | 36 | 14 | 49 | 49 | 21 | 36 | 14 | 5.0 |
| `data` | 49 | 79 | 21 | No | 36 | 14 | 49 | 49 | 21 | 36 | 14 | 5.0 |
| `timecode` | 57 | 79 | NoSee [bug 1573299](https://bugzil.la/1573299). | No | 44 | 14.1 | 57 | 57 | NoSee [bug 1573299](https://bugzil.la/1573299). | 43 | 14.5 | 7.0 |


See also
--------


* The [`Event`](event) base interface.
* [MediaStream Recording API](mediastream_recording_api): Sends `BlobEvent` objects each time a chunk of media is ready.
* [Using the MediaStream Recording API](mediastream_recording_api/using_the_mediastream_recording_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/BlobEvent>

BluetoothCharacteristicProperties
=================================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `BluetoothCharacteristicProperties` interface of the [Web Bluetooth API](web_bluetooth_api) provides the operations that are valid on the given [`BluetoothRemoteGATTCharacteristic`](bluetoothremotegattcharacteristic).

 This interface is returned by calling [`BluetoothRemoteGATTCharacteristic.properties`](bluetoothremotegattcharacteristic/properties).



Instance properties
-------------------


 
[`authenticatedSignedWrites`](bluetoothcharacteristicproperties/authenticatedsignedwrites) Read only   Experimental 
  Returns a `boolean` that is `true` if signed writing to the characteristic value is permitted.

  
[`broadcast`](bluetoothcharacteristicproperties/broadcast) Read only   Experimental 
  Returns a `boolean` that is `true` if the broadcast of the characteristic value is permitted using the Server Characteristic Configuration Descriptor.

  
[`indicate`](bluetoothcharacteristicproperties/indicate) Read only   Experimental 
  Returns a `boolean` that is `true` if indications of the characteristic value with acknowledgement is permitted.

  
[`notify`](bluetoothcharacteristicproperties/notify) Read only   Experimental 
  Returns a `boolean` that is `true` if notifications of the characteristic value without acknowledgement is permitted.

  
[`read`](bluetoothcharacteristicproperties/read) Read only   Experimental 
  Returns a `boolean` that is `true` if the reading of the characteristic value is permitted.

  
[`reliableWrite`](bluetoothcharacteristicproperties/reliablewrite) Read only   Experimental 
  Returns a `boolean` that is `true` if reliable writes to the characteristic is permitted.

  
[`writableAuxiliaries`](bluetoothcharacteristicproperties/writableauxiliaries) Read only   Experimental 
  Returns a `boolean` that is `true` if reliable writes to the characteristic descriptor is permitted.

  
[`write`](bluetoothcharacteristicproperties/write) Read only   Experimental 
  Returns a `boolean` that is `true` if the writing to the characteristic with response is permitted.

  
[`writeWithoutResponse`](bluetoothcharacteristicproperties/writewithoutresponse) Read only   Experimental 
  Returns a `boolean` that is `true` if the writing to the characteristic without response is permitted.

  
Examples
--------



The following example shows how tell if a GATT characteristic supports value change notifications.

 
```
let device = await navigator.bluetooth.requestDevice({
  filters: [{ services: ["heart\_rate"] }],
});
let gatt = await device.gatt.connect();
let service = await gatt.getPrimaryService("heart\_rate");
let characteristic = await service.getCharacteristic("heart\_rate\_measurement");
if (characteristic.properties.notify) {
  characteristic.addEventListener(
    "characteristicvaluechanged",
    async (event) => {
      console.log(`Received heart rate measurement: ${event.target.value}`);
    }
  );
  await characteristic.startNotifications();
}

```


Specifications
--------------




| Specification |
| --- |
| [Web Bluetooth # characteristicproperties-interface](https://webbluetoothcg.github.io/web-bluetooth/#characteristicproperties-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `BluetoothCharacteristicProperties` | 56Before Chrome 70, this feature was only supported in macOS. In Chrome 70, support was added for Windows 10. Linux support is not enabled by default.56In Linux and versions of Windows earlier than 10, this flag must be enabled. | 79Supported by default only on macOS and Windows 10. Linux support is not enabled by default.79In Linux and versions of Windows earlier than 10, this flag must be enabled. | No | No | 43Before Opera 57, this feature was only supported in macOS. In Opera 57, support was added for Windows 10. Linux support is not enabled by default.43In Linux and versions of Windows earlier than 10, this flag must be enabled. | No | NoSee [bug 1100993](https://crbug.com/1100993). | 56 | No | 43 | No | 6.0 |
| `authenticatedSignedWrites` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `broadcast` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `indicate` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `notify` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `read` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `reliableWrite` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `writableAuxiliaries` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `write` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `writeWithoutResponse` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/BluetoothCharacteristicProperties>

BluetoothDevice
===============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

  The BluetoothDevice interface of the [Web Bluetooth API](web_bluetooth_api) represents a Bluetooth device inside a particular script execution environment. 


 EventTarget BluetoothDevice

Instance properties
-------------------


 
[`BluetoothDevice.id`](bluetoothdevice/id)  Experimental  Read only 
  A string that uniquely identifies a device.

  
[`BluetoothDevice.name`](bluetoothdevice/name)  Experimental  Read only 
  A string that provides a human-readable name for the device.

  
[`BluetoothDevice.gatt`](bluetoothdevice/gatt)  Experimental  Read only 
  A reference to the device's [`BluetoothRemoteGATTServer`](bluetoothremotegattserver).

  
Instance methods
----------------


 
`BluetoothDevice.watchAdvertisements()`  Experimental 
   A [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to `undefined` or is rejected with an error if advertisements can't be shown for any reason. 

  
`BluetoothDevice.forget()`  Experimental 
  Provides a way for the page to revoke access to a device the user has granted access to.

  
Specifications
--------------




| Specification |
| --- |
| [Web Bluetooth # bluetoothdevice-interface](https://webbluetoothcg.github.io/web-bluetooth/#bluetoothdevice-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `BluetoothDevice` | 56Before Chrome 70, this feature was only supported in macOS. In Chrome 70, support was added for Windows 10. Linux support is not enabled by default.56In Linux and versions of Windows earlier than 10, this flag must be enabled. | 79Supported by default only on macOS and Windows 10. Linux support is not enabled by default.79In Linux and versions of Windows earlier than 10, this flag must be enabled. | No | No | 43Before Opera 57, this feature was only supported in macOS. In Opera 57, support was added for Windows 10. Linux support is not enabled by default.43In Linux and versions of Windows earlier than 10, this flag must be enabled. | No | NoSee [bug 1100993](https://crbug.com/1100993). | 56 | No | 43 | No | 6.0 |
| `gatt` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `gattserverdisconnected_event` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `id` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `name` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/BluetoothDevice>

BluetoothRemoteGATTCharacteristic
=================================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `BluetoothRemoteGattCharacteristic` interface of the [Web Bluetooth API](web_bluetooth_api) represents a GATT Characteristic, which is a basic data element that provides further information about a peripheral's service.


 EventTarget BluetoothRemoteGATTCharacteristic

Instance properties
-------------------


 
[`BluetoothRemoteGATTCharacteristic.service`](bluetoothremotegattcharacteristic/service) Read only   Experimental 
  Returns the [`BluetoothRemoteGATTService`](bluetoothremotegattservice) this characteristic belongs to.

  
[`BluetoothRemoteGATTCharacteristic.uuid`](bluetoothremotegattcharacteristic/uuid) Read only   Experimental 
  Returns a string containing the UUID of the characteristic, for example `'00002a37-0000-1000-8000-00805f9b34fb'` for the Heart Rate Measurement characteristic.

  
[`BluetoothRemoteGATTCharacteristic.properties`](bluetoothremotegattcharacteristic/properties) Read only   Experimental 
  Returns the properties of this characteristic.

  
[`BluetoothRemoteGATTCharacteristic.value`](bluetoothremotegattcharacteristic/value) Read only   Experimental 
  The currently cached characteristic value. This value gets updated when the value of the characteristic is read or updated via a notification or indication.

  
### Events


 
`oncharacteristicvaluechanged`  Experimental 
  Event handler for the `characteristicvaluechanged` event.

  
Instance methods
----------------


 
[`BluetoothRemoteGATTCharacteristic.getDescriptor()`](bluetoothremotegattcharacteristic/getdescriptor)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to the first [`BluetoothRemoteGATTDescriptor`](bluetoothremotegattdescriptor) for a given descriptor UUID.

  
[`BluetoothRemoteGATTCharacteristic.getDescriptors()`](bluetoothremotegattcharacteristic/getdescriptors)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to an [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of all [`BluetoothRemoteGATTDescriptor`](bluetoothremotegattdescriptor) objects for a given descriptor UUID.

  
[`BluetoothRemoteGATTCharacteristic.readValue()`](bluetoothremotegattcharacteristic/readvalue)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) holding a duplicate of the `value` property if it is available and supported. Otherwise it throws an error.

  
[`BluetoothRemoteGATTCharacteristic.writeValue(value)`](bluetoothremotegattcharacteristic/writevalue)  Deprecated 
  Sets the `value` property to the bytes contained in a given [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), calls [`WriteCharacteristicValue`(*this*=`this`, *value=value*, *response*=`"optional"`)](https://webbluetoothcg.github.io/web-bluetooth/#writecharacteristicvalue), and returns the resulting [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).

  
[`BluetoothRemoteGATTCharacteristic.writeValueWithResponse(value)`](bluetoothremotegattcharacteristic/writevaluewithresponse)  Experimental 
  Sets the `value` property to the bytes contained in a given [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), calls [`WriteCharacteristicValue`(*this*=`this`, *value=value*, *response*=`"required"`)](https://webbluetoothcg.github.io/web-bluetooth/#writecharacteristicvalue), and returns the resulting [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).

  
[`BluetoothRemoteGATTCharacteristic.writeValueWithoutResponse(value)`](bluetoothremotegattcharacteristic/writevaluewithoutresponse)  Experimental 
  Sets the `value` property to the bytes contained in a given [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), calls [`WriteCharacteristicValue`(*this*=`this`, *value=value*, *response*=`"never"`)](https://webbluetoothcg.github.io/web-bluetooth/#writecharacteristicvalue), and returns the resulting [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).

  
[`BluetoothRemoteGATTCharacteristic.startNotifications()`](bluetoothremotegattcharacteristic/startnotifications)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) when `navigator.bluetooth` is added to the active notification context.

  
[`BluetoothRemoteGATTCharacteristic.stopNotifications()`](bluetoothremotegattcharacteristic/stopnotifications)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) when `navigator.bluetooth` is removed from the active notification context.

  
Specifications
--------------




| Specification |
| --- |
| [Web Bluetooth # bluetoothgattcharacteristic-interface](https://webbluetoothcg.github.io/web-bluetooth/#bluetoothgattcharacteristic-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `BluetoothRemoteGATTCharacteristic` | 56Before Chrome 70, this feature was only supported in macOS. In Chrome 70, support was added for Windows 10. Linux support is not enabled by default.56In Linux and versions of Windows earlier than 10, this flag must be enabled. | 79Supported by default only on macOS and Windows 10. Linux support is not enabled by default.79In Linux and versions of Windows earlier than 10, this flag must be enabled. | No | No | 43Before Opera 57, this feature was only supported in macOS. In Opera 57, support was added for Windows 10. Linux support is not enabled by default.43In Linux and versions of Windows earlier than 10, this flag must be enabled. | No | NoSee [bug 1100993](https://crbug.com/1100993). | 56 | No | 43 | No | 6.0 |
| `characteristicvaluechanged_event` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `getDescriptor` | 57 | 79 | No | No | 44 | No | No | 57 | No | 43 | No | 7.0 |
| `getDescriptors` | 57 | 79 | No | No | 44 | No | No | 57 | No | 43 | No | 7.0 |
| `properties` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `readValue` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `service` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `startNotifications` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `stopNotifications` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `uuid` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `value` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `writeValue` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `writeValueWithResponse` | 85 | 85 | No | No | 71 | No | No | 85 | No | 60 | No | 14.0 |
| `writeValueWithoutResponse` | 85 | 85 | No | No | 71 | No | No | 85 | No | 60 | No | 14.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/BluetoothRemoteGATTCharacteristic>

BaseAudioContext
================



The `BaseAudioContext` interface of the [Web Audio API](web_audio_api) acts as a base definition for online and offline audio-processing graphs, as represented by [`AudioContext`](audiocontext) and [`OfflineAudioContext`](offlineaudiocontext) respectively. You wouldn't use `BaseAudioContext` directly — you'd use its features via one of these two inheriting interfaces.

 A `BaseAudioContext` can be a target of events, therefore it implements the [`EventTarget`](eventtarget) interface.


 EventTarget BaseAudioContext

Instance properties
-------------------


 
[`BaseAudioContext.audioWorklet`](baseaudiocontext/audioworklet) Read only  Secure context
  Returns the [`AudioWorklet`](audioworklet) object, which can be used to create and manage [`AudioNode`](audionode)s in which JavaScript code implementing the [`AudioWorkletProcessor`](audioworkletprocessor) interface are run in the background to process audio data.

  
[`BaseAudioContext.currentTime`](baseaudiocontext/currenttime) Read only 
  Returns a double representing an ever-increasing hardware time in seconds used for scheduling. It starts at `0`.

  
[`BaseAudioContext.destination`](baseaudiocontext/destination) Read only 
  Returns an [`AudioDestinationNode`](audiodestinationnode) representing the final destination of all audio in the context. It can be thought of as the audio-rendering device.

  
[`BaseAudioContext.listener`](baseaudiocontext/listener) Read only 
  Returns the [`AudioListener`](audiolistener) object, used for 3D spatialization.

  
[`BaseAudioContext.sampleRate`](baseaudiocontext/samplerate) Read only 
  Returns a float representing the sample rate (in samples per second) used by all nodes in this context. The sample-rate of an [`AudioContext`](audiocontext) cannot be changed.

  
[`BaseAudioContext.state`](baseaudiocontext/state) Read only 
  Returns the current state of the `AudioContext`.

  
Instance methods
----------------



*Also implements methods from the interface* [`EventTarget`](eventtarget).

  [`BaseAudioContext.createAnalyser()`](baseaudiocontext/createanalyser)  Creates an [`AnalyserNode`](analysernode), which can be used to expose audio time and frequency data and for example to create data visualizations.

  [`BaseAudioContext.createBiquadFilter()`](baseaudiocontext/createbiquadfilter)  Creates a [`BiquadFilterNode`](biquadfilternode), which represents a second order filter configurable as several different common filter types: high-pass, low-pass, band-pass, etc

  [`BaseAudioContext.createBuffer()`](baseaudiocontext/createbuffer)  Creates a new, empty [`AudioBuffer`](audiobuffer) object, which can then be populated by data and played via an [`AudioBufferSourceNode`](audiobuffersourcenode).

  [`BaseAudioContext.createBufferSource()`](baseaudiocontext/createbuffersource)  Creates an [`AudioBufferSourceNode`](audiobuffersourcenode), which can be used to play and manipulate audio data contained within an [`AudioBuffer`](audiobuffer) object. [`AudioBuffer`](audiobuffer)s are created using [`AudioContext.createBuffer()`](baseaudiocontext/createbuffer) or returned by [`AudioContext.decodeAudioData()`](baseaudiocontext/decodeaudiodata) when it successfully decodes an audio track.

  [`BaseAudioContext.createConstantSource()`](baseaudiocontext/createconstantsource)  Creates a [`ConstantSourceNode`](constantsourcenode) object, which is an audio source that continuously outputs a monaural (one-channel) sound signal whose samples all have the same value.

  [`BaseAudioContext.createChannelMerger()`](baseaudiocontext/createchannelmerger)  Creates a [`ChannelMergerNode`](channelmergernode), which is used to combine channels from multiple audio streams into a single audio stream.

  [`BaseAudioContext.createChannelSplitter()`](baseaudiocontext/createchannelsplitter)  Creates a [`ChannelSplitterNode`](channelsplitternode), which is used to access the individual channels of an audio stream and process them separately.

  [`BaseAudioContext.createConvolver()`](baseaudiocontext/createconvolver)  Creates a [`ConvolverNode`](convolvernode), which can be used to apply convolution effects to your audio graph, for example a reverberation effect.

  [`BaseAudioContext.createDelay()`](baseaudiocontext/createdelay)  Creates a [`DelayNode`](delaynode), which is used to delay the incoming audio signal by a certain amount. This node is also useful to create feedback loops in a Web Audio API graph.

  [`BaseAudioContext.createDynamicsCompressor()`](baseaudiocontext/createdynamicscompressor)  Creates a [`DynamicsCompressorNode`](dynamicscompressornode), which can be used to apply acoustic compression to an audio signal.

  [`BaseAudioContext.createGain()`](baseaudiocontext/creategain)  Creates a [`GainNode`](gainnode), which can be used to control the overall volume of the audio graph.

  [`BaseAudioContext.createIIRFilter()`](baseaudiocontext/createiirfilter)  Creates an [`IIRFilterNode`](iirfilternode), which represents a second order filter configurable as several different common filter types.

  [`BaseAudioContext.createOscillator()`](baseaudiocontext/createoscillator)  Creates an [`OscillatorNode`](oscillatornode), a source representing a periodic waveform. It basically generates a tone.

  [`BaseAudioContext.createPanner()`](baseaudiocontext/createpanner)  Creates a [`PannerNode`](pannernode), which is used to spatialize an incoming audio stream in 3D space.

  [`BaseAudioContext.createPeriodicWave()`](baseaudiocontext/createperiodicwave)  Creates a [`PeriodicWave`](periodicwave), used to define a periodic waveform that can be used to determine the output of an [`OscillatorNode`](oscillatornode).

  
[`BaseAudioContext.createScriptProcessor()`](baseaudiocontext/createscriptprocessor)  Deprecated 
  Creates a [`ScriptProcessorNode`](scriptprocessornode), which can be used for direct audio processing via JavaScript.

  [`BaseAudioContext.createStereoPanner()`](baseaudiocontext/createstereopanner)  Creates a [`StereoPannerNode`](stereopannernode), which can be used to apply stereo panning to an audio source.

  [`BaseAudioContext.createWaveShaper()`](baseaudiocontext/createwaveshaper)  Creates a [`WaveShaperNode`](waveshapernode), which is used to implement non-linear distortion effects.

  [`BaseAudioContext.decodeAudioData()`](baseaudiocontext/decodeaudiodata)  Asynchronously decodes audio file data contained in an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). In this case, the `ArrayBuffer` is usually loaded from an [`XMLHttpRequest`](xmlhttprequest)'s `response` attribute after setting the `responseType` to `arraybuffer`. This method only works on complete files, not fragments of audio files.

  

Events
------


 [`statechange`](baseaudiocontext/statechange_event)  Fired when the `AudioContext`'s state changes due to the calling of one of the state change methods ([`AudioContext.suspend`](audiocontext/suspend), [`AudioContext.resume`](audiocontext/resume), or [`AudioContext.close`](audiocontext/close)).

  
Examples
--------



Basic audio context declaration:

 
```
const audioContext = new AudioContext();

```
 Cross browser variant:

 
```
const AudioContext = window.AudioContext || window.webkitAudioContext;
const audioContext = new AudioContext();

const oscillatorNode = audioContext.createOscillator();
const gainNode = audioContext.createGain();
const finish = audioContext.destination;

```


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # BaseAudioContext](https://webaudio.github.io/web-audio-api/#BaseAudioContext) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `BaseAudioContext` | 5614–56The `BaseAudioContext` interface itself is not present, but many of the methods are available on the [`AudioContext`](https://developer.mozilla.org/docs/Web/API/AudioContext) and [`OfflineAudioContext`](https://developer.mozilla.org/docs/Web/API/OfflineAudioContext) interfaces. | 7912–79The `BaseAudioContext` interface itself is not present, but many of the methods are available on the [`AudioContext`](https://developer.mozilla.org/docs/Web/API/AudioContext) and [`OfflineAudioContext`](https://developer.mozilla.org/docs/Web/API/OfflineAudioContext) interfaces. | 5325–53The `BaseAudioContext` interface itself is not present, but many of the methods are available on the [`AudioContext`](https://developer.mozilla.org/docs/Web/API/AudioContext) and [`OfflineAudioContext`](https://developer.mozilla.org/docs/Web/API/OfflineAudioContext) interfaces. | No | 4315–43The `BaseAudioContext` interface itself is not present, but many of the methods are available on the [`AudioContext`](https://developer.mozilla.org/docs/Web/API/AudioContext) and [`OfflineAudioContext`](https://developer.mozilla.org/docs/Web/API/OfflineAudioContext) interfaces. | 14.16–14.1The `BaseAudioContext` interface itself is not present, but many of the methods are available on the [`AudioContext`](https://developer.mozilla.org/docs/Web/API/AudioContext) and [`OfflineAudioContext`](https://developer.mozilla.org/docs/Web/API/OfflineAudioContext) interfaces. | 56≤37–56The `BaseAudioContext` interface itself is not present, but many of the methods are available on the [`AudioContext`](https://developer.mozilla.org/docs/Web/API/AudioContext) and [`OfflineAudioContext`](https://developer.mozilla.org/docs/Web/API/OfflineAudioContext) interfaces. | 5618–56The `BaseAudioContext` interface itself is not present, but many of the methods are available on the [`AudioContext`](https://developer.mozilla.org/docs/Web/API/AudioContext) and [`OfflineAudioContext`](https://developer.mozilla.org/docs/Web/API/OfflineAudioContext) interfaces. | 5325–53The `BaseAudioContext` interface itself is not present, but many of the methods are available on the [`AudioContext`](https://developer.mozilla.org/docs/Web/API/AudioContext) and [`OfflineAudioContext`](https://developer.mozilla.org/docs/Web/API/OfflineAudioContext) interfaces. | 4314–43The `BaseAudioContext` interface itself is not present, but many of the methods are available on the [`AudioContext`](https://developer.mozilla.org/docs/Web/API/AudioContext) and [`OfflineAudioContext`](https://developer.mozilla.org/docs/Web/API/OfflineAudioContext) interfaces. | 14.56–14.5The `BaseAudioContext` interface itself is not present, but many of the methods are available on the [`AudioContext`](https://developer.mozilla.org/docs/Web/API/AudioContext) and [`OfflineAudioContext`](https://developer.mozilla.org/docs/Web/API/OfflineAudioContext) interfaces. | 6.01.0–6.0The `BaseAudioContext` interface itself is not present, but many of the methods are available on the [`AudioContext`](https://developer.mozilla.org/docs/Web/API/AudioContext) and [`OfflineAudioContext`](https://developer.mozilla.org/docs/Web/API/OfflineAudioContext) interfaces. |
| `audioWorklet` | 66 | 79 | 76 | No | 53 | 14.1 | 66 | 66 | 79 | 47 | 14.5 | 9.0 |
| `createAnalyser` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `createBiquadFilter` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `createBuffer` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `createBufferSource` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `createChannelMerger` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `createChannelSplitter` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `createConstantSource` | 56 | 79 | 52 | No | 43 | 14.1 | 56 | 56 | 52 | 43 | 14.5 | 6.0 |
| `createConvolver` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `createDelay` | 24 | 12 | 25 | No | 15 | 7 | ≤37 | 25 | 25 | 14 | 7 | 1.5 |
| `createDynamicsCompressor` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `createGain` | 24 | 12 | 25 | No | 15 | 7 | ≤37 | 25 | 25 | 14 | 7 | 1.5 |
| `createIIRFilter` | 49 | 14 | 50 | No | 36 | 14.1 | 49 | 49 | 50 | 36 | 14.5 | 5.0 |
| `createOscillator` | 20 | 12 | 25 | No | 15 | 6 | 4.4 | 25 | 25 | 14 | 6 | 1.5 |
| `createPanner` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `createPeriodicWave` | 30 | 12 | 25 | No | 17 | 8 | 4.4 | 30 | 25 | 18 | 8 | 2.0 |
| `createScriptProcessor` | 24 | 12 | 25 | No | 15 | 7 | ≤37 | 25 | 25 | 14 | 7 | 1.5 |
| `createStereoPanner` | 41 | 12 | 37 | No | 28 | 14.1 | 41 | 41 | 37 | 28 | 14.5 | 4.0 |
| `createWaveShaper` | 15 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `currentTime` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `decodeAudioData` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `destination` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `listener` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `sampleRate` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `state` | 41 | 14 | 40 | No | 28 | 9 | 41 | 41 | 40 | 28 | 9 | 4.0 |
| `statechange_event` | 41 | 14 | 40 | No | 28 | 9 | 41 | 41 | 40 | 28 | 9 | 4.0 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)
* [`AudioContext`](audiocontext)
* [`OfflineAudioContext`](offlineaudiocontext)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/BaseAudioContext>

BatteryManager
==============



The `BatteryManager` interface of the [Battery Status API](battery_status_api) provides information about the system's battery charge level. The [`navigator.getBattery()`](navigator/getbattery) method returns a promise that resolves with a `BatteryManager` interface.


 EventTarget BatteryManager

Instance properties
-------------------


 
[`BatteryManager.charging`](batterymanager/charging) Read only 
  A Boolean value indicating whether the battery is currently being charged.

  
[`BatteryManager.chargingTime`](batterymanager/chargingtime) Read only 
  A number representing the remaining time in seconds until the battery is fully charged, or 0 if the battery is already fully charged.

  
[`BatteryManager.dischargingTime`](batterymanager/dischargingtime) Read only 
  A number representing the remaining time in seconds until the battery is completely discharged and the system suspends.

  
[`BatteryManager.level`](batterymanager/level) Read only 
  A number representing the system's battery charge level scaled to a value between 0.0 and 1.0.

  
Instance methods
----------------


*Inherits methods from its parent interface:* [`EventTarget`](eventtarget).


Events
------


 [`chargingchange`](batterymanager/chargingchange_event)  Fired when the battery charging state (the [`charging`](batterymanager/charging) property) is updated.

  [`chargingtimechange`](batterymanager/chargingtimechange_event)  Fired when the battery charging time (the [`chargingTime`](batterymanager/chargingtime) property) is updated.

  [`dischargingtimechange`](batterymanager/dischargingtimechange_event)  Fired when the battery discharging time (the [`dischargingTime`](batterymanager/dischargingtime) property) is updated.

  [`levelchange`](batterymanager/levelchange_event)  Fired when the battery level (the [`level`](batterymanager/level) property) is updated.

  
Specifications
--------------




| Specification |
| --- |
| [Battery Status API # the-batterymanager-interface](https://w3c.github.io/battery/#the-batterymanager-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `BatteryManager` | 38 | 79 | 43–52 | No | 25 | No | 38 | 38 | 43–52 | 25 | No | 3.0 |
| `charging` | 38 | 79 | 43–52 | No | 25 | No | 38 | 38 | 43–52 | 25 | No | 3.0 |
| `chargingTime` | 38 | 79 | 43–52 | No | 25 | No | 4238–42Always equal to `0` or `Infinity`. | 4238–42Always equal to `0` or `Infinity`. | 43–52 | 2925–29Always equal to `0` or `Infinity`. | No | 4.03.0–4.0Always equal to `0` or `Infinity`. |
| `chargingchange_event` | 38 | 79 | 43–52 | No | 25 | No | 38 | 38 | 43–52 | 25 | No | 3.0 |
| `chargingtimechange_event` | 38 | 79 | 43–52 | No | 25 | No | 38 | 38 | 43–52 | 25 | No | 3.0 |
| `dischargingTime` | 38 | 79 | 43–52 | No | 25 | No | 4238–42Always equal to `Infinity`. | 4238–42Always equal to `Infinity`. | 43–52 | 2925–29Always equal to `Infinity`. | No | 4.03.0–4.0Always equal to `Infinity`. |
| `dischargingtimechange_event` | 38 | 79 | 43–52 | No | 25 | No | 38 | 38 | 43–52 | 25 | No | 3.0 |
| `level` | 38 | 79 | 43–52 | No | 25 | No | 38 | 38 | 43–52 | 25 | No | 3.0 |
| `levelchange_event` | 38 | 79 | 43–52 | No | 25 | No | 38 | 38 | 43–52 | 25 | No | 3.0 |
| `secure_context_required` | 103 | 103 | No | No | No | No | 103 | 103 | No | 71 | No | 20.0 |


See also
--------


* The [Battery Status API](battery_status_api)
* [`navigator.getBattery`](navigator/getbattery)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/BatteryManager>

BeforeInstallPromptEvent
========================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.


**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The `BeforeInstallPromptEvent` is the interface of the [`beforeinstallprompt`](window/beforeinstallprompt_event) event fired at the [`Window`](window) object before a user is prompted to "install" a website to a home screen on mobile.

 This interface inherits from the [`Event`](event) interface.


 Event BeforeInstallPromptEvent

Constructor
-----------


 
`BeforeInstallPromptEvent()` Non-standard   Experimental 
  Creates a new `BeforeInstallPromptEvent` object.

  
Instance properties
-------------------



*Inherits properties from its parent, [`Event`](event).*

  
`BeforeInstallPromptEvent.platforms` Read only  Non-standard   Experimental 
  Returns an array of string items containing the platforms on which the event was dispatched. This is provided for user agents that want to present a choice of versions to the user such as, for example, "web" or "play" which would allow the user to choose between a web version or an Android version.

  
`BeforeInstallPromptEvent.userChoice` Read only  Non-standard   Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to a string containing either "accepted" or "dismissed".

  

Instance methods
----------------


 
[`BeforeInstallPromptEvent.prompt()`](beforeinstallpromptevent/prompt)  Experimental 
  Allows a developer to show the install prompt at a time of their own choosing. This method returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).

  
Example
-------



```
window.addEventListener("beforeinstallprompt", (e) => {
  // log the platforms provided as options in an install prompt
  console.log(e.platforms); // e.g., ["web", "android", "windows"]
  e.userChoice.then((choiceResult) => {
    console.log(choiceResult.outcome); // either "accepted" or "dismissed"
  }, handleError);
});

```

Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `BeforeInstallPromptEvent` | 44 | 79 | No | No | 31 | No | 44 | 44 | No | 32 | No | 5.0 |
| `BeforeInstallPromptEvent` | 44 | 79 | No | No | 31 | No | 44 | 44 | No | 32 | No | 5.0 |
| `platforms` | 44 | 79 | No | No | 31 | No | 44 | 44 | No | 32 | No | 5.0 |
| `prompt` | 76The object returned by the promise returns a property called `outcome` instead of `userChoice`.44–76Resolved with an empty promise. | 79The object returned by the promise returns a property called `outcome` instead of `userChoice`. | No | No | 63The object returned by the promise returns a property called `outcome` instead of `userChoice`.31–63Resolved with an empty promise. | No | 76The object returned by the promise returns a property called `outcome` instead of `userChoice`.44–76Resolved with an empty promise. | 76The object returned by the promise returns a property called `outcome` instead of `userChoice`.44–76Resolved with an empty promise. | No | 54The object returned by the promise returns a property called `outcome` instead of `userChoice`.32–54Resolved with an empty promise. | No | 5.0 |
| `userChoice` | 44 | 79 | No | No | 31 | No | 44 | 44 | No | 32 | No | 5.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/BeforeInstallPromptEvent>

BeforeUnloadEvent
=================



`BeforeUnloadEvent` is an interface for the [`beforeunload`](window/beforeunload_event) event.

 The `beforeunload` event is fired when the window, the document and its resources are about to be unloaded.

 When a non-empty string is assigned to the `returnValue` Event property, a dialog box appears, asking the users for confirmation to leave the page (see example below). When no value is provided, the event is processed silently. Some implementations only show the dialog box if the frame or any embedded frame receives a user gesture or user interaction. See [Browser compatibility](#browser_compatibility) for more information.

  **Note:** For security reasons, only a generic string not under the control of the webpage is shown instead of the returned string.

 
 Event BeforeUnloadEvent 

|  |  |
| --- | --- |
| Bubbles | No |
| Cancelable | Yes |
| Target objects | defaultView |
| Interface | [`Event`](event) |



Examples
--------




```
window.addEventListener("beforeunload", (event) => {
  event.returnValue = "\\o/";
});

// is equivalent to
window.addEventListener("beforeunload", (event) => {
  event.preventDefault();
});

```
 WebKit-derived browsers don't follow the spec for the dialog box. An almost-cross-browser working example would be close to the below example.

 
```
window.addEventListener("beforeunload", (e) => {
  const confirmationMessage = "\\o/";

  // Gecko + IE
  (e || window.event).returnValue = confirmationMessage;

  // Safari, Chrome, and other WebKit-derived browsers
  return confirmationMessage;
});

```


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-beforeunloadevent-interface](https://html.spec.whatwg.org/multipage/nav-history-apis.html#the-beforeunloadevent-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `BeforeUnloadEvent` | 30 | 79 | 1.5 | 4 | 17 | 7 | ≤37 | 30 | 4 | 18 | 7 | 3.0 |
| `returnValue` | 30 | 79 | 1.5 | 9 | 17 | 7 | ≤37 | 30 | 4 | 18 | 7 | 3.0 |
| `user_interaction` | 60 | 79 | 44 | No | 47 | 11 | 60 | 60 | 44 | 44 | 11 | 8.0 |


See also
--------


* [`DOMContentLoaded`](document/domcontentloaded_event)
* [`readystatechange`](document/readystatechange_event)
* [`load`](window/load_event)
* [`beforeunload`](window/beforeunload_event)
* [`unload`](window/unload_event)
* [Unloading Documents — Prompt to unload a document](https://html.spec.whatwg.org/#prompt-to-unload-a-document)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/BeforeUnloadEvent>

Blob
====



The `Blob` object represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a [`ReadableStream`](readablestream) so its methods can be used for processing the data.

 Blobs can represent data that isn't necessarily in a JavaScript-native format. The [`File`](file) interface is based on `Blob`, inheriting blob functionality and expanding it to support files on the user's system.



Using blobs
-----------



To construct a `Blob` from other non-blob objects and data, use the [`Blob()`](blob/blob) constructor. To create a blob that contains a subset of another blob's data, use the [`slice()`](blob/slice) method. To obtain a `Blob` object for a file on the user's file system, see the [`File`](file) documentation.

 The APIs accepting `Blob` objects are also listed in the [`File`](file) documentation.



Constructor
-----------


 [`Blob()`](blob/blob)  Returns a newly created `Blob` object which contains a concatenation of all of the data in the array passed into the constructor.

  
Instance properties
-------------------


 
[`Blob.prototype.size`](blob/size) Read only 
  The size, in bytes, of the data contained in the `Blob` object.

  
[`Blob.prototype.type`](blob/type) Read only 
  A string indicating the MIME type of the data contained in the `Blob`. If the type is unknown, this string is empty.

  
Instance methods
----------------


 [`Blob.prototype.arrayBuffer()`](blob/arraybuffer)  Returns a promise that resolves with an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing the entire contents of the `Blob` as binary data.

  [`Blob.prototype.slice()`](blob/slice)  Returns a new `Blob` object containing the data in the specified range of bytes of the blob on which it's called.

  [`Blob.prototype.stream()`](blob/stream)  Returns a [`ReadableStream`](readablestream) that can be used to read the contents of the `Blob`.

  [`Blob.prototype.text()`](blob/text)  Returns a promise that resolves with a string containing the entire contents of the `Blob` interpreted as UTF-8 text.

  
Examples
--------


### Creating a blob



The [`Blob()`](blob/blob) constructor can create blobs from other objects. For example, to construct a blob from a JSON string:

 
```
const obj = { hello: "world" };
const blob = new Blob([JSON.stringify(obj, null, 2)], {
  type: "application/json",
});

```


### Creating a URL representing the contents of a typed array



The following code creates a JavaScript [typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays) and creates a new `Blob` containing the typed array's data. It then calls [`URL.createObjectURL()`](url/createobjecturl) to convert the blob into a [URL](https://developer.mozilla.org/en-US/docs/Glossary/URL).

 #### HTML

 
```
<p>
  This example creates a typed array containing the ASCII codes for the space
  character through the letter Z, then converts it to an object URL. A link to
  open that object URL is created. Click the link to see the decoded object URL.
</p>

```
 #### JavaScript

 The main piece of this code for example purposes is the `typedArrayToURL()` function, which creates a `Blob` from the given typed array and returns an object URL for it. Having converted the data into an object URL, it can be used in a number of ways, including as the value of the [`<img>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img) element's [`src`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#src) attribute (assuming the data contains an image, of course).

 
```
function showViewLiveResultButton() {
  if (window.self !== window.top) {
    // Ensure that if our document is in a frame, we get the user
    // to first open it in its own tab or window. Otherwise, this
    // example won't work.
    const p = document.querySelector("p");
    p.textContent = "";
    const button = document.createElement("button");
    button.textContent = "View live result of the example code above";
    p.append(button);
    button.addEventListener("click", () => window.open(location.href));
    return true;
  }
  return false;
}

if (!showViewLiveResultButton()) {
  function typedArrayToURL(typedArray, mimeType) {
    return URL.createObjectURL(
      new Blob([typedArray.buffer], { type: mimeType })
    );
  }
  const bytes = new Uint8Array(59);

  for (let i = 0; i < 59; i++) {
    bytes[i] = 32 + i;
  }

  const url = typedArrayToURL(bytes, "text/plain");

  const link = document.createElement("a");
  link.href = url;
  link.innerText = "Open the array URL";

  document.body.appendChild(link);
}

```
 #### Result




### Extracting data from a blob



One way to read content from a `Blob` is to use a [`FileReader`](filereader). The following code reads the content of a `Blob` as a typed array:

 
```
const reader = new FileReader();
reader.addEventListener("loadend", () => {
  // reader.result contains the contents of blob as a typed array
});
reader.readAsArrayBuffer(blob);

```
 Another way to read content from a `Blob` is to use a [`Response`](response). The following code reads the content of a `Blob` as text:

 
```
const text = await new Response(blob).text();

```
 Or by using [`Blob.prototype.text()`](blob/text):

 
```
const text = await blob.text();

```
 By using other methods of `FileReader`, it is possible to read the contents of a Blob as a string or a data URL.



Specifications
--------------




| Specification |
| --- |
| [File API # blob-section](https://w3c.github.io/FileAPI/#blob-section) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Blob` | 20 | 12 | 13Before Firefox 16, the second parameter, when set to `null` or `undefined`, leads to an error instead of being handled as an empty dictionary. | 10IE10 throws `InvalidStateError` with a `TypedArray` argument. Consider using `MSBuilder` as an alternative. | 12 | 6 | 4.4 | 25 | 14Before Firefox 16, the second parameter, when set to `null` or `undefined`, leads to an error instead of being handled as an empty dictionary. | 12 | 6 | 1.5 |
| `Blob` | 5 | 12 | 4 | 10 | 11 | 6 | 4.4 | 18 | 4 | 11 | 6 | 1.0 |
| `arrayBuffer` | 76 | 79 | 69 | No | 63 | 14 | 76 | 76 | 79 | 54 | 14 | 12.0 |
| `size` | 5 | 12 | 4 | 10 | 11 | 6 | 4.4 | 18 | 4 | 11 | 6 | 1.0 |
| `slice` | 215–25 | 12 | 13Before Firefox 12, there was a bug that affected the behavior of `Blob.slice()`; it did not work for `start` and `end` positions outside the range of signed 64-bit values; it has now been fixed to support unsigned 64-bit values.5–13 | 10 | 12 | 76–7 | 4.4 | 2518–25 | 14Before Firefox 12, there was a bug that affected the behavior of `Blob.slice()`; it did not work for `start` and `end` positions outside the range of signed 64-bit values; it has now been fixed to support unsigned 64-bit values.5–14 | 12 | 76–7 | 1.51.0–1.5 |
| `stream` | 76 | 79 | 69 | No | 63 | 14.1 | 76 | 76 | 79 | 54 | 14.5 | 12.0 |
| `text` | 76 | 79 | 69 | No | 63 | 14 | 76 | 76 | 79 | 54 | 14 | 12.0 |
| `type` | 5 | 12 | 4 | 10 | 11 | 6 | 4.4 | 18 | 4 | 11 | 6 | 1.0 |


See also
--------


* [`FileReader`](filereader)
* [`File`](file)
* [`URL.createObjectURL`](url/createobjecturl)
* [Using files from web applications](file_api/using_files_from_web_applications)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Blob>

Bluetooth
=========



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

  The `Bluetooth` interface of the [Web Bluetooth API](web_bluetooth_api) returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) to a [`BluetoothDevice`](bluetoothdevice) object with the specified options. 


 EventTarget Bluetooth

Instance properties
-------------------


*Inherits properties from its parent [`EventTarget`](eventtarget).*


Instance methods
----------------


 
[`Bluetooth.getAvailability()`](bluetooth/getavailability)  Experimental 
   Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolved to a boolean value indicating whether the user-agent has the ability to support Bluetooth. Some user-agents let the user configure an option that affects what is returned by this value. If this option is set, that is the value returned by this method. 

  
[`Bluetooth.getDevices()`](bluetooth/getdevices)  Experimental 
   Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolved to an array of [`BluetoothDevice`](bluetoothdevice)s which the origin already obtained permission for via a call to [`Bluetooth.requestDevice()`](bluetooth/requestdevice). 

  
[`Bluetooth.requestDevice()`](bluetooth/requestdevice)  Experimental 
   Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) to a [`BluetoothDevice`](bluetoothdevice) object with the specified options. 

  
Events
------


 
[`availabilitychanged`](bluetooth/availabilitychanged_event)  Experimental 
  An event that fires when Bluetooth capabilities have changed in availability.

  
Specifications
--------------




| Specification |
| --- |
| [Web Bluetooth # bluetooth](https://webbluetoothcg.github.io/web-bluetooth/#bluetooth) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Bluetooth` | 56Before Chrome 70, this feature was only supported in macOS. In Chrome 70, support was added for Windows 10. Linux support is not enabled by default.56In Linux and versions of Windows earlier than 10, this flag must be enabled. | 79Supported by default only on macOS and Windows 10. Linux support is not enabled by default.79In Linux and versions of Windows earlier than 10, this flag must be enabled. | No | No | 43Before Opera 57, this feature was only supported in macOS. In Opera 57, support was added for Windows 10. Linux support is not enabled by default.43In Linux and versions of Windows earlier than 10, this flag must be enabled. | No | NoSee [bug 1100993](https://crbug.com/1100993). | 56 | No | 43 | No | 6.0 |
| `availabilitychanged_event` | 56 | 79 | No | No | 43 | No | No | No | No | No | No | No |
| `getAvailability` | 78 | 79 | No | No | 65 | No | No | 78 | No | 56 | No | 12.0 |
| `getDevices` | 85 | 85 | No | No | 71 | No | No | 85 | No | No | No | No |
| `requestDevice` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Bluetooth>

BluetoothRemoteGATTDescriptor
=============================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

  The `BluetoothRemoteGATTDescriptor` interface of the [Web Bluetooth API](web_bluetooth_api) provides a GATT Descriptor, which provides further information about a characteristic's value. 



Instance properties
-------------------


 
[`BluetoothRemoteGATTDescriptor.characteristic`](bluetoothremotegattdescriptor/characteristic) Read only   Experimental 
   Returns the [`BluetoothRemoteGATTCharacteristic`](bluetoothremotegattcharacteristic) this descriptor belongs to. 

  
[`BluetoothRemoteGATTDescriptor.uuid`](bluetoothremotegattdescriptor/uuid) Read only   Experimental 
   Returns the UUID of the characteristic descriptor, for example '`00002902-0000-1000-8000-00805f9b34fb`' for theClient Characteristic Configuration descriptor. 

  
[`BluetoothRemoteGATTDescriptor.value`](bluetoothremotegattdescriptor/value) Read only   Experimental 
   Returns the currently cached descriptor value. This value gets updated when the value of the descriptor is read. 

  
Instance methods
----------------


 
[`BluetoothRemoteGATTDescriptor.readValue()`](bluetoothremotegattdescriptor/readvalue)  Experimental 
   Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) holding a duplicate of the `value` property if it is available and supported. Otherwise it throws an error. 

  
[`BluetoothRemoteGATTDescriptor.writeValue()`](bluetoothremotegattdescriptor/writevalue)  Experimental 
   Sets the value property to the bytes contained in an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). 

  
Specifications
--------------




| Specification |
| --- |
| [Web Bluetooth # bluetoothgattdescriptor-interface](https://webbluetoothcg.github.io/web-bluetooth/#bluetoothgattdescriptor-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `BluetoothRemoteGATTDescriptor` | 57Before Chrome 70, this feature was only supported in macOS. In Chrome 70, support was added for Windows 10. Linux support is not enabled by default.57In Linux and versions of Windows earlier than 10, this flag must be enabled. | 79Supported by default only on macOS and Windows 10. Linux support is not enabled by default.79In Linux and versions of Windows earlier than 10, this flag must be enabled. | No | No | 44Before Opera 57, this feature was only supported in macOS. In Opera 57, support was added for Windows 10. Linux support is not enabled by default.44In Linux and versions of Windows earlier than 10, this flag must be enabled. | No | NoSee [bug 1100993](https://crbug.com/1100993). | 57 | No | 44 | No | 7.0 |
| `characteristic` | 57 | 79 | No | No | 44 | No | No | 57 | No | 44 | No | 7.0 |
| `readValue` | 57 | 79 | No | No | 44 | No | No | 57 | No | 44 | No | 7.0 |
| `uuid` | 57 | 79 | No | No | 44 | No | No | 57 | No | 44 | No | 7.0 |
| `value` | 57 | 79 | No | No | 44 | No | No | 57 | No | 44 | No | 7.0 |
| `writeValue` | 57 | 79 | No | No | 44 | No | No | 57 | No | 44 | No | 7.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/BluetoothRemoteGATTDescriptor>

BluetoothUUID
=============


 The `BluetoothUUID` interface of the [`Web Bluetooth API`](web_bluetooth_api) provides a way to look up Universally Unique Identifier (UUID) values by name in the [registry](https://www.bluetooth.com/specifications/assigned-numbers/) maintained by the Bluetooth SIG. 


Description
-----------



 A UUID string is a 128-bit UUID, for example `00001818-0000-1000-8000-00805f9b34fb`. The Bluetooth registry contains lists of descriptors, services, and characteristics identified by these UUIDs in addition to a 16- or 32- bit alias, and a name. 

 The `BluetoothUUID` interface provides methods to retrieve these 128-bit UUIDs.



Instance properties
-------------------


None.


### Event handlers


None.


Instance methods
----------------


 
[`BluetoothUUID.canonicalUUID()`](bluetoothuuid/canonicaluuid)  Experimental 
  Returns the 128-bit UUID when passed the 16- or 32-bit UUID alias.

  
[`BluetoothUUID.getCharacteristic()`](bluetoothuuid/getcharacteristic)  Experimental 
  Returns the 128-bit UUID representing a registered characteristic when passed a name or the 16- or 32-bit UUID alias.

  
[`BluetoothUUID.getDescriptor()`](bluetoothuuid/getdescriptor)  Experimental 
  Returns a UUID representing a registered descriptor when passed a name or the 16- or 32-bit UUID alias.

  
[`BluetoothUUID.getService()`](bluetoothuuid/getservice)  Experimental 
  Returns a UUID representing a registered service when passed a name or the 16- or 32-bit UUID alias.

  
Examples
--------



In the following example the UUID representing the service named `device_information` is returned and printed to the console.

 
```
let result = BluetoothUUID.getService("device\_information");
console.log(result); // "0000180a-0000-1000-8000-00805f9b34fb"

```


Specifications
--------------




| Specification |
| --- |
| [Web Bluetooth # bluetoothuuid](https://webbluetoothcg.github.io/web-bluetooth/#bluetoothuuid) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `BluetoothUUID` | 56Before Chrome 70, this feature was only supported in macOS. In Chrome 70, support was added for Windows 10. Linux support is not enabled by default.56In Linux and versions of Windows earlier than 10, this flag must be enabled. | 79Supported by default only on macOS and Windows 10. Linux support is not enabled by default.79In Linux and versions of Windows earlier than 10, this flag must be enabled. | No | No | 43Before Opera 57, this feature was only supported in macOS. In Opera 57, support was added for Windows 10. Linux support is not enabled by default.43In Linux and versions of Windows earlier than 10, this flag must be enabled. | No | NoSee [bug 1100993](https://crbug.com/1100993). | 56 | No | 43 | No | 6.0 |
| `canonicalUUID` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `getCharacteristic` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `getDescriptor` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `getService` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/BluetoothUUID>

BroadcastChannel
================



The `BroadcastChannel` interface represents a named channel that any [browsing context](https://developer.mozilla.org/en-US/docs/Glossary/Browsing_context) of a given [origin](https://developer.mozilla.org/en-US/docs/Glossary/Origin) can subscribe to. It allows communication between different documents (in different windows, tabs, frames or iframes) of the same origin. Messages are broadcasted via a [`message`](broadcastchannel/message_event) event fired at all `BroadcastChannel` objects listening to the channel, except the object that sent the message.


 **Note:** This feature is available in [Web Workers](web_workers_api)

   EventTarget BroadcastChannel

Constructor
-----------


 [`BroadcastChannel()`](broadcastchannel/broadcastchannel)  Creates an object linking to the named channel.

  
Instance properties
-------------------



*This interface also inherits properties from its parent, [`EventTarget`](eventtarget).*

  
[`BroadcastChannel.name`](broadcastchannel/name) Read only 
  Returns a string, the name of the channel.

  

Instance methods
----------------



*This interface also inherits methods from its parent, [`EventTarget`](eventtarget).*

  [`BroadcastChannel.postMessage()`](broadcastchannel/postmessage)  Sends the message, of any type of object, to each `BroadcastChannel` object listening to the same channel.

  [`BroadcastChannel.close()`](broadcastchannel/close)  Closes the channel object, indicating it won't get any new messages, and allowing it to be, eventually, garbage collected.

  

Events
------


 [`message`](broadcastchannel/message_event)   Fired when a message arrives on the channel. Also available via the `onmessage` property. 

  [`messageerror`](broadcastchannel/messageerror_event)   Fired when a message arrives that can't be deserialized. Also available via the `onmessageerror` property. 

  
Specifications
--------------




| Specification |
| --- |
| [HTML Standard # broadcasting-to-other-browsing-contexts](https://html.spec.whatwg.org/multipage/web-messaging.html#broadcasting-to-other-browsing-contexts) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `BroadcastChannel` | 54 | 79 | 38 | No | 41 | 15.4 | 54 | 54 | 38 | 41 | 15.4 | 6.0 |
| `BroadcastChannel` | 54 | 79 | 38 | No | 41 | 15.4 | 54 | 54 | 38 | 41 | 15.4 | 6.0 |
| `close` | 54 | 79 | 38 | No | 41 | 15.4 | 54 | 54 | 38 | 41 | 15.4 | 6.0 |
| `message_event` | 54 | 79 | 38 | No | 41 | 15.4 | 54 | 54 | 38 | 41 | 15.4 | 6.0 |
| `messageerror_event` | 60 | 79 | 57 | No | 47 | 15.4 | 60 | 60 | 57 | 47 | 15.4 | 8.0 |
| `name` | 54 | 79 | 38 | No | 41 | 15.4 | 54 | 54 | 38 | 41 | 15.4 | 6.0 |
| `postMessage` | 54 | 79 | 38 | No | 41 | 15.4 | 54 | 54 | 38 | 41 | 15.4 | 6.0 |


See also
--------


* Another, more heavyweight, way of communicating between browser contexts: [`ServiceWorker`](serviceworker).
* [Broadcast Channel API overview](broadcast_channel_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel>

ByteLengthQueuingStrategy
=========================


The `ByteLengthQueuingStrategy` interface of the [Streams API](streams_api) provides a built-in byte length queuing strategy that can be used when constructing streams.


Constructor
-----------


 [`ByteLengthQueuingStrategy()`](bytelengthqueuingstrategy/bytelengthqueuingstrategy)  Creates a new `ByteLengthQueuingStrategy` object instance.

  
Instance properties
-------------------


 
[`ByteLengthQueuingStrategy.highWaterMark`](bytelengthqueuingstrategy/highwatermark) Read only 
  The total number of bytes that can be contained in the internal queue before [backpressure](streams_api/concepts#backpressure) is applied.

  
Instance methods
----------------


 [`ByteLengthQueuingStrategy.size()`](bytelengthqueuingstrategy/size)  Returns the given chunk's `byteLength` property.

  
Examples
--------



```
const queueingStrategy = new ByteLengthQueuingStrategy({ highWaterMark: 1024 });

const readableStream = new ReadableStream(
  {
    start(controller) {
      // …
    },
    pull(controller) {
      // …
    },
    cancel(err) {
      console.log("stream error:", err);
    },
  },
  queueingStrategy
);

const size = queueingStrategy.size(chunk);

```

Specifications
--------------




| Specification |
| --- |
| [Streams Standard # blqs-class](https://streams.spec.whatwg.org/#blqs-class) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ByteLengthQueuingStrategy` | 52 | 16 | 65 | No | 39 | 10.1 | 52 | 52 | 65 | 41 | 10.3 | 6.0 |
| `ByteLengthQueuingStrategy` | 52 | 16 | 65 | No | 39 | 10.1 | 52 | 52 | 65 | 41 | 10.3 | 6.0 |
| `highWaterMark` | 52 | 16 | 65 | No | 39 | 10.1 | 52 | 52 | 65 | 41 | 10.3 | 6.0 |
| `size` | 52 | 16 | 65 | No | 39 | 10.1 | 52 | 52 | 65 | 41 | 10.3 | 6.0 |


See also
--------


* [`ByteLengthQueuingStrategy()`](bytelengthqueuingstrategy/bytelengthqueuingstrategy) constructor


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ByteLengthQueuingStrategy>

Cache
=====



The `Cache` interface provides a persistent storage mechanism for [`Request`](request) / [`Response`](response) object pairs that are cached in long lived memory. How long a `Cache` object lives is browser dependent, but a single origin's scripts can typically rely on the presence of a previously populated `Cache` object. Note that the `Cache` interface is exposed to windowed scopes as well as workers. You don't have to use it in conjunction with service workers, even though it is defined in the service worker spec.

 An origin can have multiple, named `Cache` objects. You are responsible for implementing how your script (e.g. in a [`ServiceWorker`](serviceworker)) handles `Cache` updates. Items in a `Cache` do not get updated unless explicitly requested; they don't expire unless deleted. Use [`CacheStorage.open()`](cachestorage/open) to open a specific named `Cache` object and then call any of the `Cache` methods to maintain the `Cache`.

 You are also responsible for periodically purging cache entries. Each browser has a hard limit on the amount of cache storage that a given origin can use. `Cache` quota usage estimates are available via the [`StorageManager.estimate()`](storagemanager/estimate) method. The browser does its best to manage disk space, but it may delete the `Cache` storage for an origin. The browser will generally delete all of the data for an origin or none of the data for an origin. Make sure to version caches by name and use the caches only from the version of the script that they can safely operate on. See [Deleting old caches](service_worker_api/using_service_workers#deleting_old_caches) for more information.

  **Note:** The key matching algorithm depends on the [VARY header](https://www.fastly.com/blog/best-practices-using-vary-header) in the value. So matching a new key requires looking at both key and value for entries in the `Cache` object.

   **Note:** The caching API doesn't honor HTTP caching headers.

 
 **Note:** This feature is available in [Web Workers](web_workers_api)

  **Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).



Instance methods
----------------


 [`Cache.match(request, options)`](cache/match)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to the response associated with the first matching request in the `Cache` object.

  [`Cache.matchAll(request, options)`](cache/matchall)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to an array of all matching responses in the `Cache` object.

  [`Cache.add(request)`](cache/add)  Takes a URL, retrieves it and adds the resulting response object to the given cache. This is functionally equivalent to calling `fetch()`, then using `put()` to add the results to the cache.

  [`Cache.addAll(requests)`](cache/addall)  Takes an array of URLs, retrieves them, and adds the resulting response objects to the given cache.

  [`Cache.put(request, response)`](cache/put)  Takes both a request and its response and adds it to the given cache.

  [`Cache.delete(request, options)`](cache/delete)  Finds the `Cache` entry whose key is the request, returning a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to `true` if a matching `Cache` entry is found and deleted. If no `Cache` entry is found, the promise resolves to `false`.

  [`Cache.keys(request, options)`](cache/keys)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to an array of `Cache` keys.

  
Examples
--------



This code snippet is from the [service worker selective caching sample](https://github.com/GoogleChrome/samples/blob/gh-pages/service-worker/selective-caching/service-worker.js). (see [selective caching live](https://googlechrome.github.io/samples/service-worker/selective-caching/)) The code uses [`CacheStorage.open()`](cachestorage/open) to open any `Cache` objects with a `Content-Type` header that starts with `font/`.

 The code then uses [`Cache.match()`](cache/match) to see if there's already a matching font in the cache, and if so, returns it. If there isn't a matching font, the code fetches the font from the network and uses [`Cache.put()`](cache/put) to cache the fetched resource.

 The code handles exceptions thrown from the [`fetch()`](fetch) operation. Note that an HTTP error response (e.g., 404) will not trigger an exception. It will return a normal response object that has the appropriate error code.

 The code snippet also shows a best practice for versioning caches used by the service worker. Though there's only one cache in this example, the same approach can be used for multiple caches. It maps a shorthand identifier for a cache to a specific, versioned cache name. The code also deletes all caches that aren't named in `CURRENT_CACHES`.

 In the code example, `caches` is a property of the [`ServiceWorkerGlobalScope`](serviceworkerglobalscope). It holds the `CacheStorage` object, by which it can access the [`CacheStorage`](cachestorage) interface.

  **Note:** In Chrome, visit `chrome://inspect/#service-workers` and click on the "inspect" link below the registered service worker to view logging statements for the various actions the [`service-worker.js`](https://github.com/GoogleChrome/samples/blob/gh-pages/service-worker/selective-caching/service-worker.js) script is performing.

  
```
const CACHE\_VERSION = 1;
const CURRENT\_CACHES = {
  font: `font-cache-v${CACHE\_VERSION}`,
};

self.addEventListener("activate", (event) => {
  // Delete all caches that aren't named in CURRENT\_CACHES.
  // While there is only one cache in this example, the same logic
  // will handle the case where there are multiple versioned caches.
  const expectedCacheNamesSet = new Set(Object.values(CURRENT\_CACHES));
  event.waitUntil(
    caches.keys().then((cacheNames) =>
      Promise.all(
        cacheNames.map((cacheName) => {
          if (!expectedCacheNamesSet.has(cacheName)) {
            // If this cache name isn't present in the set of
            // "expected" cache names, then delete it.
            console.log("Deleting out of date cache:", cacheName);
            return caches.delete(cacheName);
          }
        })
      )
    )
  );
});

self.addEventListener("fetch", (event) => {
  console.log("Handling fetch event for", event.request.url);

  event.respondWith(
    caches.open(CURRENT\_CACHES.font).then((cache) => {
      return cache
        .match(event.request)
        .then((response) => {
          if (response) {
            // If there is an entry in the cache for event.request,
            // then response will be defined and we can just return it.
            // Note that in this example, only font resources are cached.
            console.log(" Found response in cache:", response);

            return response;
          }

          // Otherwise, if there is no entry in the cache for event.request,
          // response will be undefined, and we need to fetch() the resource.
          console.log(
            " No response for %s found in cache. About to fetch " +
              "from network…",
            event.request.url
          );

          // We call .clone() on the request since we might use it
          // in a call to cache.put() later on.
          // Both fetch() and cache.put() "consume" the request,
          // so we need to make a copy.
          // (see https://developer.mozilla.org/en-US/docs/Web/API/Request/clone)
          return fetch(event.request.clone()).then((response) => {
            console.log(
              " Response for %s from network is: %O",
              event.request.url,
              response
            );

            if (
              response.status < 400 &&
              response.headers.has("content-type") &&
              response.headers.get("content-type").match(/^font\//i)
            ) {
              // This avoids caching responses that we know are errors
              // (i.e. HTTP status code of 4xx or 5xx).
              // We also only want to cache responses that correspond
              // to fonts, i.e. have a Content-Type response header that
              // starts with "font/".
              // Note that for opaque filtered responses
              // https://fetch.spec.whatwg.org/#concept-filtered-response-opaque
              // we can't access to the response headers, so this check will
              // always fail and the font won't be cached.
              // All of the Google Web Fonts are served from a domain that
              // supports CORS, so that isn't an issue here.
              // It is something to keep in mind if you're attempting
              // to cache other resources from a cross-origin
              // domain that doesn't support CORS, though!
              console.log(" Caching the response to", event.request.url);
              // We call .clone() on the response to save a copy of it
              // to the cache. By doing so, we get to keep the original
              // response object which we will return back to the controlled
              // page.
              // https://developer.mozilla.org/en-US/docs/Web/API/Request/clone
              cache.put(event.request, response.clone());
            } else {
              console.log(" Not caching the response to", event.request.url);
            }

            // Return the original response object, which will be used to
            // fulfill the resource request.
            return response;
          });
        })
        .catch((error) => {
          // This catch() will handle exceptions that arise from the match()
          // or fetch() operations.
          // Note that a HTTP error response (e.g. 404) will NOT trigger
          // an exception.
          // It will return a normal response object that has the appropriate
          // error code set.
          console.error(" Error in fetch handler:", error);

          throw error;
        });
    })
  );
});

```


### Cookies and Cache objects


The [Fetch API](fetch_api) requires [`Set-Cookie`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie) headers to be stripped before returning a [`Response`](response) object from [`fetch()`](fetch). So a `Response` stored in a `Cache` won't contain `Set-Cookie` headers, and therefore won't cause any cookies to be stored.


Specifications
--------------




| Specification |
| --- |
| [Service Workers # cache-interface](https://w3c.github.io/ServiceWorker/#cache-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Cache` | 40Before version 43, only service workers are supported. From version 43, all worker types and the main thread are supported. | 16 | 41 | No | 27Before version 30, only service workers are supported. From version 30, all worker types and the main thread are supported. | 11.1 | 40Before version 43, only service workers are supported. From version 43, all worker types and the main thread are supported. | 40Before version 43, only service workers are supported. From version 43, all worker types and the main thread are supported. | 41 | 27Before version 30, only service workers are supported. From version 30, all worker types and the main thread are supported. | 11.3 | 4.0 |
| `add` | 44Requires HTTPS from version 46. | 16 | 41 | No | 31Requires HTTPS from version 33. | 11.1 | 44Requires HTTPS from version 46. | 44Requires HTTPS from version 46. | 41 | 32Requires HTTPS from version 33. | 11.3 | 4.0Requires HTTPS from Samsung Internet 5.0. |
| `addAll` | 46Requires HTTPS. | 16 | 41 | No | 33Requires HTTPS. | 11.1 | 46Requires HTTPS. | 46Requires HTTPS. | 41 | 33Requires HTTPS. | 11.3 | 5.0Requires HTTPS. |
| `delete` | 43 | 16 | 41 | No | 30 | 11.1 | 43 | 43 | 41 | 30 | 11.3 | 4.0 |
| `keys` | 43 | 16 | 41 | No | 30 | 11.1 | 43 | 43 | 41 | 30 | 11.3 | 4.0 |
| `match` | 43 | 16 | 41 | No | 30 | 11.1 | 43 | 43 | 41 | 30 | 11.3 | 4.0 |
| `matchAll` | 47 | 16 | 41 | No | 34Requires HTTPS. | 11.1 | 47 | 47 | 41 | 34 | 11.3 | 5.0 |
| `put` | 43Requires HTTPS from version 46. | 16 | 41 | No | 30Requires HTTPS from version 33. | 11.1 | 43Requires HTTPS from version 46. | 43Requires HTTPS from version 46. | 41 | 30Requires HTTPS from version 33. | 11.3 | 4.0Requires HTTPS from Samsung Internet 5.0. |
| `worker_support` | 40Before version 43, only service workers are supported. From version 43, all worker types and the main thread are supported. | 16 | 44 | No | 27Before version 30, only service workers are supported. From version 30, all worker types and the main thread are supported. | 11.1 | 40Before version 43, only service workers are supported. From version 43, all worker types and the main thread are supported. | 40Before version 43, only service workers are supported. From version 43, all worker types and the main thread are supported. | 44 | 27Before version 30, only service workers are supported. From version 30, all worker types and the main thread are supported. | 11.3 | 4.0 |


See also
--------


* [Using Service Workers](service_worker_api/using_service_workers)
* [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker)
* [Is ServiceWorker ready?](https://jakearchibald.github.io/isserviceworkerready/)
* [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
* [Using web workers](web_workers_api/using_web_workers)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Cache>

CanMakePaymentEvent
===================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `CanMakePaymentEvent` interface of the [Payment Handler API](payment_handler_api) is the event object for the [`canmakepayment`](serviceworkerglobalscope/canmakepayment_event) event, fired on a payment app's service worker to check whether it is ready to handle a payment. Specifically, it is fired when the merchant website calls [`new PaymentRequest()`](paymentrequest/paymentrequest).


 Event ExtendableEvent CanMakePaymentEvent

Constructor
-----------


 
[`CanMakePaymentEvent()`](canmakepaymentevent/canmakepaymentevent)  Experimental 
  Creates a new `CanMakePaymentEvent` object instance.

  
Instance methods
----------------


 
[`respondWith()`](canmakepaymentevent/respondwith)  Experimental 
  Enables the service worker to respond appropriately to signal whether it is ready to handle payments.

  
Examples
--------



```
self.addEventListener("canmakepayment", (e) => {
  e.respondWith(
    new Promise((resolve, reject) => {
      someAppSpecificLogic()
        .then((result) => {
          resolve(result);
        })
        .catch((error) => {
          reject(error);
        });
    })
  );
});

```

Specifications
--------------




| Specification |
| --- |
| [Payment Handler API # the-canmakepaymentevent](https://w3c.github.io/payment-handler/#the-canmakepaymentevent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CanMakePaymentEvent` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |
| `CanMakePaymentEvent` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |
| `methodData` | 70–111 | 79–111 | No | No | 57–97 | No | No | 70–111 | No | 49 | No | 10.0 |
| `modifiers` | 70–111 | 79–111 | No | No | 57–97 | No | No | 70–111 | No | 49 | No | 10.0 |
| `paymentRequestOrigin` | 70–111 | 79–111 | No | No | 57–97 | No | No | 70–111 | No | 49 | No | 10.0 |
| `respondWith` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |
| `topOrigin` | 70–111 | 79–111 | No | No | 57–97 | No | No | 70–111 | No | 49 | No | 10.0 |


See also
--------


* [Payment Handler API](payment_handler_api)
* [Web-based payment apps overview](https://web.dev/web-based-payment-apps-overview/)
* [Setting up a payment method](https://web.dev/setting-up-a-payment-method/)
* [Life of a payment transaction](https://web.dev/life-of-a-payment-transaction/)
* [Using the Payment Request API](payment_request_api/using_the_payment_request_api)
* [Payment processing concepts](payment_request_api/concepts)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CanMakePaymentEvent>

BluetoothRemoteGATTServer
=========================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

  The `BluetoothRemoteGATTServer` interface of the [Web Bluetooth API](web_bluetooth_api) represents a GATT Server on a remote device. 



Instance properties
-------------------


 
[`BluetoothRemoteGATTServer.connected`](bluetoothremotegattserver/connected) Read only   Experimental 
   A boolean value that returns true while this script execution environment is connected to `this.device`. It can be false while the user agent is physically connected. 

  
[`BluetoothRemoteGATTServer.device`](bluetoothremotegattserver/device) Read only   Experimental 
  A reference to the [`BluetoothDevice`](bluetoothdevice) running the server.

  
Instance methods
----------------


 
[`BluetoothRemoteGATTServer.connect()`](bluetoothremotegattserver/connect)  Experimental 
  Causes the script execution environment to connect to `this.device`.

  
[`BluetoothRemoteGATTServer.disconnect()`](bluetoothremotegattserver/disconnect)  Experimental 
  Causes the script execution environment to disconnect from `this.device`.

  
[`BluetoothRemoteGATTServer.getPrimaryService()`](bluetoothremotegattserver/getprimaryservice)  Experimental 
   Returns a promise to the primary [`BluetoothRemoteGATTService`](bluetoothremotegattservice) offered by the Bluetooth device for a specified `BluetoothServiceUUID`. 

  
[`BluetoothRemoteGATTServer.getPrimaryServices()`](bluetoothremotegattserver/getprimaryservices)  Experimental 
   Returns a promise to a list of primary [`BluetoothRemoteGATTService`](bluetoothremotegattservice) objects offered by the Bluetooth device for a specified `BluetoothServiceUUID`. 

  
Specifications
--------------




| Specification |
| --- |
| [Web Bluetooth # bluetoothgattremoteserver-interface](https://webbluetoothcg.github.io/web-bluetooth/#bluetoothgattremoteserver-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `BluetoothRemoteGATTServer` | 56Before Chrome 70, this feature was only supported in macOS. In Chrome 70, support was added for Windows 10. Linux support is not enabled by default.56In Linux and versions of Windows earlier than 10, this flag must be enabled. | 79Supported by default only on macOS and Windows 10. Linux support is not enabled by default.79In Linux and versions of Windows earlier than 10, this flag must be enabled. | No | No | 43Before Opera 57, this feature was only supported in macOS. In Opera 57, support was added for Windows 10. Linux support is not enabled by default.43In Linux and versions of Windows earlier than 10, this flag must be enabled. | No | NoSee [bug 1100993](https://crbug.com/1100993). | 56 | No | 43 | No | 6.0 |
| `connect` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `connected` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `device` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `disconnect` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `getPrimaryService` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `getPrimaryServices` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/BluetoothRemoteGATTServer>

BluetoothRemoteGATTService
==========================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

  The `BluetoothRemoteGATTService` interface of the [Web Bluetooth API](web_bluetooth_api) represents a service provided by a GATT server, including a device, a list of referenced services, and a list of the characteristics of this service. 


 EventTarget BluetoothRemoteGATTService

Instance properties
-------------------


 
[`BluetoothRemoteGATTService.device`](bluetoothremotegattservice/device) Read only   Experimental 
   Returns information about a Bluetooth device through an instance of [`BluetoothDevice`](bluetoothdevice). 

  
[`BluetoothRemoteGATTService.isPrimary`](bluetoothremotegattservice/isprimary) Read only   Experimental 
   Returns a boolean value indicating whether this is a primary or secondary service. 

  
[`BluetoothRemoteGATTService.uuid`](bluetoothremotegattservice/uuid) Read only   Experimental 
  Returns a string representing the UUID of this service.

  
Instance methods
----------------


 
[`BluetoothRemoteGATTService.getCharacteristic()`](bluetoothremotegattservice/getcharacteristic)  Experimental 
   Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) to an instance of [`BluetoothRemoteGATTCharacteristic`](bluetoothremotegattcharacteristic) for a given universally unique identifier (UUID). 

  
[`BluetoothRemoteGATTService.getCharacteristics()`](bluetoothremotegattservice/getcharacteristics)  Experimental 
   Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) to an [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of [`BluetoothRemoteGATTCharacteristic`](bluetoothremotegattcharacteristic) instances for an optional universally unique identifier (UUID). 

  
Specifications
--------------




| Specification |
| --- |
| [Web Bluetooth # bluetoothgattservice-interface](https://webbluetoothcg.github.io/web-bluetooth/#bluetoothgattservice-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `BluetoothRemoteGATTService` | 56Before Chrome 70, this feature was only supported in macOS. In Chrome 70, support was added for Windows 10. Linux support is not enabled by default.56In Linux and versions of Windows earlier than 10, this flag must be enabled. | 79Supported by default only on macOS and Windows 10. Linux support is not enabled by default.79In Linux and versions of Windows earlier than 10, this flag must be enabled. | No | No | 43Before Opera 57, this feature was only supported in macOS. In Opera 57, support was added for Windows 10. Linux support is not enabled by default.43In Linux and versions of Windows earlier than 10, this flag must be enabled. | No | NoSee [bug 1100993](https://crbug.com/1100993). | 56 | No | 43 | No | 6.0 |
| `device` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `getCharacteristic` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `getCharacteristics` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `isPrimary` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `uuid` | 56 | 79 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/BluetoothRemoteGATTService>

CacheStorage
============



The `CacheStorage` interface represents the storage for [`Cache`](cache) objects.

 The interface:

 * Provides a master directory of all the named caches that can be accessed by a [`ServiceWorker`](serviceworker) or other type of worker or [`window`](window) scope (you're not limited to only using it with service workers).
* Maintains a mapping of string names to corresponding [`Cache`](cache) objects.

 Use [`CacheStorage.open()`](cachestorage/open) to obtain a [`Cache`](cache) instance.

 Use [`CacheStorage.match()`](cachestorage/match) to check if a given [`Request`](request) is a key in any of the [`Cache`](cache) objects that the `CacheStorage` object tracks.

 You can access `CacheStorage` through the global [`caches`](caches) property.

  **Note:** `CacheStorage` always rejects with a `SecurityError` on untrusted origins (i.e. those that aren't using HTTPS, although this definition will likely become more complex in the future.) When testing on Firefox, you can get around this by checking the **Enable Service Workers over HTTP (when toolbox is open)** option in the Firefox Devtools options/gear menu. Furthermore, because `CacheStorage` requires file-system access, it may be unavailable in private mode in Firefox.

   **Note:** [`CacheStorage.match()`](cachestorage/match) is a convenience method. Equivalent functionality to match a cache entry can be implemented by returning an array of cache names from [`CacheStorage.keys()`](cachestorage/keys), opening each cache with [`CacheStorage.open()`](cachestorage/open), and matching the one you want with [`Cache.match()`](cache/match).

 
 **Note:** This feature is available in [Web Workers](web_workers_api)

  **Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).



Instance methods
----------------


 [`CacheStorage.match()`](cachestorage/match)  Checks if a given [`Request`](request) is a key in any of the [`Cache`](cache) objects that the [`CacheStorage`](cachestorage) object tracks, and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to that match.

  [`CacheStorage.has()`](cachestorage/has)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to `true` if a [`Cache`](cache) object matching the `cacheName` exists.

  [`CacheStorage.open()`](cachestorage/open)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to the [`Cache`](cache) object matching the `cacheName` (a new cache is created if it doesn't already exist.)

  [`CacheStorage.delete()`](cachestorage/delete)  Finds the [`Cache`](cache) object matching the `cacheName`, and if found, deletes the [`Cache`](cache) object and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to `true`. If no [`Cache`](cache) object is found, it resolves to `false`.

  [`CacheStorage.keys()`](cachestorage/keys)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that will resolve with an array containing strings corresponding to all of the named [`Cache`](cache) objects tracked by the [`CacheStorage`](cachestorage). Use this method to iterate over a list of all the [`Cache`](cache) objects.

  
Examples
--------



 This code snippet is from the MDN [simple service worker example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker) (see [simple service worker running live](https://bncb2v.csb.app/).) This service worker script waits for an [`InstallEvent`](installevent) to fire, then runs [`waitUntil`](extendableevent/waituntil) to handle the install process for the app. This consists of calling [`CacheStorage.open`](cachestorage/open) to create a new cache, then using [`Cache.addAll`](cache/addall) to add a series of assets to it. 

 In the second code block, we wait for a [`FetchEvent`](fetchevent) to fire. We construct a custom response like so:

 1. Check whether a match for the request is found in the CacheStorage. If so, serve that.
2. If not, fetch the request from the network, then also open the cache created in the first block and add a clone of the request to it using [`Cache.put`](cache/put) (`cache.put(event.request, response.clone())`.)
3. If this fails (e.g. because the network is down), return a fallback response.

 Finally, return whatever the custom response ended up being equal to, using [`FetchEvent.respondWith`](fetchevent/respondwith).

 
```
self.addEventListener("install", (event) => {
  event.waitUntil(
    caches
      .open("v1")
      .then((cache) =>
        cache.addAll([
          "/",
          "/index.html",
          "/style.css",
          "/app.js",
          "/image-list.js",
          "/star-wars-logo.jpg",
          "/gallery/bountyHunters.jpg",
          "/gallery/myLittleVader.jpg",
          "/gallery/snowTroopers.jpg",
        ])
      )
  );
});

self.addEventListener("fetch", (event) => {
  event.respondWith(
    caches.match(event.request).then((response) => {
      // caches.match() always resolves
      // but in case of success response will have value
      if (response !== undefined) {
        return response;
      } else {
        return fetch(event.request)
          .then((response) => {
            // response may be used only once
            // we need to save clone to put one copy in cache
            // and serve second one
            let responseClone = response.clone();

            caches.open("v1").then((cache) => {
              cache.put(event.request, responseClone);
            });
            return response;
          })
          .catch(() => caches.match("/gallery/myLittleVader.jpg"));
      }
    })
  );
});

```
 This snippet shows how the API can be used outside of a service worker context, and uses the `await` operator for much more readable code.

 
```
// Try to get data from the cache, but fall back to fetching it live.
async function getData() {
  const cacheVersion = 1;
  const cacheName = `myapp-${cacheVersion}`;
  const url = "https://jsonplaceholder.typicode.com/todos/1";
  let cachedData = await getCachedData(cacheName, url);

  if (cachedData) {
    console.log("Retrieved cached data");
    return cachedData;
  }

  console.log("Fetching fresh data");

  const cacheStorage = await caches.open(cacheName);
  await cacheStorage.add(url);
  cachedData = await getCachedData(cacheName, url);
  await deleteOldCaches(cacheName);

  return cachedData;
}

// Get data from the cache.
async function getCachedData(cacheName, url) {
  const cacheStorage = await caches.open(cacheName);
  const cachedResponse = await cacheStorage.match(url);

  if (!cachedResponse || !cachedResponse.ok) {
    return false;
  }

  return await cachedResponse.json();
}

// Delete any old caches to respect user's disk space.
async function deleteOldCaches(currentCache) {
  const keys = await caches.keys();

  for (const key of keys) {
    const isOurCache = key.startsWith("myapp-");
    if (currentCache === key || !isOurCache) {
      continue;
    }
    caches.delete(key);
  }
}

try {
  const data = await getData();
  console.log({ data });
} catch (error) {
  console.error({ error });
}

```


Specifications
--------------




| Specification |
| --- |
| [Service Workers # cachestorage-interface](https://w3c.github.io/ServiceWorker/#cachestorage-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CacheStorage` | 4340–43Only available in service workers. | 16 | 41 | No | 3027–30Only available in service workers. | 11.1 | 4340–43Only available in service workers. | 4340–43Only available in service workers. | 41 | 3027–30Only available in service workers. | 11.3 | 4.0 |
| `delete` | 40 | 16 | 41 | No | 27 | 11.1 | 40 | 40 | 41 | 27 | 11.3 | 4.0 |
| `has` | 40 | 16 | 41 | No | 27 | 11.1 | 40 | 40 | 41 | 27 | 11.3 | 4.0 |
| `keys` | 40 | 16 | 41 | No | 27 | 11.1 | 40 | 40 | 41 | 27 | 11.3 | 4.0 |
| `match` | 5440The options parameter only supports `ignoreSearch`, and `cacheName`. | 16 | 41 | No | 4127The options parameter only supports `ignoreSearch`, and `cacheName`. | 11.1 | 5440The options parameter only supports `ignoreSearch`, and `cacheName`. | 5440The options parameter only supports `ignoreSearch`, and `cacheName`. | 41 | 4127The options parameter only supports `ignoreSearch`, and `cacheName`. | 11.3 | 6.04.0The options parameter only supports `ignoreSearch`, and `cacheName`. |
| `open` | 40 | 16 | 41 | No | 27 | 11.1 | 40 | 40 | 41 | 27 | 11.3 | 4.0 |
| `secure_context_required` | 65 | 79 | 44 | No | 52 | 11.1 | 65 | 65 | 44 | 47 | 11.3 | 9.0 |
| `worker_support` | 4340–43Only available in service workers. | 16 | 44 | No | 3027–30Only available in service workers. | 11.1 | 4340–43Only available in service workers. | 4340–43Only available in service workers. | 44 | 3027–30Only available in service workers. | 11.3 | 4.0 |


See also
--------


* [Using Service Workers](service_worker_api/using_service_workers)
* [`Cache`](cache)
* [`caches`](caches)
* [Private Browsing / Incognito modes](web_storage_api#private_browsing_incognito_modes)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage>

CanvasCaptureMediaStreamTrack
=============================



The `CanvasCaptureMediaStreamTrack` interface represents the video track contained in a [`MediaStream`](mediastream) being generated from a [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) following a call to [`HTMLCanvasElement.captureStream()`](htmlcanvaselement/capturestream).

 Part of the [Media Capture and Streams API](media_capture_and_streams_api).


 EventTarget MediaStreamTrack CanvasCaptureMediaStreamTrack

Instance properties
-------------------



*This interface inherits the properties of its parent, [`MediaStreamTrack`](mediastreamtrack).*

  
[`CanvasCaptureMediaStreamTrack.canvas`](canvascapturemediastreamtrack/canvas) Read only 
  Returns the [`HTMLCanvasElement`](htmlcanvaselement) object whose surface is captured in real-time.

  

Instance methods
----------------



*This interface inherits the methods of its parent, [`MediaStreamTrack`](mediastreamtrack).*

  [`CanvasCaptureMediaStreamTrack.requestFrame()`](canvascapturemediastreamtrack/requestframe)  Manually forces a frame to be captured and sent to the stream. This lets applications that wish to specify the frame capture times directly do so, if they specified a `frameRate` of 0 when calling [`captureStream()`](htmlcanvaselement/capturestream).

  

Specifications
--------------




| Specification |
| --- |
| [Media Capture from DOM Elements # the-canvascapturemediastreamtrack](https://w3c.github.io/mediacapture-fromelement/#the-canvascapturemediastreamtrack) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CanvasCaptureMediaStreamTrack` | 51 | 79 | 41 | No | 38 | 11 | 51 | 51 | No | 41 | 11 | 5.0 |
| `canvas` | 51 | 79 | 41 | No | 38 | 11 | 51 | 51 | No | 41 | 11 | 5.0 |
| `requestFrame` | 51 | 79 | 41 | No | 38 | 11 | 51 | 51 | No | 41 | 11 | 5.0 |


See also
--------


* [`HTMLCanvasElement.captureStream()`](htmlcanvaselement/capturestream) to begin capturing frames from a canvas


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CanvasCaptureMediaStreamTrack>

CanvasGradient
==============



The `CanvasGradient` interface represents an [opaque object](https://en.wikipedia.org/wiki/Opaque_data_type) describing a gradient. It is returned by the methods [`CanvasRenderingContext2D.createLinearGradient()`](canvasrenderingcontext2d/createlineargradient), [`CanvasRenderingContext2D.createConicGradient()`](canvasrenderingcontext2d/createconicgradient) or [`CanvasRenderingContext2D.createRadialGradient()`](canvasrenderingcontext2d/createradialgradient).

 It can be used as a [`fillStyle`](canvasrenderingcontext2d/fillstyle) or [`strokeStyle`](canvasrenderingcontext2d/strokestyle).



Instance properties
-------------------


*As an opaque object, there is no exposed property.*


Instance methods
----------------


 [`CanvasGradient.addColorStop()`](canvasgradient/addcolorstop)  Adds a new stop, defined by an `offset` and a `color`, to the gradient.

  
Specifications
--------------




| Specification |
| --- |
| [HTML Standard # canvasgradient](https://html.spec.whatwg.org/multipage/canvas.html#canvasgradient) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CanvasGradient` | 1 | 12 | 1.5Before Firefox 5.0, specifying non-finite values when adding color stops through a call to `addColorStop()` incorrectly throws `SYNTAX_ERR` instead of `INDEX_SIZE_ERR`. | 9 | 9 | 2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `addColorStop` | 1 | 12 | 1.5 | 9 | 9 | 2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |


See also
--------


* Creator methods in [`CanvasRenderingContext2D`](canvasrenderingcontext2d).
* The [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element and its associated interface, [`HTMLCanvasElement`](htmlcanvaselement).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CanvasGradient>

CanvasPattern
=============



The `CanvasPattern` interface represents an [opaque object](https://en.wikipedia.org/wiki/Opaque_data_type) describing a pattern, based on an image, a canvas, or a video, created by the [`CanvasRenderingContext2D.createPattern()`](canvasrenderingcontext2d/createpattern) method.

 It can be used as a [`fillStyle`](canvasrenderingcontext2d/fillstyle) or [`strokeStyle`](canvasrenderingcontext2d/strokestyle).



Instance properties
-------------------


*As an opaque object, this has no exposed property.*


Instance methods
----------------



*There are no inherited method.*

  [`CanvasPattern.setTransform()`](canvaspattern/settransform)  Applies a [`DOMMatrix`](dommatrix) representing a linear transform to the pattern.

  

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # canvaspattern](https://html.spec.whatwg.org/multipage/canvas.html#canvaspattern) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CanvasPattern` | 1 | 12 | 1.5 | 9 | 9 | 2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `setTransform` | 68 | 79 | 33 | No | 55 | 11.1 | 68 | 68 | 33 | 48 | 11.3 | 10.0 |


See also
--------


* [`CanvasRenderingContext2D.createPattern()`](canvasrenderingcontext2d/createpattern)
* The [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element and its associated interface, [`HTMLCanvasElement`](htmlcanvaselement)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CanvasPattern>

CanvasRenderingContext2D
========================



 The `CanvasRenderingContext2D` interface, part of the [Canvas API](canvas_api), provides the 2D rendering context for the drawing surface of a [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element. It is used for drawing shapes, text, images, and other objects. 

  The interface's properties and methods are described in the reference section of this page. The [Canvas tutorial](canvas_api/tutorial) has more explanation, examples, and resources, as well. 

  For [`OffscreenCanvas`](offscreencanvas), there is an equivalent interface that provides the rendering context. The offscreen rendering context inherits most of the same properties and methods as the `CanvasRenderingContext2D` and is described in more detail in the [`OffscreenCanvasRenderingContext2D`](offscreencanvasrenderingcontext2d) reference page. 



Basic example
-------------



To get a `CanvasRenderingContext2D` instance, you must first have an HTML `<canvas>` element to work with:

 
```
<canvas id="my-house" width="300" height="300"></canvas>

```
 To get the canvas' 2D rendering context, call [`getContext()`](htmlcanvaselement/getcontext) on the `<canvas>` element, supplying `'2d'` as the argument:

 
```
const canvas = document.getElementById("my-house");
const ctx = canvas.getContext("2d");

```
 With the context in hand, you can draw anything you like. This code draws a house:

 
```
// Set line width
ctx.lineWidth = 10;

// Wall
ctx.strokeRect(75, 140, 150, 110);

// Door
ctx.fillRect(130, 190, 40, 60);

// Roof
ctx.beginPath();
ctx.moveTo(50, 140);
ctx.lineTo(150, 60);
ctx.lineTo(250, 140);
ctx.closePath();
ctx.stroke();

```
 The resulting drawing looks like this:




Reference
---------


### Context


 
[`CanvasRenderingContext2D.isContextLost()`](canvasrenderingcontext2d/iscontextlost)  Experimental 
  Returns `true` if the rendering context was lost.

  
### Drawing rectangles



There are three methods that immediately draw rectangles to the canvas.

  [`CanvasRenderingContext2D.clearRect()`](canvasrenderingcontext2d/clearrect)  Sets all pixels in the rectangle defined by starting point *(x, y)* and size *(width, height)* to transparent black, erasing any previously drawn content.

  [`CanvasRenderingContext2D.fillRect()`](canvasrenderingcontext2d/fillrect)  Draws a filled rectangle at *(x, y)* position whose size is determined by *width* and *height*.

  [`CanvasRenderingContext2D.strokeRect()`](canvasrenderingcontext2d/strokerect)  Paints a rectangle which has a starting point at *(x, y)* and has a *w* width and an *h* height onto the canvas, using the current stroke style.

  

### Drawing text



The following methods draw text. See also the [`TextMetrics`](textmetrics) object for text properties.

  [`CanvasRenderingContext2D.fillText()`](canvasrenderingcontext2d/filltext)  Draws (fills) a given text at the given (x, y) position.

  [`CanvasRenderingContext2D.strokeText()`](canvasrenderingcontext2d/stroketext)  Draws (strokes) a given text at the given (x, y) position.

  [`CanvasRenderingContext2D.measureText()`](canvasrenderingcontext2d/measuretext)  Returns a [`TextMetrics`](textmetrics) object.

  

### Line styles



The following methods and properties control how lines are drawn.

  [`CanvasRenderingContext2D.lineWidth`](canvasrenderingcontext2d/linewidth)  Width of lines. Default `1.0`.

  [`CanvasRenderingContext2D.lineCap`](canvasrenderingcontext2d/linecap)  Type of endings on the end of lines. Possible values: `butt` (default), `round`, `square`.

  [`CanvasRenderingContext2D.lineJoin`](canvasrenderingcontext2d/linejoin)  Defines the type of corners where two lines meet. Possible values: `round`, `bevel`, `miter` (default).

  [`CanvasRenderingContext2D.miterLimit`](canvasrenderingcontext2d/miterlimit)  Miter limit ratio. Default `10`.

  [`CanvasRenderingContext2D.getLineDash()`](canvasrenderingcontext2d/getlinedash)  Returns the current line dash pattern array containing an even number of non-negative numbers.

  [`CanvasRenderingContext2D.setLineDash()`](canvasrenderingcontext2d/setlinedash)  Sets the current line dash pattern.

  [`CanvasRenderingContext2D.lineDashOffset`](canvasrenderingcontext2d/linedashoffset)  Specifies where to start a dash array on a line.

  

### Text styles



The following properties control how text is laid out.

  [`CanvasRenderingContext2D.font`](canvasrenderingcontext2d/font)  Font setting. Default value `"10px sans-serif"`.

  [`CanvasRenderingContext2D.textAlign`](canvasrenderingcontext2d/textalign)  Text alignment setting. Possible values: `start` (default), `end`, `left`, `right`, `center`.

  [`CanvasRenderingContext2D.textBaseline`](canvasrenderingcontext2d/textbaseline)  Baseline alignment setting. Possible values: `top`, `hanging`, `middle`, `alphabetic` (default), `ideographic`, `bottom`.

  [`CanvasRenderingContext2D.direction`](canvasrenderingcontext2d/direction)  Directionality. Possible values: `ltr`, `rtl`, `inherit` (default).

  
[`CanvasRenderingContext2D.letterSpacing`](canvasrenderingcontext2d/letterspacing)  Experimental 
  Letter spacing. Default: `0px`.

  [`CanvasRenderingContext2D.fontKerning`](canvasrenderingcontext2d/fontkerning)  Font kerning. Possible values: `auto` (default), `normal`, `none`.

  
[`CanvasRenderingContext2D.fontStretch`](canvasrenderingcontext2d/fontstretch)  Experimental 
  Font stretch. Possible values: `ultra-condensed`, `extra-condensed`, `condensed`, `semi-condensed`, `normal` (default), `semi-expanded`, `expanded`, `extra-expanded`, `ultra-expanded`.

  
[`CanvasRenderingContext2D.fontVariantCaps`](canvasrenderingcontext2d/fontvariantcaps)  Experimental 
  Font variant caps. Possible values: `normal` (default), `small-caps`, `all-small-caps`, `petite-caps`, `all-petite-caps`, `unicase`, `titling-caps`.

  
[`CanvasRenderingContext2D.textRendering`](canvasrenderingcontext2d/textrendering)  Experimental 
  Text rendering. Possible values: `auto` (default), `optimizeSpeed`, `optimizeLegibility`, `geometricPrecision`.

  
[`CanvasRenderingContext2D.wordSpacing`](canvasrenderingcontext2d/wordspacing)  Experimental 
  Word spacing. Default value: `0px`

  

### Fill and stroke styles



Fill styling is used for colors and styles inside shapes and stroke styling is used for the lines around shapes.

  [`CanvasRenderingContext2D.fillStyle`](canvasrenderingcontext2d/fillstyle)  Color or style to use inside shapes. Default `#000` (black).

  [`CanvasRenderingContext2D.strokeStyle`](canvasrenderingcontext2d/strokestyle)  Color or style to use for the lines around shapes. Default `#000` (black).

  

### Gradients and patterns


 [`CanvasRenderingContext2D.createConicGradient()`](canvasrenderingcontext2d/createconicgradient)  Creates a conic gradient around a point given by coordinates represented by the parameters.

  [`CanvasRenderingContext2D.createLinearGradient()`](canvasrenderingcontext2d/createlineargradient)  Creates a linear gradient along the line given by the coordinates represented by the parameters.

  [`CanvasRenderingContext2D.createRadialGradient()`](canvasrenderingcontext2d/createradialgradient)  Creates a radial gradient given by the coordinates of the two circles represented by the parameters.

  [`CanvasRenderingContext2D.createPattern()`](canvasrenderingcontext2d/createpattern)  Creates a pattern using the specified image. It repeats the source in the directions specified by the repetition argument. This method returns a [`CanvasPattern`](canvaspattern).

  
### Shadows


 [`CanvasRenderingContext2D.shadowBlur`](canvasrenderingcontext2d/shadowblur)  Specifies the blurring effect. Default: `0`.

  [`CanvasRenderingContext2D.shadowColor`](canvasrenderingcontext2d/shadowcolor)  Color of the shadow. Default: fully-transparent black.

  [`CanvasRenderingContext2D.shadowOffsetX`](canvasrenderingcontext2d/shadowoffsetx)  Horizontal distance the shadow will be offset. Default: `0`.

  [`CanvasRenderingContext2D.shadowOffsetY`](canvasrenderingcontext2d/shadowoffsety)  Vertical distance the shadow will be offset. Default: `0`.

  
### Paths



The following methods can be used to manipulate paths of objects.

  [`CanvasRenderingContext2D.beginPath()`](canvasrenderingcontext2d/beginpath)  Starts a new path by emptying the list of sub-paths. Call this method when you want to create a new path.

  [`CanvasRenderingContext2D.closePath()`](canvasrenderingcontext2d/closepath)  Causes the point of the pen to move back to the start of the current sub-path. It tries to draw a straight line from the current point to the start. If the shape has already been closed or has only one point, this function does nothing.

  [`CanvasRenderingContext2D.moveTo()`](canvasrenderingcontext2d/moveto)  Moves the starting point of a new sub-path to the (x, y) coordinates.

  [`CanvasRenderingContext2D.lineTo()`](canvasrenderingcontext2d/lineto)  Connects the last point in the current sub-path to the specified (x, y) coordinates with a straight line.

  [`CanvasRenderingContext2D.bezierCurveTo()`](canvasrenderingcontext2d/beziercurveto)  Adds a cubic Bézier curve to the current path.

  [`CanvasRenderingContext2D.quadraticCurveTo()`](canvasrenderingcontext2d/quadraticcurveto)  Adds a quadratic Bézier curve to the current path.

  [`CanvasRenderingContext2D.arc()`](canvasrenderingcontext2d/arc)  Adds a circular arc to the current path.

  [`CanvasRenderingContext2D.arcTo()`](canvasrenderingcontext2d/arcto)  Adds an arc to the current path with the given control points and radius, connected to the previous point by a straight line.

  [`CanvasRenderingContext2D.ellipse()`](canvasrenderingcontext2d/ellipse)  Adds an elliptical arc to the current path.

  [`CanvasRenderingContext2D.rect()`](canvasrenderingcontext2d/rect)  Creates a path for a rectangle at position (x, y) with a size that is determined by *width* and *height*.

  [`CanvasRenderingContext2D.roundRect()`](canvasrenderingcontext2d/roundrect)  Creates a path for a rounded rectangle with a specified position, width, height, and corner radii.

  

### Drawing paths


 [`CanvasRenderingContext2D.fill()`](canvasrenderingcontext2d/fill)  Fills the current sub-paths with the current fill style.

  [`CanvasRenderingContext2D.stroke()`](canvasrenderingcontext2d/stroke)  Strokes the current sub-paths with the current stroke style.

  [`CanvasRenderingContext2D.drawFocusIfNeeded()`](canvasrenderingcontext2d/drawfocusifneeded)  If a given element is focused, this method draws a focus ring around the current path.

  
[`CanvasRenderingContext2D.scrollPathIntoView()`](canvasrenderingcontext2d/scrollpathintoview)  Experimental 
  Scrolls the current path or a given path into the view.

  [`CanvasRenderingContext2D.clip()`](canvasrenderingcontext2d/clip)  Creates a clipping path from the current sub-paths. Everything drawn after `clip()` is called appears inside the clipping path only. For an example, see [Clipping paths](canvas_api/tutorial/compositing) in the Canvas tutorial.

  [`CanvasRenderingContext2D.isPointInPath()`](canvasrenderingcontext2d/ispointinpath)  Reports whether or not the specified point is contained in the current path.

  [`CanvasRenderingContext2D.isPointInStroke()`](canvasrenderingcontext2d/ispointinstroke)  Reports whether or not the specified point is inside the area contained by the stroking of a path.

  
### Transformations



Objects in the `CanvasRenderingContext2D` rendering context have a current transformation matrix and methods to manipulate it. The transformation matrix is applied when creating the current default path, painting text, shapes and [`Path2D`](path2d) objects. The methods listed below remain for historical and compatibility reasons as [`DOMMatrix`](dommatrix) objects are used in most parts of the API nowadays and will be used in the future instead.

  [`CanvasRenderingContext2D.getTransform()`](canvasrenderingcontext2d/gettransform)  Retrieves the current transformation matrix being applied to the context.

  [`CanvasRenderingContext2D.rotate()`](canvasrenderingcontext2d/rotate)  Adds a rotation to the transformation matrix. The angle argument represents a clockwise rotation angle and is expressed in radians.

  [`CanvasRenderingContext2D.scale()`](canvasrenderingcontext2d/scale)  Adds a scaling transformation to the canvas units by x horizontally and by y vertically.

  [`CanvasRenderingContext2D.translate()`](canvasrenderingcontext2d/translate)  Adds a translation transformation by moving the canvas and its origin x horizontally and y vertically on the grid.

  [`CanvasRenderingContext2D.transform()`](canvasrenderingcontext2d/transform)  Multiplies the current transformation matrix with the matrix described by its arguments.

  [`CanvasRenderingContext2D.setTransform()`](canvasrenderingcontext2d/settransform)  Resets the current transform to the identity matrix, and then invokes the `transform()` method with the same arguments.

  [`CanvasRenderingContext2D.resetTransform()`](canvasrenderingcontext2d/resettransform)  Resets the current transform by the identity matrix.

  

### Compositing


 [`CanvasRenderingContext2D.globalAlpha`](canvasrenderingcontext2d/globalalpha)  Alpha value that is applied to shapes and images before they are composited onto the canvas. Default `1.0` (opaque).

  [`CanvasRenderingContext2D.globalCompositeOperation`](canvasrenderingcontext2d/globalcompositeoperation)  With `globalAlpha` applied this sets how shapes and images are drawn onto the existing bitmap.

  
### Drawing images


 [`CanvasRenderingContext2D.drawImage()`](canvasrenderingcontext2d/drawimage)  Draws the specified image. This method is available in multiple formats, providing a great deal of flexibility in its use.

  
### Pixel manipulation



See also the [`ImageData`](imagedata) object.

  [`CanvasRenderingContext2D.createImageData()`](canvasrenderingcontext2d/createimagedata)  Creates a new, blank [`ImageData`](imagedata) object with the specified dimensions. All of the pixels in the new object are transparent black.

  [`CanvasRenderingContext2D.getImageData()`](canvasrenderingcontext2d/getimagedata)  Returns an [`ImageData`](imagedata) object representing the underlying pixel data for the area of the canvas denoted by the rectangle which starts at *(sx, sy)* and has an *sw* width and *sh* height.

  [`CanvasRenderingContext2D.putImageData()`](canvasrenderingcontext2d/putimagedata)  Paints data from the given [`ImageData`](imagedata) object onto the bitmap. If a dirty rectangle is provided, only the pixels from that rectangle are painted.

  

### Image smoothing


 [`CanvasRenderingContext2D.imageSmoothingEnabled`](canvasrenderingcontext2d/imagesmoothingenabled)  Image smoothing mode; if disabled, images will not be smoothed if scaled.

  [`CanvasRenderingContext2D.imageSmoothingQuality`](canvasrenderingcontext2d/imagesmoothingquality)  Allows you to set the quality of image smoothing.

  
### The canvas state



The `CanvasRenderingContext2D` rendering context contains a variety of drawing style states (attributes for line styles, fill styles, shadow styles, text styles). The following methods help you to work with that state:

  [`CanvasRenderingContext2D.save()`](canvasrenderingcontext2d/save)  Saves the current drawing style state using a stack so you can revert any change you make to it using `restore()`.

  [`CanvasRenderingContext2D.restore()`](canvasrenderingcontext2d/restore)  Restores the drawing style state to the last element on the 'state stack' saved by `save()`.

  [`CanvasRenderingContext2D.canvas`](canvasrenderingcontext2d/canvas)  A read-only back-reference to the [`HTMLCanvasElement`](htmlcanvaselement). Might be [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null) if it is not associated with a [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element.

  [`CanvasRenderingContext2D.getContextAttributes()`](canvasrenderingcontext2d/getcontextattributes)  Returns an object containing the actual context attributes. Context attributes can be requested with [`HTMLCanvasElement.getContext()`](htmlcanvaselement/getcontext).

  [`CanvasRenderingContext2D.reset()`](canvasrenderingcontext2d/reset)  Resets the rendering context, including the backing buffer, the drawing state stack, path, and styles.

  
[`CanvasRenderingContext2D.isContextLost()`](canvasrenderingcontext2d/iscontextlost)  Experimental 
  Returns `true` if the rendering context was lost.

  

### Filters


 [`CanvasRenderingContext2D.filter`](canvasrenderingcontext2d/filter)  Applies a CSS or SVG filter to the canvas, e.g., to change its brightness or blurriness.

  
Specifications
--------------




| Specification |
| --- |
| [HTML Standard # 2dcontext](https://html.spec.whatwg.org/multipage/canvas.html#2dcontext) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CanvasRenderingContext2D` | 1 | 12 | 1.5 | 9 | 9 | 2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `arc` | 1 | 12 | 1.5 | 9 | 11.6 | 3 | 4.4 | 18 | 4 | 12 | 1 | 1.0 |
| `arcTo` | 1 | 12 | 1.5 | 9 | 11.6 | 2 | 4.4 | 18 | 4 | 12 | 1 | 1.0 |
| `beginPath` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `bezierCurveTo` | 1 | 12 | 1.5 | 9 | 11.6 | 2 | 4.4 | 18 | 4 | 12 | 1 | 1.0 |
| `canvas` | 1 | 12 | 1.5 | 9 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `clearRect` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `clip` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `closePath` | 1 | 12 | 1.5 | 9 | 11.6 | 2 | 4.4 | 18 | 4 | 12 | 1 | 1.0 |
| `createConicGradient` | 99 | 99 | 90 | No | 85 | 15 | 99 | 99 | 90 | 68 | 15 | 18.0 |
| `createImageData` | 2 | 12 | 3.5 | 9 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `createLinearGradient` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `createPattern` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `createRadialGradient` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `direction` | 77 | 79 | 101 | No | 64 | 9 | 77 | 77 | 101 | 55 | 9 | 12.0 |
| `drawFocusIfNeeded` | 37 | 14 | 3228 | No | 24 | 8 | 37 | 37 | 3228 | 24 | 8 | 3.0 |
| `drawImage` | 1 | 12 | 1.5 | 9 | 9 | 2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `ellipse` | 31 | 13 | 48 | No | 18 | 9 | 4.4.3 | 31 | 48 | 18 | 9 | 2.0 |
| `fill` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `fillRect` | 1 | 12 | 1.5 | 9 | 9 | 2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `fillStyle` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `fillText` | 2 | 12 | 3.5 | 9 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `filter` | 52 | 79 | 49 | No | 39 | NoSee [bug 198416](https://webkit.org/b/198416). | 52 | 52 | 49 | 41 | NoSee [bug 198416](https://webkit.org/b/198416). | 6.0 |
| `font` | 2 | 12 | 3.5 | 9 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `fontKerning` | 99 | 99 | 104 | No | 85 | No | 99 | 99 | 104 | 68 | No | 18.0 |
| `fontStretch` | 99 | 99 | No | No | 85 | No | 99 | 99 | No | 68 | No | 18.0 |
| `fontVariantCaps` | 99 | 99 | No | No | 85 | No | 99 | 99 | No | 68 | No | 18.0 |
| `getContextAttributes` | 7332–60 | 79 | No | No | 6019–47 | 15 | 734.4.3–60 | 7332–60 | No | 5219–44 | 15 | 11.02.0–8.0 |
| `getImageData` | 2 | 12 | 2Since Firefox 5, `getImageData` now correctly accepts rectangles that extend beyond the bounds of the canvas; pixels outside the canvas are returned as transparent black and now also returns at least one pixel's worth of image data if a rectangle smaller than one pixel is specified. | 9 | 9.5 | 4 | ≤37 | 18 | 4Since Firefox 5, `getImageData` now correctly accepts rectangles that extend beyond the bounds of the canvas; pixels outside the canvas are returned as transparent black and now also returns at least one pixel's worth of image data if a rectangle smaller than one pixel is specified. | 10.1 | 3.2 | 1.0 |
| `getLineDash` | 23 | 12 | 27 | 11 | 15 | 7 | 4.4 | 25 | 27 | 14 | 7 | 1.5 |
| `getTransform` | 68 | 79 | 70 | No | 55 | 11.1 | 68 | 68 | 79 | 48 | 11.3 | 10.0 |
| `globalAlpha` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `globalCompositeOperation` | 1 | 12 | 1.5 | 9 | 9 | 2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `imageSmoothingEnabled` | 3021–30 | 1512–15 | 513.6–51 | 11 | 1715–17 | 9.1 | 4.4 | 3025–30 | 514–51 | 1814–18 | 9.3 | 2.01.5–2.0 |
| `imageSmoothingQuality` | 54 | 79 | No | No | 41 | 9.1 | 54 | 54 | No | 41 | 9.3 | 6.0 |
| `isContextLost` | 99 | 99 | No | No | 85 | No | 99 | 99 | No | 68 | No | 18.0 |
| `isPointInPath` | 1 | 12 | 2 | 9 | ≤12.1 | 3.1 | 4.4 | 18 | 4 | ≤12.1 | 2 | 1.0 |
| `isPointInStroke` | 26 | 79 | 19 | No | 15 | 7 | 4.4 | 26 | 19 | 14 | 7 | 1.5 |
| `letterSpacing` | 99 | 99 | No | No | 85 | No | 99 | 99 | No | 68 | No | 18.0 |
| `lineCap` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `lineDashOffset` | 23 | 12 | 277 | 11 | 15 | 7 | 4.4 | 25 | 277 | 14 | 7 | 1.5 |
| `lineJoin` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `lineTo` | 1 | 12 | 1.5 | 9 | 11.6 | 2 | 4.4 | 18 | 4 | 12 | 1 | 1.0 |
| `lineWidth` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `measureText` | 2 | 12 | 3.5 | 9 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `miterLimit` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `moveTo` | 1 | 12 | 1.5 | 9 | 11.6 | 2 | 4.4 | 18 | 4 | 12 | 1 | 1.0 |
| `putImageData` | 2 | 12 | 2 | 9 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `quadraticCurveTo` | 1 | 12 | 1.5 | 9 | 11.6 | 3 | 4.4 | 18 | 4 | 12 | 1 | 1.0 |
| `rect` | 1 | 12 | 1.5 | 9 | 11.6 | 2 | 4.4 | 18 | 4 | 12 | 1 | 1.0 |
| `reset` | 99 | 99 | 113 | No | 85 | No | 99 | 99 | 113 | 68 | No | 18.0 |
| `resetTransform` | 31 | 79 | 36 | No | 18 | 10.1 | 4.4.3 | 31 | 36 | 18 | 10.3 | 2.0 |
| `restore` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `rotate` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `roundRect` | 99 | 99 | 112 | No | 85 | 16 | 99 | 99 | 112 | 68 | 16 | 18.0 |
| `save` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `scale` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `scrollPathIntoView` | 36 | 79 | No | No | 23 | No | No | 36 | No | No | No | No |
| `setLineDash` | 23 | 12 | 27 | 11 | 15 | 7 | 4.4 | 25 | 27 | 14 | 7 | 1.5 |
| `setTransform` | 2 | 12 | 3 | 9 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `shadowBlur` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `shadowColor` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `shadowOffsetX` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `shadowOffsetY` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `stroke` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `strokeRect` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `strokeStyle` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `strokeText` | 2 | 12 | 3.5 | 9 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `textAlign` | 2 | 12 | 3.5 | 9 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `textBaseline` | 2 | 12 | 3.5 | 9 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `textRendering` | 99 | 99 | No | No | 85 | No | 99 | 99 | No | 68 | No | 18.0 |
| `transform` | 1 | 12 | 3 | 9 | ≤12.1 | 3.1 | 4.4 | 18 | 4 | ≤12.1 | 2 | 1.0 |
| `translate` | 1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `wordSpacing` | 99 | 99 | No | No | 85 | No | 99 | 99 | No | 68 | No | 18.0 |


See also
--------


* [`HTMLCanvasElement`](htmlcanvaselement)
* [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas)
* [`OffscreenCanvas`](offscreencanvas)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D>

CaptureController
=================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `CaptureController` interface provides methods that can be used to further manipulate a capture session separate from its initiation via [`MediaDevices.getDisplayMedia()`](mediadevices/getdisplaymedia).

 A `CaptureController` object is associated with a capture session by passing it into a [`getDisplayMedia()`](mediadevices/getdisplaymedia) call as the value of the options object's `controller` property.



Constructor
-----------


 
[`CaptureController()`](capturecontroller/capturecontroller)  Experimental 
  Creates a new `CaptureController` object instance.

  
Instance methods
----------------


 
[`setFocusBehavior()`](capturecontroller/setfocusbehavior)  Experimental 
  Controls whether the captured tab or window will be focused or whether the focus will remain with the tab containing the capturing app.

  
Examples
--------



```
// Create a new CaptureController instance
const controller = new CaptureController();

// Prompt the user to share a tab, window, or screen.
const stream = await navigator.mediaDevices.getDisplayMedia({ controller });

// Query the displaySurface value of the captured video track
const [track] = stream.getVideoTracks();
const displaySurface = track.getSettings().displaySurface;

if (displaySurface == "browser") {
  // Focus the captured tab.
  controller.setFocusBehavior("focus-captured-surface");
} else if (displaySurface == "window") {
  // Do not move focus to the captured window.
  // Keep the capturing page focused.
  controller.setFocusBehavior("no-focus-change");
}

```

Specifications
--------------




| Specification |
| --- |
| [Screen Capture # dom-capturecontroller](https://w3c.github.io/mediacapture-screen-share/#dom-capturecontroller) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CaptureController` | 109 | 109 | No | No | 95 | No | No | No | No | No | No | No |
| `CaptureController` | 109 | 109 | No | No | 95 | No | No | No | No | No | No | No |
| `setFocusBehavior` | 109 | 109 | No | No | 95 | No | No | No | No | No | No | No |


See also
--------


* [Screen Capture API](screen_capture_api)
* [`MediaDevices.getDisplayMedia()`](mediadevices/getdisplaymedia)
* [Better screen sharing with Conditional Focus](https://developer.chrome.com/docs/web-platform/conditional-focus/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CaptureController>

ChannelSplitterNode
===================



The `ChannelSplitterNode` interface, often used in conjunction with its opposite, [`ChannelMergerNode`](channelmergernode), separates the different channels of an audio source into a set of mono outputs. This is useful for accessing each channel separately, e.g. for performing channel mixing where gain must be separately controlled on each channel.

  ![Default channel splitter node with a single input splitting to form 6 mono outputs.] 

 If your `ChannelSplitterNode` always has one single input, the amount of outputs is defined by a parameter on its constructor and the call to [`AudioContext.createChannelSplitter()`](baseaudiocontext/createchannelsplitter). In the case that no value is given, it will default to `6`. If there are fewer channels in the input than there are outputs, supernumerary outputs are silent.


 EventTarget AudioNode ChannelSplitterNode 

|  |  |
| --- | --- |
| Number of inputs | `1` |
| Number of outputs | variable; default to `6`. |
| Channel count mode | `"explicit"` Older implementations, as per earlier versions of the spec use `"max"`.  |
| Channel count |  Fixed to the number of outputs. Older implementations, as per earlier versions of the spec use `2` (not used in the default count mode).  |
| Channel interpretation | `"discrete"` |



Constructor
-----------


 [`ChannelSplitterNode()`](channelsplitternode/channelsplitternode)  Creates a new `ChannelSplitterNode` object instance.

  
Instance properties
-------------------


*No specific property; inherits properties from its parent, [`AudioNode`](audionode)*.


Instance methods
----------------


*No specific method; inherits methods from its parent, [`AudioNode`](audionode)*.


Example
-------


See [`BaseAudioContext.createChannelSplitter()`](baseaudiocontext/createchannelsplitter#examples) for example code.


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # ChannelSplitterNode](https://webaudio.github.io/web-audio-api/#ChannelSplitterNode) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ChannelSplitterNode` | 55 | 79 | 53 | No | 42 | 14.1 | 55 | 55 | 53 | 42 | 14.5 | 6.0 |
| `ChannelSplitterNode` | 14Starting in Chrome 56, `channelCountMode` is set to `explicit` and `channelCount` is fixed to the number of outputs, as per the latest spec. | 12 | 25 | No | 15Starting in Opera 43, `channelCountMode` is set to `explicit` and `channelCount` is fixed to the number of outputs, as per the latest spec. | 6 | 4.4.3Starting in version 56, `channelCountMode` is set to `explicit` and `channelCount` is fixed to the number of outputs, as per the latest spec. | 18Starting in Chrome 56, `channelCountMode` is set to `explicit` and `channelCount` is fixed to the number of outputs, as per the latest spec. | 25 | 14Starting in Opera 43, `channelCountMode` is set to `explicit` and `channelCount` is fixed to the number of outputs, as per the latest spec. | 6 | 1.0Starting in Samsung Internet 6.0, `channelCountMode` is set to `explicit` and `channelCount` is fixed to the number of outputs, as per the latest spec. |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ChannelSplitterNode>

CharacterData
=============



The `CharacterData` abstract interface represents a [`Node`](node) object that contains characters. This is an abstract interface, meaning there aren't any objects of type `CharacterData`: it is implemented by other interfaces like [`Text`](text), [`Comment`](comment), [`CDATASection`](cdatasection), or [`ProcessingInstruction`](processinginstruction), which aren't abstract.


 EventTarget Node CharacterData

Instance properties
-------------------



*This interface also inherits properties from its parents, [`Node`](node) and [`EventTarget`](eventtarget).*

  [`CharacterData.data`](characterdata/data)  A string representing the textual data contained in this object.

  
[`CharacterData.length`](characterdata/length) Read only 
  Returns a number representing the size of the string contained in the object.

  
[`CharacterData.nextElementSibling`](characterdata/nextelementsibling) Read only 
  Returns the first [`Element`](element) that *follows* this node, and is a sibling.

  
[`CharacterData.previousElementSibling`](characterdata/previouselementsibling) Read only 
  Returns the first [`Element`](element) that *precedes* this node, and is a sibling.

  

Instance methods
----------------



*This interface also inherits methods from its parents, [`Node`](node) and [`EventTarget`](eventtarget).*

  [`CharacterData.after()`](characterdata/after)   Inserts a set of [`Node`](node) objects or strings in the children list of the `CharacterData`'s parent, just after the `CharacterData` object. 

  [`CharacterData.appendData()`](characterdata/appenddata)  Appends the given string to the `CharacterData.data` string; when this method returns, `data` contains the concatenated string.

  [`CharacterData.before()`](characterdata/before)   Inserts a set of [`Node`](node) objects or strings in the children list of the `CharacterData`'s parent, just before the `CharacterData` object. 

  [`CharacterData.deleteData()`](characterdata/deletedata)  Removes the specified amount of characters, starting at the specified offset, from the `CharacterData.data` string; when this method returns, `data` contains the shortened string.

  [`CharacterData.insertData()`](characterdata/insertdata)  Inserts the specified characters, at the specified offset, in the `CharacterData.data` string; when this method returns, `data` contains the modified string.

  [`CharacterData.remove()`](characterdata/remove)  Removes the object from its parent children list.

  [`CharacterData.replaceData()`](characterdata/replacedata)  Replaces the specified amount of characters, starting at the specified offset, with the specified string; when this method returns, `data` contains the modified string.

  [`CharacterData.replaceWith()`](characterdata/replacewith)  Replaces the characters in the children list of its parent with a set of [`Node`](node) objects or strings.

  [`CharacterData.substringData()`](characterdata/substringdata)  Returns a string containing the part of `CharacterData.data` of the specified length and starting at the specified offset.

  

Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-characterdata](https://dom.spec.whatwg.org/#interface-characterdata) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CharacterData` | 1 | 12 | 1 | 5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `after` | 54 | 17 | 49 | No | 39 | 10 | 54 | 54 | 49 | 41 | 10 | 6.0 |
| `appendData` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `before` | 54 | 17 | 49 | No | 39 | 10 | 54 | 54 | 49 | 41 | 10 | 6.0 |
| `data` | 1 | 12 | 1 | 5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `deleteData` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `insertData` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `length` | 1 | 12 | 1 | 5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `nextElementSibling` | 29 | 17 | 25 | No | 16 | 9 | 4.4 | 29 | 25 | 16 | 9 | 2.0 |
| `previousElementSibling` | 29 | 17 | 25 | No | 16 | 9 | 4.4 | 29 | 25 | 16 | 9 | 2.0 |
| `remove` | 24 | 12 | 23 | No | 15 | 7 | 4.4 | 25 | 23 | 14 | 7 | 1.5 |
| `replaceData` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `replaceWith` | 54 | 17 | 49 | No | 39 | 10 | 54 | 54 | 49 | 41 | 10 | 6.0 |
| `substringData` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* [The DOM overview page](document_object_model).
* The concrete interfaces implemented it: [`Text`](text), [`CDATASection`](cdatasection), [`ProcessingInstruction`](processinginstruction), and [`Comment`](comment).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CharacterData>

Client
======


The `Client` interface represents an executable context such as a [`Worker`](worker), or a [`SharedWorker`](sharedworker). [`Window`](window) clients are represented by the more-specific [`WindowClient`](windowclient). You can get `Client`/`WindowClient` objects from methods such as [`Clients.matchAll()`](clients/matchall) and [`Clients.get()`](clients/get).


Instance methods
----------------


 [`Client.postMessage()`](client/postmessage)  Sends a message to the client.

  
Instance properties
-------------------


 
[`Client.id`](client/id) Read only 
  The universally unique identifier of the client as a string.

  
[`Client.type`](client/type) Read only 
  The client's type as a string. It can be `"window"`, `"worker"`, or `"sharedworker"`.

  
[`Client.url`](client/url) Read only 
  The URL of the client as a string.

  
Specifications
--------------




| Specification |
| --- |
| [Service Workers # client-interface](https://w3c.github.io/ServiceWorker/#client-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Client` | 40 | 17 | 44 | No | 27 | 11.1 | 40 | 40 | 44 | 27 | 11.3 | 4.0 |
| `frameType` | 43 | 17 | 44 | No | 30 | 11.1 | 43 | 43 | 44 | 30 | 11.3 | 4.0 |
| `id` | 40 | 17 | 44 | No | 27 | 11.1 | 40 | 40 | 44 | 27 | 11.3 | 4.0 |
| `postMessage` | 40 | 17 | 44 | No | 27 | 11.1 | 40 | 40 | 44 | 27 | 11.3 | 4.0 |
| `type` | 60 | 17 | 54 | No | 47 | 11.1 | 60 | 60 | 54 | 44 | 11.3 | 8.0 |
| `url` | 40 | 17 | 44 | No | 27 | 11.1 | 40 | 40 | 44 | 27 | 11.3 | 4.0 |


See also
--------


* [Using Service Workers](service_worker_api/using_service_workers)
* [Is ServiceWorker ready?](https://jakearchibald.github.io/isserviceworkerready/)
* [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Client>

Clients
=======


The `Clients` interface provides access to [`Client`](client) objects. Access it via `[`self`](serviceworkerglobalscope).clients` within a [service worker](service_worker_api).


Instance methods
----------------


 [`Clients.get()`](clients/get)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) for a [`Client`](client) matching a given [`id`](client/id).

  [`Clients.matchAll()`](clients/matchall)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) for an array of [`Client`](client) objects. An options argument allows you to control the types of clients returned.

  [`Clients.openWindow()`](clients/openwindow)  Opens a new browser window for a given URL and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) for the new [`WindowClient`](windowclient).

  [`Clients.claim()`](clients/claim)  Allows an active service worker to set itself as the [`controller`](serviceworkercontainer/controller) for all clients within its [`scope`](serviceworkerregistration/scope).

  
Examples
--------



The following example shows an existing chat window or creates a new one when the user clicks a notification.

 
```
addEventListener("notificationclick", (event) => {
  event.waitUntil(
    (async () => {
      const allClients = await clients.matchAll({
        includeUncontrolled: true,
      });

      let chatClient;

      // Let's see if we already have a chat window open:
      for (const client of allClients) {
        const url = new URL(client.url);

        if (url.pathname === "/chat/") {
          // Excellent, let's use it!
          client.focus();
          chatClient = client;
          break;
        }
      }

      // If we didn't find an existing chat window,
      // open a new one:
      if (!chatClient) {
        chatClient = await clients.openWindow("/chat/");
      }

      // Message the client:
      chatClient.postMessage("New chat messages!");
    })()
  );
});

```


Specifications
--------------




| Specification |
| --- |
| [Service Workers # clients-interface](https://w3c.github.io/ServiceWorker/#clients-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Clients` | 40 | 17 | 44 | No | 27 | 11.1 | 40 | 40 | 44 | 27 | 11.3 | 4.0 |
| `claim` | 42 | 17 | 44 | No | 29 | 11.1 | 42 | 42 | 44 | 29 | 11.3 | 4.0 |
| `get` | 51 | 17 | 45 | No | 38 | 11.1 | 51 | 51 | 45 | 41 | 11.3 | 5.0 |
| `matchAll` | 42`Client` objects returned in most recent focus order. | 17`Client` objects returned in most recent focus order. | 5444–54Before Firefox 54, `Client` objects were not returned in the most recent focus order as required by the specification. | No | 29 | 11.1 | 42`Client` objects returned in most recent focus order. | 42`Client` objects returned in most recent focus order. | 5444–54Before Firefox 54, `Client` objects were not returned in the most recent focus order as required by the specification. | 29 | 11.3 | 4.0`Client` objects returned in most recent focus order. |
| `openWindow` | 40["Before Chrome 43, this method could only open URLs on the same origin.", "Since Chrome 51, URLs may open inside an existing browsing context provided by a standalone web app."] | 17 | 44 | No | 38 | 11.1 | 40["Before Chrome 43, this method could only open URLs on the same origin.", "Since Chrome 51, URLs may open inside an existing browsing context provided by a standalone web app."] | 40["Before Chrome 43, this method could only open URLs on the same origin.", "Since Chrome 51, URLs may open inside an existing browsing context provided by a standalone web app."] | 44 | 41 | 11.3 | 4.0["Before Samsung Internet 4.0, this method could only open URLs on the same origin.", "Since Samsung Internet 5.0, URLs may open inside an existing browsing context provided by a standalone web app."] |


See also
--------


* [Using Service Workers](service_worker_api/using_service_workers)
* [Is ServiceWorker ready?](https://jakearchibald.github.io/isserviceworkerready/)
* [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Clients>

Clipboard
=========



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `Clipboard` interface implements the [Clipboard API](clipboard_api), providing—if the user grants permission—both read and write access to the contents of the system clipboard. The Clipboard API can be used to implement cut, copy, and paste features within a web application.


 EventTarget Clipboard The system clipboard is exposed through the global [`Navigator.clipboard`](navigator/clipboard) property.

 Calls to the methods of the `Clipboard` object will not succeed if the user hasn't granted the needed permissions using the [Permissions API](permissions_api) and the `'clipboard-read'` or `'clipboard-write'` permission as appropriate.

  **Note:** In reality, at this time browser requirements for access to the clipboard vary significantly. Please see the section [Clipboard availability](#clipboard_availability) for details.

  All of the Clipboard API methods operate asynchronously; they return a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which is resolved once the clipboard access has been completed. The promise is rejected if clipboard access is denied.



Instance methods
----------------



*`Clipboard` is based on the [`EventTarget`](eventtarget) interface, and includes its methods.*

  [`read()`](clipboard/read)  Requests arbitrary data (such as images) from the clipboard, returning a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with an array of [`ClipboardItem`](clipboarditem) objects containing the clipboard's contents.

  [`readText()`](clipboard/readtext)  Requests text from the system clipboard; returns a `Promise` which is resolved with a string containing the clipboard's text once it's available.

  [`write()`](clipboard/write)  Writes arbitrary data to the system clipboard. This asynchronous operation signals that it's finished by resolving the returned `Promise`.

  [`writeText()`](clipboard/writetext)  Writes text to the system clipboard, returning a `Promise` which is resolved once the text is fully copied into the clipboard.

  

Clipboard availability
----------------------



The asynchronous clipboard API is a relatively recent addition, and the process of implementing it in browsers is not yet complete. Due to both potential security concerns and technical complexities, the process of integrating this API is happening gradually in most browsers. See the [browser compatibility](#browser_compatibility) section below for more information.

 In browser extensions, you can access the system clipboard using the WebExtension [`clipboard`](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/clipboard) API.



Specifications
--------------




| Specification |
| --- |
| [Clipboard API and events # clipboard-interface](https://w3c.github.io/clipboard-apis/#clipboard-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Clipboard` | 66 | 79 | 63 | No | 53 | 13.1 | 66 | 66 | 63 | 47 | 13.4 | 9.0 |
| `read` | 86From version 86, the `text/html` MIME type is supported.76From version 76, the `image/png` MIME type is supported.66Images are not supported. | 79 | 90Firefox only supports reading the clipboard in browser extensions, using the `"clipboardRead"` extension permission. | No | 63 | 13.1 | 84From version 84, the `image/png` MIME type is supported.66Images are not supported. | 86From version 86, the `text/html` MIME type is supported.84From version 84, the `image/png` MIME type is supported.66Images are not supported. | No | 54 | 13.4 | 12.0 |
| `readText` | 66 | 79 | NoFirefox only supports reading the clipboard in browser extensions, using the `"clipboardRead"` extension permission. | No | 53 | 13.1 | 66 | 66 | NoFirefox only supports reading the clipboard in browser extensions, using the `"clipboardRead"` extension permission. | 47 | 13.4 | 9.0 |
| `write` | 66From version 76, the `image/png` MIME type is supported. | 79 | 87Writing to the clipboard is available without permission in secure contexts and browser extensions, but only from user-initiated event callbacks. Browser extensions with the `"clipboardWrite"` permission can write to the clipboard at any time.63["This method accepts a `DataTransfer` object instead of an array of `ClipboardItem` objects.", "Writing to the clipboard is available without permission in secure contexts and browser extensions, but only from user-initiated event callbacks. Browser extensions with the `\"clipboardWrite\"` permission can write to the clipboard at any time."] | No | 63 | 13.1 | 66From version 84, the `image/png` MIME type is supported. | 66From version 84, the `image/png` MIME type is supported. | No | 54 | 13.4 | 12.0 |
| `writeText` | 66 | 79 | 63Writing to the clipboard is available without permission in secure contexts and browser extensions, but only from user-initiated event callbacks. Browser extensions with the `"clipboardWrite"` permission can write to the clipboard at any time. | No | 53 | 13.1Must be called within user gesture event handlers such as `pointerdown` or `pointerup`. | 66 | 66 | 63Writing to the clipboard is available without permission in secure contexts and browser extensions, but only from user-initiated event callbacks. Browser extensions with the `"clipboardWrite"` permission can write to the clipboard at any time. | 47 | 13.4Must be called within user gesture event handlers such as `pointerdown` or `pointerup`. | 9.0 |


See also
--------


* [`Document.execCommand()`](document/execcommand)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Clipboard>

Comment
=======



The `Comment` interface represents textual notations within markup; although it is generally not visually shown, such comments are available to be read in the source view.

 Comments are represented in HTML and XML as content between '`<!--`' and '`-->`'. In XML, like inside SVG or MathML markup, the character sequence '`--`' cannot be used within a comment.


 EventTarget Node CharacterData Comment

Instance properties
-------------------


*This interface has no specific property, but inherits those of its parent, [`CharacterData`](characterdata), and indirectly those of [`Node`](node).*


Constructor
-----------


 [`Comment()`](comment/comment)  Returns a new `Comment` object with the parameter as its textual content. If not present, its default value is the empty string, `''`.

  
Instance methods
----------------


*This interface has no specific method, but inherits those of its parent, [`CharacterData`](characterdata), and indirectly those of [`Node`](node).*


Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-comment](https://dom.spec.whatwg.org/#interface-comment) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Comment` | 29 | 16 | 24 | No | 16 | 8 | 4.4 | 29 | 24 | 16 | 8 | 2.0 |
| `Comment` | 1 | 12 | 1 | 9 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* [The DOM API](document_object_model)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Comment>

CaretPosition
=============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `CaretPosition` interface represents the caret position, an indicator for the text insertion point. You can get a `CaretPosition` using the [`Document.caretPositionFromPoint()`](document/caretpositionfrompoint) method.



Instance properties
-------------------



*This interface doesn't inherit any properties.*

  
`CaretPosition.offsetNode` Read only   Experimental 
  Returns a [`Node`](node) containing the found node at the caret's position.

  
`CaretPosition.offset` Read only   Experimental 
  Returns a `long` representing the character offset in the caret position node.

  

Instance methods
----------------


 
`CaretPosition.getClientRect`  Experimental 
  Returns the client rectangle for the caret range.

  
Specifications
--------------




| Specification |
| --- |
| [CSSOM View Module # caret-position](https://w3c.github.io/csswg-drafts/cssom-view/#caret-position) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CaretPosition` | No | No | 20 | No | No | No | No | No | 20 | No | No | No |
| `getClientRect` | No | No | 23 | No | No | No | No | No | 23 | No | No | No |
| `offset` | No | No | 20 | No | No | No | No | No | 20 | No | No | No |
| `offsetNode` | No | No | 20 | No | No | No | No | No | 20 | No | No | No |


See also
--------


* [`Document.caretPositionFromPoint()`](document/caretpositionfrompoint)
* [`Range`](range)
* [`Node`](node)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CaretPosition>

CDATASection
============



 The `CDATASection` interface represents a CDATA section that can be used within XML to include extended portions of unescaped text. When inside a CDATA section, the symbols `<` and `&` don't need escaping as they normally do. 

 In XML, a CDATA section looks like:

 
```
<![CDATA[ … ]]>

```
 For example:

 
```
<foo>
  Here is a CDATA section: <![CDATA[ < > & ]]> with all kinds of unescaped text.
</foo>

```
  The only sequence which is not allowed within a CDATA section is the closing sequence of a CDATA section itself, `]]>`. 

  **Note:** CDATA sections should not be used within HTML they are considered as comments and not displayed.

 
 EventTarget Node CharacterData Text CDATASection

Instance properties
-------------------


*This interface has no specific properties and implements those of its parent [`Text`](text).*


Instance methods
----------------


*This interface has no specific methods and implements those of its parent [`Text`](text).*


Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-cdatasection](https://dom.spec.whatwg.org/#interface-cdatasection) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CDATASection` | 1 | 12 | 1 | 9 | ≤12.1 | 3 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* [`Document.createCDATASection()`](document/createcdatasection)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CDATASection>

ChannelMergerNode
=================



The `ChannelMergerNode` interface, often used in conjunction with its opposite, [`ChannelSplitterNode`](channelsplitternode), reunites different mono inputs into a single output. Each input is used to fill a channel of the output. This is useful for accessing each channels separately, e.g. for performing channel mixing where gain must be separately controlled on each channel.

  ![Default channel merger node with six mono inputs combining to form a single output.] 

 If `ChannelMergerNode` has one single output, but as many inputs as there are channels to merge; the number of inputs is defined as a parameter of its constructor and the call to [`AudioContext.createChannelMerger()`](baseaudiocontext/createchannelmerger). In the case that no value is given, it will default to `6`.

 Using a `ChannelMergerNode`, it is possible to create outputs with more channels than the rendering hardware is able to process. In that case, when the signal is sent to the [`AudioContext.listener`](baseaudiocontext/listener) object, supernumerary channels will be ignored.


 EventTarget AudioNode ChannelMergerNode 

|  |  |
| --- | --- |
| Number of inputs | variable; default to `6`. |
| Number of outputs | `1` |
| Channel count mode | `"explicit"` |
| Channel count | `2` (not used in the default count mode) |
| Channel interpretation | `"speakers"` |



Constructor
-----------


 [`ChannelMergerNode()`](channelmergernode/channelmergernode)  Creates a new `ChannelMergerNode` object instance.

  
Instance properties
-------------------


*No specific property; inherits properties from its parent, [`AudioNode`](audionode)*.


Instance methods
----------------


*No specific method; inherits methods from its parent, [`AudioNode`](audionode)*.


Example
-------


See [`BaseAudioContext.createChannelMerger()`](baseaudiocontext/createchannelmerger#examples) for example code.


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # ChannelMergerNode](https://webaudio.github.io/web-audio-api/#ChannelMergerNode) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ChannelMergerNode` | 55 | 79 | 53 | No | 42 | 14.1 | 55 | 55 | 53 | 42 | 14.5 | 6.0 |
| `ChannelMergerNode` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ChannelMergerNode>

ClipboardEvent
==============



The `ClipboardEvent` interface represents events providing information related to modification of the clipboard, that is [`cut`](element/cut_event), [`copy`](element/copy_event), and [`paste`](element/paste_event) events.


 Event ClipboardEvent

Constructor
-----------


 [`ClipboardEvent()`](clipboardevent/clipboardevent)  Creates a `ClipboardEvent` event with the given parameters.

  
Instance properties
-------------------



*Also inherits properties from its parent [`Event`](event)*.

  
[`ClipboardEvent.clipboardData`](clipboardevent/clipboarddata) Read only 
  A [`DataTransfer`](datatransfer) object containing the data affected by the user-initiated [`cut`](element/cut_event), [`copy`](element/copy_event), or [`paste`](element/paste_event) operation, along with its MIME type.

  

Instance methods
----------------


*No specific methods; inherits methods from its parent [`Event`](event)*.


Specifications
--------------




| Specification |
| --- |
| [Clipboard API and events # clipboard-event-interfaces](https://w3c.github.io/clipboard-apis/#clipboard-event-interfaces) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ClipboardEvent` | 58 | 17 | 22 | No | 45 | 10.1 | 58 | 58 | 22 | 43 | 10.3 | 7.0 |
| `ClipboardEvent` | 41 | 12 | 22 | 4 | 28 | 10.1 | 41 | 41 | 22 | 28 | 10.3 | 4.0 |
| `clipboardData` | 41 | 12 | 22 | 5 | 28 | 10.1 | 41 | 41 | 22 | 28 | 10.3 | 4.0 |


See also
--------


* Copy-related events: [`copy`](element/copy_event), [`cut`](element/cut_event), [`paste`](element/paste_event)
* [Clipboard API](clipboard_api)
* [Async Clipboard API demo on Glitch](https://async-clipboard-api.glitch.me/)
* [Image support for Async Clipboard article](https://web.dev/async-clipboard/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ClipboardEvent>

ClipboardItem
=============



The `ClipboardItem` interface of the [`Clipboard API`](clipboard_api) represents a single item format, used when reading or writing data via the [`Clipboard API`](clipboard_api). That is [`clipboard.read()`](clipboard/read) and [`clipboard.write()`](clipboard/write) respectively.

 The benefit of having the `ClipboardItem` interface to represent data, is that it enables developers to cope with the varying scope of file types and data easily.

 Access to the contents of the clipboard is gated behind the [Permissions API](permissions_api): The `clipboard-write` permission is granted automatically to pages when they are in the active tab. The `clipboard-read` permission must be requested, which you can do by trying to read data from the clipboard.

  **Note:** To work with text see the [`Clipboard.readText()`](clipboard/readtext) and [`Clipboard.writeText()`](clipboard/writetext) methods of the [`Clipboard`](clipboard) interface.

   **Note:** You can only pass in one clipboard item at a time.

 

Constructor
-----------


 [`ClipboardItem()`](clipboarditem/clipboarditem)  Creates a new `ClipboardItem` object, with the [MIME type](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type) as the key and [`Blob`](blob) as the value.

  
Instance properties
-------------------



*This interface provides the following properties.*

  
[`types`](clipboarditem/types) Read only 
  Returns an [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of MIME types available within the `ClipboardItem`.

  
[`presentationStyle`](clipboarditem/presentationstyle) Read only 
  Returns one of the following: `"unspecified"`, `"inline"` or `"attachment"`.

  

Instance methods
----------------



*This interface defines the following methods.*

  [`getType()`](clipboarditem/gettype)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with a [`Blob`](blob) of the requested [MIME type](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type), or an error if the MIME type is not found.

  

Examples
--------


### Writing To Clipboard



Here we're writing a new [`ClipboardItem()`](clipboarditem/clipboarditem) to the [`clipboard`](clipboard_api) by requesting a png image using the [`Fetch API`](fetch_api), and in turn, the [`responses' blob()`](response/blob) method, to create the new [`ClipboardItem`](clipboarditem).

 
```
async function writeClipImg() {
  try {
    const imgURL = "/myimage.png";
    const data = await fetch(imgURL);
    const blob = await data.blob();

    await navigator.clipboard.write([
      new ClipboardItem({
        [blob.type]: blob,
      }),
    ]);
    console.log("Fetched image copied.");
  } catch (err) {
    console.error(err.name, err.message);
  }
}

```


### Reading From The Clipboard



Here we're returning all items on the clipboard via the [`clipboard.read()`](clipboard/read) method. Then utilizing the [`ClipboardItem.types`](clipboarditem/types) property to set the [`getType()`](clipboarditem/gettype) argument and return the corresponding blob object.

 
```
async function getClipboardContents() {
  try {
    const clipboardItems = await navigator.clipboard.read();

    for (const clipboardItem of clipboardItems) {
      for (const type of clipboardItem.types) {
        const blob = await clipboardItem.getType(type);
        // we can now use blob here
      }
    }
  } catch (err) {
    console.error(err.name, err.message);
  }
}

```


Specifications
--------------




| Specification |
| --- |
| [Clipboard API and events # clipboarditem](https://w3c.github.io/clipboard-apis/#clipboarditem) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ClipboardItem` | 9876–98The `ClipboardItem` constructor only accepts a blob as the item data, but not strings or Promises that resolve to strings or blobs. See [bug 1014310](https://crbug.com/1014310). | 9879–98The `ClipboardItem` constructor only accepts a blob as the item data, but not strings or Promises that resolve to strings or blobs. See [bug 1014310](https://crbug.com/1014310). | 87 | No | 8463–84The `ClipboardItem` constructor only accepts a blob as the item data, but not strings or Promises that resolve to strings or blobs. See [bug 1014310](https://crbug.com/1014310). | 13.1 | 9884–98The `ClipboardItem` constructor only accepts a blob as the item data, but not strings or Promises that resolve to strings or blobs. See [bug 1014310](https://crbug.com/1014310). | 9884–98The `ClipboardItem` constructor only accepts a blob as the item data, but not strings or Promises that resolve to strings or blobs. See [bug 1014310](https://crbug.com/1014310). | No | 6860–68The `ClipboardItem` constructor only accepts a blob as the item data, but not strings or Promises that resolve to strings or blobs. See [bug 1014310](https://crbug.com/1014310). | 13.4 | 18.014.0–18.0The `ClipboardItem` constructor only accepts a blob as the item data, but not strings or Promises that resolve to strings or blobs. See [bug 1014310](https://crbug.com/1014310). |
| `ClipboardItem` | 76 | 79 | 87 | No | 63 | 13.1 | 84 | 84 | No | 60 | 13.4 | 14.0 |
| `getType` | 76 | 79 | 87 | No | 63 | 13.1 | 84 | 84 | No | 60 | 13.4 | 14.0 |
| `presentationStyle` | No | No | 87 | No | No | 13.1 | 84 | 84 | No | 60 | 13.4 | 14.0 |
| `types` | 76 | 79 | 87 | No | 63 | 13.1 | 84 | 84 | No | 60 | 13.4 | 14.0 |


See also
--------


* [Clipboard API](clipboard_api)
* [Async Clipboard API demo on Glitch](https://async-clipboard-api.glitch.me/)
* [Image support for Async Clipboard article](https://web.dev/async-clipboard/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ClipboardItem>

CloseEvent
==========



A `CloseEvent` is sent to clients using [WebSockets](https://developer.mozilla.org/en-US/docs/Glossary/WebSockets) when the connection is closed. This is delivered to the listener indicated by the `WebSocket` object's `onclose` attribute.


 Event CloseEvent

Constructor
-----------


 [`CloseEvent()`](closeevent/closeevent)  Creates a new `CloseEvent`.

  
Instance properties
-------------------



*This interface also inherits properties from its parent, [`Event`](event).*

  
[`CloseEvent.code`](closeevent/code) Read only 
  Returns an `unsigned short` containing the close code sent by the server.

  
[`CloseEvent.reason`](closeevent/reason) Read only 
  Returns a string indicating the reason the server closed the connection. This is specific to the particular server and sub-protocol.

  
[`CloseEvent.wasClean`](closeevent/wasclean) Read only 
  Returns a boolean value that Indicates whether or not the connection was cleanly closed.

  

Instance methods
----------------


*This interface also inherits methods from its parent, [`Event`](event).*


Specifications
--------------




| Specification |
| --- |
| [WebSockets Standard # the-closeevent-interface](https://websockets.spec.whatwg.org/#the-closeevent-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CloseEvent` | 16 | 14 | 11 | No | 12.1 | 6 | 4.4 | 18 | 14 | 12.1 | 6 | 1.0 |
| `CloseEvent` | 15 | 12 | 8["Before Firefox 12, the close code `CLOSE_NORMAL` was used when the channel was closed due to an unexpected error or unspecified error condition.", "Before Firefox 8, the `WebSocket` close event was sent to the listener as a simple event."] | 10 | 12.1 | 6 | 4.4 | 18 | 8 | 12.1 | 6 | 1.0 |
| `code` | 15 | 12 | 8 | 10 | 12.1 | 6 | 4.4 | 18 | 8 | 12.1 | 6 | 1.0 |
| `reason` | 15 | 12 | 8 | 10 | 12.1 | 6 | 4.4 | 18 | 8 | 12.1 | 6 | 1.0 |
| `wasClean` | 15 | 12 | 8 | 10 | 12.1 | 6 | 4.4 | 18 | 8 | 12.1 | 6 | 1.0 |


See also
--------


* [`WebSocket`](websocket)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent>

ConstantSourceNode
==================



The `ConstantSourceNode` interface—part of the Web Audio API—represents an audio source (based upon [`AudioScheduledSourceNode`](audioscheduledsourcenode)) whose output is single unchanging value. This makes it useful for cases in which you need a constant value coming in from an audio source. In addition, it can be used like a constructible [`AudioParam`](audioparam) by automating the value of its [`offset`](constantsourcenode/offset) or by connecting another node to it; see [Controlling multiple parameters with ConstantSourceNode](web_audio_api/controlling_multiple_parameters_with_constantsourcenode).

 A `ConstantSourceNode` has no inputs and exactly one monaural (one-channel) output. The output's value is always the same as the value of the [`offset`](constantsourcenode/offset) parameter.


 EventTarget AudioNode AudioScheduledSourceNode ConstantSourceNode 

|  |  |
| --- | --- |
| Number of inputs | `0` |
| Number of outputs | `1` |



Constructor
-----------


 [`ConstantSourceNode()`](constantsourcenode/constantsourcenode)  Creates and returns a new `ConstantSourceNode` instance, optionally specifying an object which establishes initial values for the object's properties. As an alternative, you can use the [`BaseAudioContext.createConstantSource()`](baseaudiocontext/createconstantsource) factory method; see [Creating an AudioNode](audionode#creating_an_audionode).

  
Instance properties
-------------------



*Inherits properties from its parent interface, [`AudioScheduledSourceNode`](audioscheduledsourcenode), and adds the following properties:*

  [`offset`](constantsourcenode/offset)  An [`AudioParam`](audioparam) which specifies the value that this source continuously outputs. The default value is 1.0.

  

### Events



*Inherits events from its parent interface, [`AudioScheduledSourceNode`](audioscheduledsourcenode).*

  **Note:** Some browsers' implementations of these events are part of the [`AudioScheduledSourceNode`](audioscheduledsourcenode) interface.

   [`ended`](audioscheduledsourcenode/ended_event)  Fired whenever the [`ConstantSourceNode`](constantsourcenode) data has stopped playing.

  

Instance methods
----------------



*Inherits methods from its parent interface, [`AudioScheduledSourceNode`](audioscheduledsourcenode).*

  **Note:** Some browsers' implementations of these methods are part of the [`AudioScheduledSourceNode`](audioscheduledsourcenode) interface.

   [`start()`](audioscheduledsourcenode/start)  Schedules a sound to playback at an exact time.

  [`stop()`](audioscheduledsourcenode/stop)  Schedules a sound to stop playback at an exact time.

  

Example
-------



In the article [Controlling multiple parameters with ConstantSourceNode](web_audio_api/controlling_multiple_parameters_with_constantsourcenode), a `ConstantSourceNode` is created to allow one slider control to change the gain on two [`GainNode`](gainnode)s. The three nodes are set up like this:

 
```
gainNode2 = context.createGain();
gainNode3 = context.createGain();
gainNode2.gain.value = gainNode3.gain.value = 0.5;
volumeSliderControl.value = gainNode2.gain.value;

constantNode = context.createConstantSource();
constantNode.connect(gainNode2.gain);
constantNode.connect(gainNode3.gain);
constantNode.start();

gainNode2.connect(context.destination);
gainNode3.connect(context.destination);

```
 This code starts by creating the gain nodes and setting them and the volume control that will adjust their value all to 0.5. Then the `ConstantSourceNode` is created by calling [`AudioContext.createConstantSource()`](baseaudiocontext/createconstantsource), and the gain parameters of each of the two gain nodes are connected to the `ConstantSourceNode`. After starting the constant source by calling its [`start()`](audioscheduledsourcenode/start) method. Finally, the two gain nodes are connected to the audio destination (typically speakers or headphones).

 Now, whenever the value of [`constantNode.offset`](constantsourcenode/offset) changes, the gain on both `gainNode2` and `gainNode3` will change to have that same value.

 To see this example in action, as well as to read the rest of the code from which these snippets were derived, see [Controlling multiple parameters with ConstantSourceNode.](web_audio_api/controlling_multiple_parameters_with_constantsourcenode)



Specifications
--------------




| Specification |
| --- |
| [Web Audio API # ConstantSourceNode](https://webaudio.github.io/web-audio-api/#ConstantSourceNode) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ConstantSourceNode` | 56 | 79 | 52 | No | 43 | 14.1 | 56 | 56 | 52 | 43 | 14.5 | 6.0 |
| `ConstantSourceNode` | 56 | 79 | 52 | No | 43 | 14.1 | 56 | 56 | 52 | 43 | 14.5 | 6.0 |
| `offset` | 56 | 79 | 52 | No | 43 | 14.1 | 56 | 56 | 52 | 43 | 14.5 | 6.0 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)
* [`AudioScheduledSourceNode`](audioscheduledsourcenode)
* [`AudioNode`](audionode)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ConstantSourceNode>

ContentIndex
============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `ContentIndex` interface of the [Content Index API](content_index_api) allows developers to register their offline enabled content with the browser.



Instance properties
-------------------


There are no properties of this interface.


Instance methods
----------------


 
[`ContentIndex.add()`](contentindex/add)  Experimental 
  Registers an item with the [content index](content_index_api).

  
[`ContentIndex.delete()`](contentindex/delete)  Experimental 
  Unregisters an item from the currently indexed content.

  
[`ContentIndex.getAll()`](contentindex/getall)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with an iterable list of content index entries.

  
Examples
--------


### Feature detection and interface access



Here we get a reference to the [`ServiceWorkerRegistration`](serviceworkerregistration), then check for the `index` property, which gives us access to the content index interface.

 
```
// reference registration
const registration = await navigator.serviceWorker.ready;

// feature detection
if ("index" in registration) {
  // Content Index API functionality
  const contentIndex = registration.index;
}

```


### Adding to the content index



Here we're declaring an item in the correct format and creating an asynchronous function which uses the [`add()`](contentindex/add) method to register it with the [content index](content_index_api).

 
```
// our content
const item = {
  id: "post-1",
  url: "/posts/amet.html",
  title: "Amet consectetur adipisicing",
  description:
    "Repellat et quia iste possimus ducimus aliquid a aut eaque nostrum.",
  icons: [
    {
      src: "/media/dark.png",
      sizes: "128x128",
      type: "image/png",
    },
  ],
  category: "article",
};

// our asynchronous function to add indexed content
async function registerContent(data) {
  const registration = await navigator.serviceWorker.ready;

  // feature detect Content Index
  if (!registration.index) {
    return;
  }

  // register content
  try {
    await registration.index.add(data);
  } catch (e) {
    console.log("Failed to register content: ", e.message);
  }
}

```


### Retrieving items within the current index



The below example shows an asynchronous function that retrieves items within the [content index](content_index_api) and iterates over each entry, building a list for the interface.

 
```
async function createReadingList() {
  // access our service worker registration
  const registration = await navigator.serviceWorker.ready;

  // get our index entries
  const entries = await registration.index.getAll();

  // create a containing element
  const readingListElem = document.createElement("div");

  // test for entries
  if (!Array.length) {
    // if there are no entries, display a message
    const message = document.createElement("p");
    message.innerText =
      "You currently have no articles saved for offline reading.";

    readingListElem.append(message);
  } else {
    // if entries are present, display in a list of links to the content
    const listElem = document.createElement("ul");

    for (const entry of entries) {
      const listItem = document.createElement("li");

      const anchorElem = document.createElement("a");
      anchorElem.innerText = entry.title;
      anchorElem.setAttribute("href", entry.url);

      listElem.append(listItem);
    }

    readingListElem.append(listElem);
  }
}

```


### Unregistering indexed content



Below is an asynchronous function, that removes an item from the [content index](content_index_api).

 
```
async function unregisterContent(article) {
  // reference registration
  const registration = await navigator.serviceWorker.ready;

  // feature detect Content Index
  if (!registration.index) return;

  // unregister content from index
  await registration.index.delete(article.id);
}

```
 All the above methods are available within the scope of the [service worker](serviceworker). They are accessible from the [`WorkerGlobalScope.self`](workerglobalscope/self) property:

 
```
// service worker script

self.registration.index.add(item);

self.registration.index.delete(item.id);

const contentIndexItems = self.registration.index.getAll();

```


Specifications
--------------




| Specification |
| --- |
| [Content Index # content-index](https://wicg.github.io/content-index/spec/#content-index) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ContentIndex` | No | No | No | No | No | No | 84 | 84 | No | 60 | No | 14.0 |
| `add` | No | No | No | No | No | No | 84 | 84 | No | 60 | No | 14.0 |
| `delete` | No | No | No | No | No | No | 84 | 84 | No | 60 | No | 14.0 |
| `getAll` | No | No | No | No | No | No | 84 | 84 | No | 60 | No | 14.0 |


See also
--------


* [An introductory article on the Content Index API](https://web.dev/content-indexing-api/)
* [An app which uses the Content Index API to list and remove 'save for later' content](https://contentindex.dev/)
* [Service Worker API, along with information about Cache and CacheStorage](service_worker_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ContentIndex>

ContentIndexEvent
=================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `ContentIndexEvent` interface of the [content index](content_index_api) defines the object used to represent the [`contentdelete`](serviceworkerglobalscope/contentdelete_event) event.

 This event is sent to the [global scope](serviceworkerglobalscope) of a [`ServiceWorker`](serviceworker). It contains the id of the indexed content to be removed.

 The [`contentdelete`](serviceworkerglobalscope/contentdelete_event) event is only fired when the deletion happens due to interaction with the browser's built-in user interface. It is not fired when the [`ContentIndex.delete`](contentindex/delete) method is called.


 Event ExtendableEvent ContentIndexEvent

Constructor
-----------


 
[`ContentIndexEvent()`](contentindexevent/contentindexevent)  Experimental 
  Creates and returns a new `ContentIndexEvent` object whose type and other options are configured as specified.

  
Instance properties
-------------------



*In addition to the properties listed below, this interface inherits the properties of its parent interface, [`ExtendableEvent`](extendableevent).*

  
[`id`](contentindexevent/id) Read only   Experimental 
  A [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) which identifies the deleted content index via it's `id`.

  

Instance methods
----------------


*While `ContentIndexEvent` offers no methods of its own, it inherits any specified by its parent interface, [`ExtendableEvent`](extendableevent).*


Examples
--------



This example shows the [service worker](serviceworker) script listening for the [`contentdelete`](serviceworkerglobalscope/contentdelete_event) event and logs the removed content index id.

 
```
self.addEventListener("contentdelete", (event) => {
  console.log(event.id);

  // logs content index id, which can then be used to determine what content to delete from your cache
});

```


Specifications
--------------




| Specification |
| --- |
| [Content Index # content-index-event](https://wicg.github.io/content-index/spec/#content-index-event) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ContentIndexEvent` | No | No | No | No | No | No | 84 | 84 | No | 60 | No | 14.0 |
| `ContentIndexEvent` | No | No | No | No | No | No | 84 | 84 | No | 60 | No | 14.0 |
| `id` | No | No | No | No | No | No | 84 | 84 | No | 60 | No | 14.0 |


See also
--------


* [An introductory article on the Content Index API](https://web.dev/content-indexing-api/)
* [An app which uses the Content Index API to list and remove 'save for later' content](https://contentindex.dev/)
* [Service Worker API, along with information about Cache and CacheStorage](service_worker_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ContentIndexEvent>

CompositionEvent
================



The DOM `CompositionEvent` represents events that occur due to the user indirectly entering text.


 Event UIEvent CompositionEvent

Constructor
-----------


 [`CompositionEvent()`](compositionevent/compositionevent)  Creates a new `CompositionEvent` object instance.

  
Instance properties
-------------------



*This interface also inherits properties of its parent, [`UIEvent`](uievent), and its ancestor — [`Event`](event).*

  
[`CompositionEvent.data`](compositionevent/data) Read only 
  Returns the characters generated by the input method that raised the event; its varies depending on the type of event that generated the `CompositionEvent` object.

  
[`CompositionEvent.locale`](compositionevent/locale) Read only   Deprecated   Non-standard 
  Returns the locale of current input method (for example, the keyboard layout locale if the composition is associated with IME).

  

Instance methods
----------------



*This interface also inherits methods of its parent, [`UIEvent`](uievent), and its ancestor — [`Event`](event).*

  
[`CompositionEvent.initCompositionEvent()`](compositionevent/initcompositionevent)  Deprecated 
  Initializes the attributes of a `CompositionEvent` object.

  

Specifications
--------------




| Specification |
| --- |
| [UI Events # interface-compositionevent](https://w3c.github.io/uievents/#interface-compositionevent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CompositionEvent` | 26 | 12 | 53 | No | 15 | 7 | 4.4 | 26 | 53 | 14 | 7 | 1.5 |
| `CompositionEvent` | 15 | 12 | 9 | 9 | 15 | 5 | 4.4 | 18 | 9 | 14 | 5 | 1.0 |
| `data` | 15 | 12 | 9 | 9 | 15 | 5 | ≤37 | 18 | 9 | 14 | 5 | 1.0 |
| `initCompositionEvent` | 15 | 12 | 9 | 9 | 15 | 5 | 4.4 | 18 | 9 | 14 | 5 | 1.5 |
| `locale` | No | 12–79 | 9 | 9 | No | No | No | No | 9 | No | No | No |


See also
--------


* [compositionstart](element/compositionstart_event)
* [compositionend](element/compositionend_event)
* [compositionupdate](element/compositionupdate_event)
* [UIEvent](uievent)
* [Event](event)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent>

CompressionStream
=================


The `CompressionStream` interface of the [Compression Streams API](compression_streams_api) is an API for compressing a stream of data.


Constructor
-----------


 [`CompressionStream()`](compressionstream/compressionstream)  Creates a new `CompressionStream`

  
Instance properties
-------------------


 [`CompressionStream.readable`](compressionstream/readable)  Returns the [`ReadableStream`](readablestream) instance controlled by this object.

  [`CompressionStream.writable`](compressionstream/writable)  Returns the [`WritableStream`](writablestream) instance controlled by this object.

  
Examples
--------



In this example a stream is compressed using gzip compression.

 
```
const compressedReadableStream = inputReadableStream.pipeThrough(
  new CompressionStream("gzip")
);

```


Specifications
--------------




| Specification |
| --- |
| [Compression Streams # compression-stream](https://wicg.github.io/compression/#compression-stream) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CompressionStream` | 80 | 80 | No | No | 67 | 16.4 | 80 | 80 | No | 57 | 16.4 | 13.0 |
| `CompressionStream` | 80 | 80 | No | No | 67 | 16.4 | 80 | 80 | No | 57 | 16.4 | 13.0 |
| `readable` | 80 | 80 | No | No | 67 | 16.4 | 80 | 80 | No | 57 | 16.4 | 13.0 |
| `writable` | 80 | 80 | No | No | 67 | 16.4 | 80 | 80 | No | 57 | 16.4 | 13.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CompressionStream>

console
=======



 The `console` object provides access to the browser's debugging console (e.g. the [Web console](https://firefox-source-docs.mozilla.org/devtools-user/web_console/index.html) in Firefox). The specifics of how it works varies from browser to browser, but there is a *de facto* set of features that are typically provided. 

  The `console` object can be accessed from any global object. [`Window`](window) on browsing scopes and [`WorkerGlobalScope`](workerglobalscope) as specific variants in workers via the property console. It's exposed as [`Window.console`](window/console), and can be referenced as `console`. For example: 

 
```
console.log("Failed to open the specified link");

```
  This page documents the [Methods](#methods) available on the `console` object and gives a few [Usage](#usage) examples. 


 **Note:** This feature is available in [Web Workers](web_workers_api)

   **Note:** Certain online IDEs and editors may implement the console API differently than the browsers. As a result, certain functionality of the console API, such as the timer methods, may not be outputted in the console of online IDEs or editors. Always open your browser's DevTools console to see the logs as shown in this documentation.

 

Instance methods
----------------


 [`console.assert()`](console/assert)  Log a message and stack trace to console if the first argument is `false`.

  [`console.clear()`](console/clear)  Clear the console.

  [`console.count()`](console/count)  Log the number of times this line has been called with the given label.

  [`console.countReset()`](console/countreset)  Resets the value of the counter with the given label.

  [`console.debug()`](console/debug)  Outputs a message to the console with the log level `debug`.

  [`console.dir()`](console/dir)  Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects.

  [`console.dirxml()`](console/dirxml)  Displays an XML/HTML Element representation of the specified object if possible or the JavaScript Object view if it is not possible.

  [`console.error()`](console/error)  Outputs an error message. You may use [string substitution](#using_string_substitutions) and additional arguments with this method.

  
`console.exception()`  Non-standard   Deprecated 
  An alias for `error()`.

  [`console.group()`](console/group)  Creates a new inline [group](#using_groups_in_the_console), indenting all following output by another level. To move back out a level, call `groupEnd()`.

  [`console.groupCollapsed()`](console/groupcollapsed)  Creates a new inline [group](#using_groups_in_the_console), indenting all following output by another level. However, unlike `group()` this starts with the inline group collapsed requiring the use of a disclosure button to expand it. To move back out a level, call `groupEnd()`.

  [`console.groupEnd()`](console/groupend)  Exits the current inline [group](#using_groups_in_the_console).

  [`console.info()`](console/info)  Informative logging of information. You may use [string substitution](#using_string_substitutions) and additional arguments with this method.

  [`console.log()`](console/log)  For general output of logging information. You may use [string substitution](#using_string_substitutions) and additional arguments with this method.

  
[`console.profile()`](console/profile)  Non-standard 
  Starts the browser's built-in profiler (for example, the [Firefox performance tool](https://firefox-source-docs.mozilla.org/devtools-user/performance/index.html)). You can specify an optional name for the profile.

  
[`console.profileEnd()`](console/profileend)  Non-standard 
  Stops the profiler. You can see the resulting profile in the browser's performance tool (for example, the [Firefox performance tool](https://firefox-source-docs.mozilla.org/devtools-user/performance/index.html)).

  [`console.table()`](console/table)  Displays tabular data as a table.

  [`console.time()`](console/time)  Starts a [timer](#timers) with a name specified as an input parameter. Up to 10,000 simultaneous timers can run on a given page.

  [`console.timeEnd()`](console/timeend)  Stops the specified [timer](#timers) and logs the elapsed time in milliseconds since it started.

  [`console.timeLog()`](console/timelog)  Logs the value of the specified [timer](#timers) to the console.

  
[`console.timeStamp()`](console/timestamp)  Non-standard 
  Adds a marker to the browser performance tool's timeline ([Chrome](https://developer.chrome.com/docs/devtools/evaluate-performance/reference/) or [Firefox](https://profiler.firefox.com/docs/#/./guide-ui-tour-timeline)).

  [`console.trace()`](console/trace)  Outputs a [stack trace](#stack_traces).

  [`console.warn()`](console/warn)  Outputs a warning message. You may use [string substitution](#using_string_substitutions) and additional arguments with this method.

  
Examples
--------


### Outputting text to the console



The most frequently-used feature of the console is logging of text and other data. There are several categories of output you can generate, using the [`console.log()`](console/log), [`console.info()`](console/info), [`console.warn()`](console/warn), [`console.error()`](console/error), or [`console.debug()`](console/debug) methods. Each of these results in output styled differently in the log, and you can use the filtering controls provided by your browser to only view the kinds of output that interest you.

 There are two ways to use each of the output methods; you can pass in a list of objects whose string representations get concatenated into one string, then output to the console, or you can pass in a string containing zero or more substitution strings followed by a list of objects to replace them.

 #### Outputting a single object

 The simplest way to use the logging methods is to output a single object:

 
```
const someObject = { str: "Some text", id: 5 };
console.log(someObject);

```
 The output looks something like this:

 
```
{str:"Some text", id:5}

```
 #### Outputting multiple objects

 You can also output multiple objects by listing them when calling the logging method, like this:

 
```
const car = "Dodge Charger";
const someObject = { str: "Some text", id: 5 };
console.info("My first car was a", car, ". The object is:", someObject);

```
 The output will look like this:

 
```
My first car was a Dodge Charger. The object is: {str:"Some text", id:5}

```
 #### Using string substitutions

 When passing a string to one of the `console` object's methods that accepts a string (such as `log()`), you may use these substitution strings:

  
`%o` or `%O`
  Outputs a JavaScript object. Clicking the object name opens more information about it in the inspector.

  
`%d` or `%i`
  Outputs an integer. Number formatting is supported, for example `console.log("Foo %.2d", 1.1)` will output the number as two significant figures with a leading 0: `Foo 01`.

  `%s`  Outputs a string.

  `%f`  Outputs a floating-point value. Formatting is supported, for example `console.log("Foo %.2f", 1.1)` will output the number to 2 decimal places: `Foo 1.10`.

    **Note:** Precision formatting doesn't work in Chrome.

  Each of these pulls the next argument after the format string off the parameter list. For example:

 
```
for (let i = 0; i < 5; i++) {
  console.log("Hello, %s. You've called me %d times.", "Bob", i + 1);
}

```
 The output looks like this:

 
```
Hello, Bob. You've called me 1 times.
Hello, Bob. You've called me 2 times.
Hello, Bob. You've called me 3 times.
Hello, Bob. You've called me 4 times.
Hello, Bob. You've called me 5 times.

```
 #### Styling console output

 You can use the `%c` directive to apply a CSS style to console output:

 
```
console.log(
  "This is %cMy stylish message",
  "color: yellow; font-style: italic; background-color: blue;padding: 2px"
);

```
 The text before the directive will not be affected, but the text after the directive will be styled using the CSS declarations in the parameter.

  ![Styled Text in Firefox console] 

 You may use `%c` multiple times:

 
```
console.log(
  "Multiple styles: %cred %corange",
  "color: red",
  "color: orange",
  "Additional unformatted message"
);

```
 The properties usable along with the `%c` syntax are as follows (at least, in Firefox — they may differ in other browsers):

 * [`background`](https://developer.mozilla.org/en-US/docs/Web/CSS/background) and its longhand equivalents
* [`border`](https://developer.mozilla.org/en-US/docs/Web/CSS/border) and its longhand equivalents
* [`border-radius`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius)
* [`box-decoration-break`](https://developer.mozilla.org/en-US/docs/Web/CSS/box-decoration-break)
* [`box-shadow`](https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow)
* [`clear`](https://developer.mozilla.org/en-US/docs/Web/CSS/clear) and [`float`](https://developer.mozilla.org/en-US/docs/Web/CSS/float)
* [`color`](https://developer.mozilla.org/en-US/docs/Web/CSS/color)
* [`cursor`](https://developer.mozilla.org/en-US/docs/Web/CSS/cursor)
* [`display`](https://developer.mozilla.org/en-US/docs/Web/CSS/display)
* [`font`](https://developer.mozilla.org/en-US/docs/Web/CSS/font) and its longhand equivalents
* [`line-height`](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height)
* [`margin`](https://developer.mozilla.org/en-US/docs/Web/CSS/margin)
* [`outline`](https://developer.mozilla.org/en-US/docs/Web/CSS/outline) and its longhand equivalents
* [`padding`](https://developer.mozilla.org/en-US/docs/Web/CSS/padding)
* `text-*` properties such as [`text-transform`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-transform)
* [`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space)
* [`word-spacing`](https://developer.mozilla.org/en-US/docs/Web/CSS/word-spacing) and [`word-break`](https://developer.mozilla.org/en-US/docs/Web/CSS/word-break)
* [`writing-mode`](https://developer.mozilla.org/en-US/docs/Web/CSS/writing-mode)

  **Note:** The console message behaves like an inline element by default. To see the effects of `padding`, `margin`, etc. you should set it to for example `display: inline-block`.

 

### Using groups in the console



You can use nested groups to help organize your output by visually combining related material. To create a new nested block, call `console.group()`. The `console.groupCollapsed()` method is similar but creates the new block collapsed, requiring the use of a disclosure button to open it for reading.

 To exit the current group, call `console.groupEnd()`. For example, given this code:

 
```
console.log("This is the outer level");
console.group("First group");
console.log("In the first group");
console.group("Second group");
console.log("In the second group");
console.warn("Still in the second group");
console.groupEnd();
console.log("Back to the first group");
console.groupEnd();
console.debug("Back to the outer level");

```
 The output looks like this:

  ![Demo of nested groups in Firefox console] 



### Timers



You can start a timer to calculate the duration of a specific operation. To start one, call the `console.time()` method, giving it a name as the only parameter. To stop the timer, and to get the elapsed time in milliseconds, just call the `console.timeEnd()` method, again passing the timer's name as the parameter. Up to 10,000 timers can run simultaneously on a given page.

 For example, given this code:

 
```
console.time("answer time");
alert("Click to continue");
console.timeLog("answer time");
alert("Do a bunch of other stuff…");
console.timeEnd("answer time");

```
 Will log the time needed by the user to dismiss the alert box, log the time to the console, wait for the user to dismiss the second alert, and then log the ending time to the console:

  ![Time log in Firefox console] 

 Notice that the timer's name is displayed both when the timer is started and when it's stopped.

   **Note:** It's important to note that if you're using this to log the timing for network traffic, the timer will report the total time for the transaction, while the time listed in the network panel is just the amount of time required for the header. If you have response body logging enabled, the time listed for the response header and body combined should match what you see in the console output. 

 

### Stack traces



The console object also supports outputting a stack trace; this will show you the call path taken to reach the point at which you call [`console.trace()`](console/trace). Given code like this:

 
```
function foo() {
  function bar() {
    console.trace();
  }
  bar();
}

foo();

```
 The output in the console looks something like this:

  ![Stack trace in Firefox console] 



Specifications
--------------




| Specification |
| --- |
| [Console Standard # console-namespace](https://console.spec.whatwg.org/#console-namespace) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `console` | 1 | 12 | 4 | 8In Internet Explorer 8 and 9, the `console` object is `undefined` when the developer tools are not open. This behavior was fixed in Internet Explorer 10. | 10.5 | 3 | ≤37 | 18 | 4 | 11 | 1 | 1.0 |
| `assert` | 2 | 12 | 28 | 8 | 11 | 4 | ≤37 | 18 | 28 | 11 | 3.2 | 1.0 |
| `clear` | 25 | 12 | 39 | 8 | 12 | 7 | 4.4 | 25 | 39 | 12 | 7 | 1.5 |
| `count` | 2 | 12 | 30 | 11 | 11 | 4 | ≤37 | 18 | 30 | 11 | 3.2 | 1.0 |
| `countReset` | 68 | 79 | 62 | No | 55 | 13 | 68 | 68 | 62 | 48 | 13 | 10.0 |
| `debug` | 2 | 12 | 5 | 10 | 11 | 4 | ≤37 | 18 | 5 | 11 | 3.2 | 1.0 |
| `dir` | 2 | 12 | 8 | 9 | 11 | 4 | ≤37 | 18 | 8 | 11 | 3.2 | 1.0 |
| `dirxml` | 2 | 12 | 39 | 11 | 11 | 4 | ≤37 | 18 | 39 | 11 | 3.2 | 1.0 |
| `error` | 1 | 12 | 4 | 8 | 10.5 | 3 | 4.4 | 18 | 4 | 11 | 1 | 1.0 |
| `exception` | No | 13–79 | 28 | No | No | No | No | No | 28 | No | No | No |
| `group` | 2 | 12 | 9 | 11 | 11 | 4 | 37 | 18 | 9 | 11 | 3.2 | 1.0 |
| `groupCollapsed` | 6 | 12 | 9 | 11 | 11 | 5.1 | 3 | 18 | 9 | 11 | 5 | 1.0 |
| `groupEnd` | 2 | 12 | 9 | 11 | 11 | 4 | 37 | 18 | 9 | 11 | 3.2 | 1.0 |
| `info` | 1 | 12 | 4 | 8 | 10.5 | 3 | 4.4 | 18 | 4 | 11 | 1 | 1.0 |
| `log` | 1 | 12 | 4 | 8 | 10.5 | 3 | 4.4 | 18 | 4 | 11 | 1 | 1.0 |
| `profile` | 5 | 12 | 16–102 | 9 | 11 | 4 | ≤37 | 18 | 16–102 | 11 | 3.2 | 1.0 |
| `profileEnd` | 5 | 12 | 16 | 9 | 11 | 4 | ≤37 | 18 | 16 | 11 | 3.2 | 1.0 |
| `table` | 27 | 13 | 34 | No | 11 | 7 | 4.4 | 27 | 34 | 11 | 7 | 1.5 |
| `time` | 2 | 12 | 10 | 11 | 11 | 4 | ≤37 | 18 | 10 | 11 | 3.2 | 1.0 |
| `timeEnd` | 2 | 12 | 10 | 11 | 11 | 4 | ≤37 | 18 | 10 | 11 | 3.2 | 1.0 |
| `timeLog` | 71 | 79 | 62 | No | 60 | 13 | 71 | 71 | 62 | 50 | 13 | 10.0 |
| `timeStamp` | 15 | 12 | 39 | 11 | 15 | 6 | ≤37 | 18 | 39 | 14 | 6 | 1.0 |
| `trace` | 2 | 12 | 6 | 11 | 11 | 4 | ≤37 | 18 | 6 | 11 | 3.2 | 1.0 |
| `warn` | 1 | 12 | 4 | 8 | 10.5 | 3 | 4.4 | 18 | 4 | 11 | 1 | 1.0 |
| `worker_support` | 31 | 12 | 29 | 10 | ≤12.1 | 7 | 4.4.3 | 31 | 29 | ≤12.1 | 7 | 2.0 |


Notes
-----


* At least in Firefox, if a page defines a `console` object, that object overrides the one built into Firefox.

See also
--------


* [Firefox Developer Tools](https://firefox-source-docs.mozilla.org/devtools-user/index.html)
* [Web console](https://firefox-source-docs.mozilla.org/devtools-user/web_console/index.html) — how the Web console in Firefox handles console API calls
* [about:debugging](https://firefox-source-docs.mozilla.org/devtools-user/about_colon_debugging/index.html) — how to see console output when the debugging target is a mobile device

### Other implementations


* [Google Chrome DevTools](https://developer.chrome.com/docs/devtools/console/api/)
* [Microsoft Edge DevTools](https://docs.microsoft.com/archive/microsoft-edge/legacy/developer/)
* [Safari Web Inspector](https://developer.apple.com/library/archive/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Console/Console.html)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/console>

ContactAddress
==============



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `ContactAddress` interface of the [Contact Picker API](contact_picker_api) represents a physical address. Instances of this interface are retrieved from the `address` property of the objects returned by [`ContactsManager.getProperties()`](contactsmanager/getproperties).

 It may be useful to refer to the Universal Postal Union website's [Addressing S42 standard](https://www.upu.int/en/Postal-Solutions/Programmes-Services/Addressing-Solutions#addressing-s42-standard) materials, which provide information about international standards for postal addresses.



Instance properties
-------------------


*Inherits properties from its parent, [`PaymentAddress`](paymentaddress)*.


Instance methods
----------------


*Inherits methods from its parent, [`PaymentAddress`](paymentaddress)*.


Examples
--------



The following example prompts the user to select contacts, then prints the first returned address to the console.

 
```
const props = ["address"];
const opts = { multiple: true };

async function getContacts() {
  try {
    const contacts = await navigator.contacts.select(props, ops);
    const contactAddress = contacts[0].address[0];
    console.log(contactAddress);
  } catch (ex) {
    // Handle any errors here.
  }
}

```


Specifications
--------------




| Specification |
| --- |
| [Contact Picker API # contactaddress](https://w3c.github.io/contact-picker/#contactaddress) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ContactAddress` | No | No | No | No | No | No | 84 | 84 | No | 60 | No | 14.0 |
| `addressLine` | No | No | No | No | No | No | 84 | 84 | No | 60 | No | 14.0 |
| `city` | No | No | No | No | No | No | 84 | 84 | No | 60 | No | 14.0 |
| `country` | No | No | No | No | No | No | 84 | 84 | No | 60 | No | 14.0 |
| `dependentLocality` | No | No | No | No | No | No | 84 | 84 | No | 60 | No | 14.0 |
| `organization` | No | No | No | No | No | No | 84 | 84 | No | 60 | No | 14.0 |
| `phone` | No | No | No | No | No | No | 84 | 84 | No | 60 | No | 14.0 |
| `postalCode` | No | No | No | No | No | No | 84 | 84 | No | 60 | No | 14.0 |
| `recipient` | No | No | No | No | No | No | 84 | 84 | No | 60 | No | 14.0 |
| `region` | No | No | No | No | No | No | 84 | 84 | No | 60 | No | 14.0 |
| `sortingCode` | No | No | No | No | No | No | 84 | 84 | No | 60 | No | 14.0 |
| `toJSON` | No | No | No | No | No | No | 84 | 84 | No | 60 | No | 14.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ContactAddress>

ContactsManager
===============



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `ContactsManager` interface of the [`Contact Picker API`](contact_picker_api) allows users to select entries from their contact list and share limited details of the selected entries with a website or application.

 The `ContactsManager` is available through the global [`navigator.contacts`](navigator/contacts) property.



Instance methods
----------------


 
[`select()`](contactsmanager/select)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which, when resolved, presents the user with a contact picker which allows them to select contact(s) they wish to share.

  
[`getProperties()`](contactsmanager/getproperties)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which resolves with an [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of [`strings`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) indicating which contact properties are available.

  
Examples
--------


### Feature Detection



The following code checks whether the Contact Picker API is supported.

 
```
const supported = "contacts" in navigator && "ContactsManager" in window;

```


### Checking for Supported Properties



The following asynchronous function uses the `getProperties` method to check for supported properties.

 
```
async function checkProperties() {
  const supportedProperties = await navigator.contacts.getProperties();
  if (supportedProperties.includes("name")) {
    // run code for name support
  }
  if (supportedProperties.includes("email")) {
    // run code for email support
  }
  if (supportedProperties.includes("tel")) {
    // run code for telephone number support
  }
  if (supportedProperties.includes("address")) {
    // run code for address support
  }
  if (supportedProperties.includes("icon")) {
    // run code for avatar support
  }
}

```


### Selecting Contacts



The following example sets an array of properties to be retrieved for each contact, as well as setting an options object to allow for multiple contacts to be selected.

 An asynchronous function is then defined which uses the `select()` method to present the user with a contact picker interface and handle the chosen results.

 
```
const props = ["name", "email", "tel", "address", "icon"];
const opts = { multiple: true };

async function getContacts() {
  try {
    const contacts = await navigator.contacts.select(props, opts);
    handleResults(contacts);
  } catch (ex) {
    // Handle any errors here.
  }
}

```
 `handleResults()` is a developer defined function.



Specifications
--------------




| Specification |
| --- |
| [Contact Picker API # contacts-manager](https://w3c.github.io/contact-picker/#contacts-manager) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ContactsManager` | No | No | No | No | No | No | 80 | 80 | No | 57 | 14.5 | 13.0 |
| `getProperties` | No | No | No | No | No | No | 80 | 80 | No | 57 | 14.5 | 13.0 |
| `select` | No | No | No | No | No | No | 80 | 80 | No | 57 | 14.5 | 13.0 |


See also
--------


* [A Contact Picker for the Web](https://web.dev/contact-picker/)
* [A Contact Picker demo on glitch](https://contact-picker.glitch.me/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ContactsManager>

ContentVisibilityAutoStateChangeEvent
=====================================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `ContentVisibilityAutoStateChangeEvent` interface is the event object for the [`contentvisibilityautostatechange`](element/contentvisibilityautostatechange_event) event, which fires on any element with [`content-visibility: auto`](https://developer.mozilla.org/en-US/docs/Web/CSS/content-visibility) set on it when it starts or stops being [relevant to the user](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Containment#relevant_to_the_user) and [skipping its contents](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Containment#skips_its_contents).

  While the element is not relevant (between the start and end events), the user agent skips an element's rendering, including layout and painting. This can significantly improve page rendering speed. The [`contentvisibilityautostatechange`](element/contentvisibilityautostatechange_event) event provides a way for an app's code to also start or stop rendering processes (e.g. drawing on a [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas)) when they are not needed, thereby conserving processing power. 

 Note that even when hidden from view, element contents will remain semantically relevant (e.g. to assistive technology users), so this signal should not be used to skip significant semantic DOM updates.


 Event ContentVisibilityAutoStateChangeEvent

Constructor
-----------


 [`ContentVisibilityAutoStateChangeEvent()`](contentvisibilityautostatechangeevent/contentvisibilityautostatechangeevent)  Creates a new `ContentVisibilityAutoStateChangeEvent` object instance.

  
Instance properties
-------------------



*Inherits properties from its parent, [`Event`](event).*

  
[`skipped`](contentvisibilityautostatechangeevent/skipped) Read only 
  Returns `true` if the user agent is skipping the element's rendering, or `false` otherwise.

  

Examples
--------



```
const canvasElem = document.querySelector("canvas");

canvasElem.addEventListener("contentvisibilityautostatechange", stateChanged);
canvasElem.style.contentVisibility = "auto";

function stateChanged(event) {
  if (event.skipped) {
    stopCanvasUpdates(canvasElem);
  } else {
    startCanvasUpdates(canvasElem);
  }
}

// Call this when the canvas updates need to start.
function startCanvasUpdates(canvas) {
  // …
}

// Call this when the canvas updates need to stop.
function stopCanvasUpdates(canvas) {
  // …
}

```

Specifications
--------------




| Specification |
| --- |
| [CSS Containment Module Level 2 # content-visibility-auto-state-change](https://w3c.github.io/csswg-drafts/css-contain/#content-visibility-auto-state-change) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ContentVisibilityAutoStateChangeEvent` | 108 | 108 | 110 | No | 94 | No | 108 | 108 | No | 73 | No | No |
| `ContentVisibilityAutoStateChangeEvent` | 108 | 108 | 110 | No | 94 | No | 108 | 108 | No | 73 | No | No |
| `skipped` | 108 | 108 | 110 | No | 94 | No | 108 | 108 | No | 73 | No | No |


See also
--------


* The [`contentvisibilityautostatechange`](element/contentvisibilityautostatechange_event) event
* [CSS Containment](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Containment)
* The [`content-visibility`](https://developer.mozilla.org/en-US/docs/Web/CSS/content-visibility) property
* The [`contain`](https://developer.mozilla.org/en-US/docs/Web/CSS/contain) property


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ContentVisibilityAutoStateChangeEvent>

ConvolverNode
=============



The `ConvolverNode` interface is an [`AudioNode`](audionode) that performs a Linear Convolution on a given [`AudioBuffer`](audiobuffer), often used to achieve a reverb effect. A `ConvolverNode` always has exactly one input and one output.

  **Note:** For more information on the theory behind Linear Convolution, see the [Convolution article on Wikipedia](https://en.wikipedia.org/wiki/Convolution).

 
 EventTarget AudioNode ConvolverNode 

|  |  |
| --- | --- |
| Number of inputs | `1` |
| Number of outputs | `1` |
| Channel count mode | `"clamped-max"` |
| Channel count | `1`, `2`, or `4` |
| Channel interpretation | `"speakers"` |



Constructor
-----------


 [`ConvolverNode()`](convolvernode/convolvernode)  Creates a new `ConvolverNode` object instance.

  
Instance properties
-------------------



*Inherits properties from its parent, [`AudioNode`](audionode)*.

  [`ConvolverNode.buffer`](convolvernode/buffer)  A mono, stereo, or 4-channel *[`AudioBuffer`](audiobuffer)* containing the (possibly multichannel) impulse response used by the `ConvolverNode` to create the reverb effect.

  [`ConvolverNode.normalize`](convolvernode/normalize)  A boolean that controls whether the impulse response from the buffer will be scaled by an equal-power normalization when the `buffer` attribute is set, or not.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`AudioNode`](audionode)*.


ConvolverNode Example
---------------------



The following example shows basic usage of an AudioContext to create a convolver node.

  **Note:** You will need to find an impulse response to complete the example below. See this [Codepen](https://codepen.io/DonKarlssonSan/pen/doVKRE) for an applied example.

  
```
let audioCtx = new window.AudioContext();

async function createReverb() {
  let convolver = audioCtx.createConvolver();

  // load impulse response from file
  let response = await fetch("path/to/impulse-response.wav");
  let arraybuffer = await response.arrayBuffer();
  convolver.buffer = await audioCtx.decodeAudioData(arraybuffer);

  return convolver;
}

// …

let reverb = await createReverb();

// someOtherAudioNode -> reverb -> destination
someOtherAudioNode.connect(reverb);
reverb.connect(audioCtx.destination);

```


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # ConvolverNode](https://webaudio.github.io/web-audio-api/#ConvolverNode) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ConvolverNode` | 55 | 79 | 53 | No | 42 | 14.1 | 55 | 55 | 53 | 42 | 14.5 | 6.0 |
| `ConvolverNode` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `buffer` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `normalize` | 18 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ConvolverNode>

CookieChangeEvent
=================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `CookieChangeEvent` interface of the ['Cookie Store API'](cookie_store_api) is the event type of the [`change`](cookiestore/change_event) event fired at a [`CookieStore`](cookiestore) when any cookie changes occur. A cookie change consists of a cookie and a type (either "changed" or "deleted").

 Cookie changes that will cause the `CookieChangeEvent` to be dispatched are:

 * A cookie is newly created and not immediately removed. In this case `type` is "changed".
* A cookie is newly created and immediately removed. In this case `type` is "deleted"
* A cookie is removed. In this case `type` is "deleted".

  **Note:** A cookie that is replaced due to the insertion of another cookie with the same name, domain, and path, is ignored and does not trigger a change event.

 
 Event CookieChangeEvent

Constructor
-----------


 
[`CookieChangeEvent()`](cookiechangeevent/cookiechangeevent)  Experimental 
  Creates a new `CookieChangeEvent`.

  
Instance properties
-------------------



*This interface also inherits properties from [`Event`](event).*

  
[`CookieChangeEvent.changed`](cookiechangeevent/changed) Read only   Experimental 
  Returns an array containing one or more changed cookies.

  
[`CookieChangeEvent.deleted`](cookiechangeevent/deleted) Read only   Experimental 
  Returns an array containing one or more deleted cookies.

  

Examples
--------



In this example when the cookie is set, the event listener logs the event to the console. This is a `CookieChangeEvent` object with the [`changed`](cookiechangeevent/changed) property containing an object representing the cookie that has just been set.

 
```
cookieStore.addEventListener("change", (event) => {
  console.log(event);
});

const one_day = 24 \* 60 \* 60 \* 1000;
cookieStore.set({
  name: "cookie1",
  value: "cookie1-value",
  expires: Date.now() + one_day,
  domain: "example.com",
});

```


Specifications
--------------




| Specification |
| --- |
| [Cookie Store API # CookieChangeEvent](https://wicg.github.io/cookie-store/#CookieChangeEvent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CookieChangeEvent` | 87 | 87 | No | No | 73 | No | 87 | 87 | No | 62 | No | 14.0 |
| `CookieChangeEvent` | 87 | 87 | No | No | 73 | No | 87 | 87 | No | 62 | No | 14.0 |
| `changed` | 87 | 87 | No | No | 73 | No | 87 | 87 | No | 62 | No | 14.0 |
| `deleted` | 87 | 87 | No | No | 73 | No | 87 | 87 | No | 62 | No | 14.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CookieChangeEvent>

CookieStoreManager
==================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `CookieStoreManager` interface of the ['Cookie Store API'](cookie_store_api) allows service workers to subscribe to cookie change events. Call [`subscribe()`](cookiestoremanager/subscribe) on a particular service worker registration to receive change events.

 A `CookieStoreManager` has an associated [`ServiceWorkerRegistration`](serviceworkerregistration). Each service worker registration has a cookie change subscription list, which is a list of cookie change subscriptions each containing a name and URL. The methods in this interface allow the service worker to add and remove subscriptions from this list, and to get a list of all subscriptions.

 To get a `CookieStoreManager`, call `ServiceWorkerRegistration.cookies`.



Instance methods
----------------


 
[`CookieStoreManager.getSubscriptions()`](cookiestoremanager/getsubscriptions)  Experimental 
  Returns a [`promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which resolves to a list of the cookie change subscriptions for this service worker registration.

  
[`CookieStoreManager.subscribe()`](cookiestoremanager/subscribe)  Experimental 
  Subscribes to changes to cookies. It returns a [`promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which resolves when the subscription is successful.

  
[`CookieStoreManager.unsubscribe()`](cookiestoremanager/unsubscribe)  Experimental 
  Unsubscribes the registered service worker from changes to cookies. It returns a [`promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which resolves when the operation is successful.

  
Examples
--------



In this example the [`ServiceWorkerRegistration`](serviceworkerregistration) represented by `registration` is subscribing to change events on the cookie named `"cookie1"` with a scope of `"/path1"`.

 
```
const subscriptions = [{ name: "cookie1", url: `/path1` }];
await registration.cookies.subscribe(subscriptions);

```
 If the [`ServiceWorkerRegistration`](serviceworkerregistration) has subscribed to any cookies then [`getSubscriptions()`](cookiestoremanager/getsubscriptions) will return a list of cookies represented by objects in the same format as used for the original subscription.

 
```
const subscriptions = await registration.cookies.getSubscriptions();

```


Specifications
--------------




| Specification |
| --- |
| [Cookie Store API # cookiestoremanager](https://wicg.github.io/cookie-store/#cookiestoremanager) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CookieStoreManager` | 87 | 87 | No | No | 73 | No | 87 | 87 | No | 62 | No | 14.0 |
| `getSubscriptions` | 87 | 87 | No | No | 73 | No | 87 | 87 | No | 62 | No | 14.0 |
| `subscribe` | 87 | 87 | No | No | 73 | No | 87 | 87 | No | 62 | No | 14.0 |
| `unsubscribe` | 87 | 87 | No | No | 73 | No | 87 | 87 | No | 62 | No | 14.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CookieStoreManager>

CountQueuingStrategy
====================


The `CountQueuingStrategy` interface of the [Streams API](streams_api) provides a built-in chunk counting queuing strategy that can be used when constructing streams.


Constructor
-----------


 [`CountQueuingStrategy()`](countqueuingstrategy/countqueuingstrategy)  Creates a new `CountQueuingStrategy` object instance.

  
Instance properties
-------------------


 
[`CountQueuingStrategy.highWaterMark`](countqueuingstrategy/highwatermark) Read only 
  The total number of chunks that can be contained in the internal queue before [backpressure](streams_api/concepts#backpressure) is applied.

  
Instance methods
----------------


 [`CountQueuingStrategy.size()`](countqueuingstrategy/size)  Always returns `1`.

  
Examples
--------



```
const queueingStrategy = new CountQueuingStrategy({ highWaterMark: 1 });

const writableStream = new WritableStream(
  {
    // Implement the sink
    write(chunk) {
      // …
    },
    close() {
      // …
    },
    abort(err) {
      console.log("Sink error:", err);
    },
  },
  queueingStrategy
);

const size = queueingStrategy.size();

```

Specifications
--------------




| Specification |
| --- |
| [Streams Standard # cqs-class](https://streams.spec.whatwg.org/#cqs-class) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CountQueuingStrategy` | 52 | 16 | 65 | No | 39 | 10.1 | 52 | 52 | 65 | 41 | 10.3 | 6.0 |
| `CountQueuingStrategy` | 52 | 16 | 65 | No | 39 | 10.1 | 52 | 52 | 65 | 41 | 10.3 | 6.0 |
| `highWaterMark` | 52 | 16 | 65 | No | 39 | 10.1 | 52 | 52 | 65 | 41 | 10.3 | 6.0 |
| `size` | 52 | 16 | 65 | No | 39 | 10.1 | 52 | 52 | 65 | 41 | 10.3 | 6.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CountQueuingStrategy>

CookieStore
===========



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `CookieStore` interface of the ['Cookie Store API'](cookie_store_api) provides methods for getting and setting cookies asynchronously from either a page or a service worker.

 The `CookieStore` is accessed via attributes in the global scope in a [`Window`](window) or [`ServiceWorkerGlobalScope`](serviceworkerglobalscope) context. Therefore there is no constructor.


 EventTarget CookieStore

Instance methods
----------------


 
[`CookieStore.delete()`](cookiestore/delete)  Experimental 
  The `delete()` method deletes a cookie with the given name or options object, it returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves when the deletion completes.

  
[`CookieStore.get()`](cookiestore/get)  Experimental 
  The `get()` method gets a single cookie with the given name or options object, it returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with details of a single cookie.

  
[`CookieStore.getAll()`](cookiestore/getall)  Experimental 
  The `getAll()` method gets all matching cookies, it returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with a list of cookies.

  
[`CookieStore.set()`](cookiestore/set)  Experimental 
  The `set()` method sets a cookie with the given name and value or options object, it returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves when the cookie is set.

  
Events
------


 
[`change`](cookiestore/change_event)  Experimental 
  The `change` event fires when a change is made to any cookie.

  
Examples
--------



In this example we set a cookie and write to the console feedback as to whether the operation succeeded or failed.

 
```
const day = 24 \* 60 \* 60 \* 1000;
cookieStore
  .set({
    name: "cookie1",
    value: "cookie1-value",
    expires: Date.now() + day,
    domain: "example.com",
  })
  .then(
    () => {
      console.log("It worked!");
    },
    (reason) => {
      console.error("It failed: ", reason);
    }
  );

```


Specifications
--------------




| Specification |
| --- |
| [Cookie Store API # CookieStore](https://wicg.github.io/cookie-store/#CookieStore) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CookieStore` | 87 | 87 | NoSee [bug 1475599](https://bugzil.la/1475599). | No | 73 | NoSee [bug 231750](https://webkit.org/b/231750). | 87 | 87 | NoSee [bug 1475599](https://bugzil.la/1475599). | 62 | NoSee [bug 231750](https://webkit.org/b/231750). | 14.0 |
| `change_event` | 87 | 87 | No | No | 73 | No | 87 | 87 | No | 62 | No | 14.0 |
| `delete` | 87 | 87 | No | No | 73 | No | 87 | 87 | No | 62 | No | 14.0 |
| `get` | 87 | 87 | No | No | 73 | No | 87 | 87 | No | 62 | No | 14.0 |
| `getAll` | 87 | 87 | No | No | 73 | No | 87 | 87 | No | 62 | No | 14.0 |
| `set` | 87 | 87 | No | No | 73 | No | 87 | 87 | No | 62 | No | 14.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CookieStore>

Crypto
======



 The `Crypto` interface represents basic cryptography features available in the current context. It allows access to a cryptographically strong random number generator and to cryptographic primitives. 


 **Note:** This feature is available in [Web Workers](web_workers_api)

  The [Web Crypto API](web_crypto_api) is accessed through the global [`crypto`](crypto_property) property, which is a `Crypto` object.



Instance properties
-------------------



*This interface implements properties defined on [`RandomSource`](crypto/getrandomvalues).*

  
[`Crypto.subtle`](crypto/subtle) Read only  Secure context
  Returns a [`SubtleCrypto`](subtlecrypto) object providing access to common cryptographic primitives, like hashing, signing, encryption, or decryption.

  

Instance methods
----------------



*This interface implements methods defined on [`RandomSource`](crypto/getrandomvalues).*

  [`Crypto.getRandomValues()`](crypto/getrandomvalues)  Fills the passed [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) with cryptographically sound random values.

  [`Crypto.randomUUID()`](crypto/randomuuid)  Returns a randomly generated, 36 character long v4 UUID.

  

Usage notes
-----------



 You should avoid using the Web Crypto API on insecure contexts, even though the `Crypto` interface is present on insecure contexts, as is the [`crypto`](crypto_property) property. In addition, the `Crypto` method [`getRandomValues()`](crypto/getrandomvalues) is available on insecure contexts, but the [`subtle`](crypto/subtle) property is not. 

 In general, you probably should just treat `Crypto` as available only on secure contexts.



Specifications
--------------




| Specification |
| --- |
| [Web Cryptography API # crypto-interface](https://w3c.github.io/webcrypto/#crypto-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Crypto` | 11 | 12 | 21 | 11 | 15 | 5 | ≤37 | 18 | 21 | 14 | 5 | 1.0 |
| `getRandomValues` | 11 | 12 | 21 | 11 | 15 | 5 | ≤37 | 18 | 21 | 14 | 5 | 1.0 |
| `randomUUID` | 92 | 92 | 95 | No | 78 | 15.4 | 92 | 92 | 95 | 65 | 15.4 | 16.0 |
| `subtle` | 37 | 12 | 34 | 11 | 24 | 117–11.1 | 37 | 37 | 34 | 24 | 117–11.3 | 3.0 |


See also
--------


* [Web security](https://developer.mozilla.org/en-US/docs/Web/Security)
* [Secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts)
* [Features restricted to secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts/features_restricted_to_secure_contexts)
* [Transport Layer Security](https://developer.mozilla.org/en-US/docs/Web/Security/Transport_Layer_Security)
* [Strict-Transport-Security](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Crypto>

CryptoKey
=========



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `CryptoKey` interface of the [Web Crypto API](web_crypto_api) represents a cryptographic [key](https://developer.mozilla.org/en-US/docs/Glossary/Key) obtained from one of the [`SubtleCrypto`](subtlecrypto) methods [`generateKey()`](subtlecrypto/generatekey), [`deriveKey()`](subtlecrypto/derivekey), [`importKey()`](subtlecrypto/importkey), or [`unwrapKey()`](subtlecrypto/unwrapkey).

 For security reasons, the `CryptoKey` interface can only be used in a [secure context](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts).



Instance properties
-------------------


 
[`CryptoKey.type`](cryptokey/type) Read only 
  The type of key the object represents. It may take one of the following values: `"secret"`, `"private"` or `"public"`.

  
[`CryptoKey.extractable`](cryptokey/extractable) Read only 
  A boolean value indicating whether or not the key may be extracted using [`SubtleCrypto.exportKey()`](subtlecrypto/exportkey) or [`SubtleCrypto.wrapKey()`](subtlecrypto/wrapkey).

  
[`CryptoKey.algorithm`](cryptokey/algorithm) Read only 
  An object describing the algorithm for which this key can be used and any associated extra parameters.

  
[`CryptoKey.usages`](cryptokey/usages) Read only 
  An [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of strings, indicating what can be done with the key. Possible values for array elements are `"encrypt"`, `"decrypt"`, `"sign"`, `"verify"`, `"deriveKey"`, `"deriveBits"`, `"wrapKey"`, and `"unwrapKey"`.

  
Examples
--------



The examples for `SubtleCrypto` methods often use `CryptoKey` objects. For example:

 * [`SubtleCrypto.generateKey()`](subtlecrypto/generatekey)
* [`SubtleCrypto.deriveKey()`](subtlecrypto/derivekey)
* [`SubtleCrypto.importKey()`](subtlecrypto/importkey)
* [`SubtleCrypto.exportKey()`](subtlecrypto/exportkey)
* [`SubtleCrypto.wrapKey()`](subtlecrypto/wrapkey)
* [`SubtleCrypto.unwrapKey()`](subtlecrypto/unwrapkey)
* [`SubtleCrypto.encrypt()`](subtlecrypto/encrypt)
* [`SubtleCrypto.decrypt()`](subtlecrypto/decrypt)
* [`SubtleCrypto.sign()`](subtlecrypto/sign)
* [`SubtleCrypto.verify()`](subtlecrypto/verify)



Specifications
--------------




| Specification |
| --- |
| [Web Cryptography API # cryptokey-interface](https://w3c.github.io/webcrypto/#cryptokey-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CryptoKey` | 37 | 12 | 34 | No | 24 | 7 | 37 | 37 | 34 | 24 | 7 | 3.0 |
| `algorithm` | 37 | 12 | 34 | No | 24 | 7 | 37 | 37 | 34 | 24 | 7 | 3.0 |
| `extractable` | 37 | 12 | 34 | No | 24 | 7 | 37 | 37 | 34 | 24 | 7 | 3.0 |
| `type` | 37 | 12 | 34 | No | 24 | 7 | 37 | 37 | 34 | 24 | 7 | 3.0 |
| `usages` | 37 | 12 | 34 | No | 24 | 7 | 37 | 37 | 34 | 24 | 7 | 3.0 |


See also
--------


* [Web Crypto API](web_crypto_api)
* [Web security](https://developer.mozilla.org/en-US/docs/Web/Security)
* [Privacy, permissions, and information security](https://developer.mozilla.org/en-US/docs/Web/Privacy)
* [`Crypto`](crypto) and [`Crypto.subtle`](crypto/subtle).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey>

CryptoKeyPair
=============



The `CryptoKeyPair` dictionary of the [Web Crypto API](web_crypto_api) represents a key pair for an asymmetric cryptography algorithm, also known as a public-key algorithm.

 A `CryptoKeyPair` object can be obtained using [`SubtleCrypto.generateKey()`](subtlecrypto/generatekey), when the selected algorithm is one of the asymmetric algorithms: RSASSA-PKCS1-v1\_5, RSA-PSS, RSA-OAEP, ECDSA, or ECDH.

 It contains two properties, which are both [`CryptoKey`](cryptokey) objects: a `privateKey` property containing the private key and a `publicKey` property containing the public key.



Instance properties
-------------------


 `CryptoKeyPair.privateKey`  A [`CryptoKey`](cryptokey) object representing the private key. For encryption and decryption algorithms, this key is used to decrypt. For signing and verification algorithms it is used to sign.

  `CryptoKeyPair.publicKey`  A [`CryptoKey`](cryptokey) object representing the public key. For encryption and decryption algorithms, this key is used to encrypt. For signing and verification algorithms it is used to verify signatures.

  
Examples
--------



The examples for `SubtleCrypto` methods often use `CryptoKeyPair` objects. For example:

 * [`SubtleCrypto.generateKey()`](subtlecrypto/generatekey)
* [`SubtleCrypto.deriveKey()`](subtlecrypto/derivekey)
* [`SubtleCrypto.importKey()`](subtlecrypto/importkey)
* [`SubtleCrypto.exportKey()`](subtlecrypto/exportkey)
* [`SubtleCrypto.wrapKey()`](subtlecrypto/wrapkey)
* [`SubtleCrypto.unwrapKey()`](subtlecrypto/unwrapkey)
* [`SubtleCrypto.encrypt()`](subtlecrypto/encrypt)
* [`SubtleCrypto.decrypt()`](subtlecrypto/decrypt)
* [`SubtleCrypto.sign()`](subtlecrypto/sign)
* [`SubtleCrypto.verify()`](subtlecrypto/verify)



Specifications
--------------




| Specification |
| --- |
| [Web Cryptography API # keypair](https://w3c.github.io/webcrypto/#keypair) |


See also
--------


* [`SubtleCrypto.generateKey`](subtlecrypto/generatekey).
* [`SubtleCrypto.sign`](subtlecrypto/sign) and [`SubtleCrypto.verify`](subtlecrypto/verify).
* [`SubtleCrypto.encrypt`](subtlecrypto/encrypt) and [`SubtleCrypto.decrypt`](subtlecrypto/decrypt).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CryptoKeyPair>

CSPViolationReportBody
======================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `CSPViolationReportBody` interface contains the report data for a Content Security Policy (CSP) violation. CSP violations are thrown when the webpage attempts to load a resource that violates the CSP set by the [`Content-Security-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) HTTP header.

  **Note:** this interface is similar, but not identical to, the [JSON objects](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP#violation_report_syntax) sent back to the [`report-uri`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/report-uri) or [`report-to`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/report-to) policy directive of the [`Content-Security-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) header.

 
 ReportBody CSPViolationReportBody

Instance properties
-------------------



*Also inherits properties from its parent interface, [`ReportBody`](reportbody).*

  
`CSPViolationReportBody.blockedURL` Read only 
  A string representing the URL of the resource that was blocked because it violates the CSP.

  
`CSPViolationReportBody.columnNumber` Read only 
  The column number in the script at which the violation occurred.

  
`CSPViolationReportBody.disposition` Read only 
  Indicates how the violated policy is configured to be treated by the user agent. This will be `"enforce"` or `"report"`.

  
`CSPViolationReportBody.documentURL` Read only 
  A string representing the URL of the document or worker in which the violation was found.

  
`CSPViolationReportBody.effectiveDirective` Read only 
  A string representing the directive whose enforcement uncovered the violation.

  
`CSPViolationReportBody.lineNumber` Read only 
  The line number in the script at which the violation occurred.

  
`CSPViolationReportBody.originalPolicy` Read only 
  A string containing the policy whose enforcement uncovered the violation.

  
`CSPViolationReportBody.referrer` Read only 
  A string representing the URL for the referrer of the resources whose policy was violated, or `null`.

  
`CSPViolationReportBody.sample` Read only 
  A string representing a sample of the resource that caused the violation, usually the first 40 characters. This will only be populated if the resource is an inline script, event handler, or style — external resources causing a violation will not generate a sample.

  
`CSPViolationReportBody.sourceFile` Read only 
  If the violation occurred as a result of a script, this will be the URL of the script; otherwise, it will be `null`. Both `columnNumber` and `lineNumber` should have non-null values if this property is not `null`.

  
`CSPViolationReportBody.statusCode` Read only 
  A number representing the HTTP status code of the document or worker in which the violation occurred.

  

Instance methods
----------------



*Also inherits methods from its parent interface, [`ReportBody`](reportbody).*

  `CSPViolationReportBody.toJSON()`  A *serializer* which returns a JSON representation of the `CSPViolationReportBody` object.

  

Examples
--------


### Obtaining a `CSPViolationReportBody` object



To obtain a `CSPViolationReportBody` object, you must configure your page so that a CSP violation will occur. In this example, we will set our CSP to only allow content from the site's own origin, and then attempt to load a script from `apis.google.com`, which is an external origin.

 First, we will set our [`Content-Security-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) header:

 
```
Content-Security-Policy: default-src 'self';

```
 Then, we will attempt to load an external script:

 
```
<!-- This should generate a CSP violation -->
<script src="https://apis.google.com/js/platform.js"></script>

```
 Finally, we will create a new [`ReportingObserver`](reportingobserver) object to listen for CSP violations.

 
```
const observer = new ReportingObserver(
  (reports, observer) => {
    const cspViolation = reports[0].body;
  },
  {
    types: ["csp-violation"],
    buffered: true,
  }
);

observer.observe();

```


Specifications
--------------




| Specification |
| --- |
| [Content Security Policy Level 3 # cspviolationreportbody](https://w3c.github.io/webappsec-csp/#cspviolationreportbody) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSPViolationReportBody` | 74 | 79 | No | No | 56 | preview | 74 | 74 | No | 48 | No | 10.0 |
| `blockedURL` | 74 | 79 | No | No | 56 | preview | 74 | 74 | No | 48 | No | 10.0 |
| `columnNumber` | 74 | 79 | No | No | 56 | preview | 74 | 74 | No | 48 | No | 10.0 |
| `disposition` | 74 | 79 | No | No | 56 | preview | 74 | 74 | No | 48 | No | 10.0 |
| `documentURL` | 74 | 79 | No | No | 56 | preview | 74 | 74 | No | 48 | No | 10.0 |
| `effectiveDirective` | 74 | 79 | No | No | 56 | preview | 74 | 74 | No | 48 | No | 10.0 |
| `lineNumber` | 74 | 79 | No | No | 56 | preview | 74 | 74 | No | 48 | No | 10.0 |
| `originalPolicy` | 74 | 79 | No | No | 56 | preview | 74 | 74 | No | 48 | No | 10.0 |
| `referrer` | 74 | 79 | No | No | 56 | preview | 74 | 74 | No | 48 | No | 10.0 |
| `sample` | 74 | 79 | No | No | 56 | preview | 74 | 74 | No | 48 | No | 10.0 |
| `sourceFile` | 74 | 79 | No | No | 56 | preview | 74 | 74 | No | 48 | No | 10.0 |
| `statusCode` | 74 | 79 | No | No | 56 | preview | 74 | 74 | No | 48 | No | 10.0 |
| `toJSON` | 80 | 80 | No | No | 56 | preview | 80 | 80 | No | 48 | No | 10.0 |


See also
--------


* [`ReportBody`](reportbody)
* [`ReportingObserver`](reportingobserver)
* [`Content-Security-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy)
* [`SecurityPolicyViolationEvent`](securitypolicyviolationevent)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSPViolationReportBody>

CSS
===


The `CSS` interface holds useful CSS-related methods. No objects with this interface are implemented: it contains only static methods and is therefore a utilitarian interface.


Static properties
-----------------


 
[`CSS.highlights`](css/highlights)  Experimental 
  Provides access to the `HighlightRegistry` used to style arbitrary text ranges using the [CSS Custom Highlight API](css_custom_highlight_api).

  
[`CSS.paintWorklet`](css/paintworklet)  Experimental  Secure context
  Provides access to the Worklet responsible for all the classes related to painting.

  
Instance properties
-------------------


*The CSS interface is a utility interface and no object of this type can be created: only static properties are defined on it.*


Static methods
--------------



*No inherited static methods*.

  [`CSS.registerProperty()`](css/registerproperty)  Registers [`custom properties`](https://developer.mozilla.org/en-US/docs/Web/CSS/--*), allowing for property type checking, default values, and properties that do or do not inherit their value.

  [`CSS.supports()`](css/supports)  Returns a boolean value indicating if the pair *property-value*, or the condition, given in parameter is supported.

  [`CSS.escape()`](css/escape)  Can be used to escape a string mostly for use as part of a CSS selector.

  [`CSS factory functions`](css/factory_functions)  Can be used to return a new [`CSSUnitValue`](cssunitvalue) with a value of the parameter number of the units of the name of the factory function method used.

 
```
CSS.em(3); // CSSUnitValue {value: 3, unit: "em"}

```
  

Instance methods
----------------


*The CSS interface is a utility interface and no object of this type can be created: only static methods are defined on it.*


Specifications
--------------




| Specification |
| --- |
| [CSS Object Model (CSSOM) # namespacedef-css](https://w3c.github.io/csswg-drafts/cssom/#namespacedef-css) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Hz` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `Q` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `CSS` | 28 | 12 | 22 | No | 15 | 9 | 4.4 | 28 | 22 | 15 | 9 | 1.5 |
| `ch` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `cm` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `cqb` | 105 | 105 | No | No | 91 | 16.4 | 105 | 105 | No | 72 | 16.4 | 20.0 |
| `cqh` | 105 | 105 | No | No | 91 | 16.4 | 105 | 105 | No | 72 | 16.4 | 20.0 |
| `cqi` | 105 | 105 | No | No | 91 | 16.4 | 105 | 105 | No | 72 | 16.4 | 20.0 |
| `cqmax` | 105 | 105 | No | No | 91 | 16.4 | 105 | 105 | No | 72 | 16.4 | 20.0 |
| `cqmin` | 105 | 105 | No | No | 91 | 16.4 | 105 | 105 | No | 72 | 16.4 | 20.0 |
| `cqw` | 105 | 105 | No | No | 91 | 16.4 | 105 | 105 | No | 72 | 16.4 | 20.0 |
| `deg` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `dpcm` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `dpi` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `dppx` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `dvb` | 108 | 108 | No | No | 94 | 16.4 | 108 | 108 | No | 73 | 16.4 | No |
| `dvh` | 108 | 108 | No | No | 94 | 16.4 | 108 | 108 | No | 73 | 16.4 | No |
| `dvi` | 108 | 108 | No | No | 94 | 16.4 | 108 | 108 | No | 73 | 16.4 | No |
| `dvmax` | 108 | 108 | No | No | 94 | 16.4 | 108 | 108 | No | 73 | 16.4 | No |
| `dvmin` | 108 | 108 | No | No | 94 | 16.4 | 108 | 108 | No | 73 | 16.4 | No |
| `dvw` | 108 | 108 | No | No | 94 | 16.4 | 108 | 108 | No | 73 | 16.4 | No |
| `em` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `escape` | 46 | 79 | 31 | No | 33 | 10.1 | 46 | 46 | 31 | 33 | 10.3 | 5.0 |
| `ex` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `fr` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `grad` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `highlights` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `in` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `kHz` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `lvb` | 108 | 108 | No | No | 94 | 16.4 | 108 | 108 | No | 73 | 16.4 | No |
| `lvh` | 108 | 108 | No | No | 94 | 16.4 | 108 | 108 | No | 73 | 16.4 | No |
| `lvi` | 108 | 108 | No | No | 94 | 16.4 | 108 | 108 | No | 73 | 16.4 | No |
| `lvmax` | 108 | 108 | No | No | 94 | 16.4 | 108 | 108 | No | 73 | 16.4 | No |
| `lvmin` | 108 | 108 | No | No | 94 | 16.4 | 108 | 108 | No | 73 | 16.4 | No |
| `lvw` | 108 | 108 | No | No | 94 | 16.4 | 108 | 108 | No | 73 | 16.4 | No |
| `mm` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `ms` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `number` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `paintWorklet` | 65 | 79 | No | No | 52 | No | 65 | 65 | No | 47 | No | 9.0 |
| `pc` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `percent` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `pt` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `px` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `rad` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `registerProperty` | 78 | 79 | No | No | 65 | 16.4 | 78 | 78 | No | 56 | 16.4 | 12.0 |
| `rem` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `s` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `supports` | 6128–61The parentheses-less one-argument version is not supported. | 7912–79The parentheses-less one-argument version is not supported. | 5522–55The parentheses-less one-argument version is not supported. | No | 4815–48The parentheses-less one-argument version is not supported. | 119–11The parentheses-less one-argument version is not supported. | 614.4–61The parentheses-less one-argument version is not supported. | 6128–61The parentheses-less one-argument version is not supported. | 5522–55The parentheses-less one-argument version is not supported. | 4515–45The parentheses-less one-argument version is not supported. | 119–11The parentheses-less one-argument version is not supported. | 8.01.5–8.0The parentheses-less one-argument version is not supported. |
| `svb` | 108 | 108 | No | No | 94 | 16.4 | 108 | 108 | No | 73 | 16.4 | No |
| `svh` | 108 | 108 | No | No | 94 | 16.4 | 108 | 108 | No | 73 | 16.4 | No |
| `svi` | 108 | 108 | No | No | 94 | 16.4 | 108 | 108 | No | 73 | 16.4 | No |
| `svmax` | 108 | 108 | No | No | 94 | 16.4 | 108 | 108 | No | 73 | 16.4 | No |
| `svmin` | 108 | 108 | No | No | 94 | 16.4 | 108 | 108 | No | 73 | 16.4 | No |
| `svw` | 108 | 108 | No | No | 94 | 16.4 | 108 | 108 | No | 73 | 16.4 | No |
| `turn` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `vb` | 108 | 108 | NoSee [bug 1287034](https://bugzil.la/1287034). | No | 94 | 16.4See [bug 159801](https://webkit.org/b/159801). | 108 | 108 | NoSee [bug 1287034](https://bugzil.la/1287034). | 73 | 16.4See [bug 159801](https://webkit.org/b/159801). | No |
| `vh` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `vi` | 108 | 108 | NoSee [bug 1287034](https://bugzil.la/1287034). | No | 94 | 16.4See [bug 159801](https://webkit.org/b/159801). | 108 | 108 | NoSee [bug 1287034](https://bugzil.la/1287034). | 73 | 16.4See [bug 159801](https://webkit.org/b/159801). | No |
| `vmax` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `vmin` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `vw` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSS>

Credential
==========



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `Credential` interface of the [Credential Management API](credential_management_api) provides information about an entity (usually a user) normally as a prerequisite to a trust decision.

 `Credential` objects may be of four different types:

 * [`FederatedCredential`](federatedcredential)
* [`IdentityCredential`](identitycredential)
* [`PasswordCredential`](passwordcredential)
* [`PublicKeyCredential`](publickeycredential)



Instance properties
-------------------


 
[`Credential.id`](credential/id) Read only 
  Returns a string containing the credential's identifier. This might be any one of a GUID, username, or email address.

  
[`Credential.type`](credential/type) Read only 
  Returns a string containing the credential's type. Valid values are `password`, `federated` and `public-key`. (For [`PasswordCredential`](passwordcredential), [`FederatedCredential`](federatedcredential) and [`PublicKeyCredential`](publickeycredential))

  
### Event handlers


None.


Instance methods
----------------


None.


Examples
--------



```
let pwdCredential = new PasswordCredential({
  id: "example-username", // Username/ID
  name: "Carina Anand", // Display name
  password: "correct horse battery staple", // Password
});

console.assert(pwdCredential.type === "password");

```

Specifications
--------------




| Specification |
| --- |
| [Credential Management Level 1 # the-credential-interface](https://w3c.github.io/webappsec-credential-management/#the-credential-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Credential` | 51 | 18 | 60 | No | 38 | 13 | 51 | 51 | 60 | 41 | 13 | 5.0 |
| `id` | 51 | 18 | 60 | No | 38 | 13 | 51 | 51 | 60 | 41 | 13 | 5.0 |
| `isConditionalMediationAvailable` | No | No | No | No | No | 16 | No | No | No | No | 16 | No |
| `type` | 51 | 18 | 60 | No | 38 | 13 | 51 | 51 | 60 | 41 | 13 | 5.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Credential>

CredentialsContainer
====================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `CredentialsContainer` interface of the [Credential Management API](credential_management_api) exposes methods to request credentials and notify the user agent when events such as successful sign in or sign out happen. This interface is accessible from [`Navigator.credentials`](navigator/credentials).



Instance properties
-------------------


None.


### Event handlers


None.


Instance methods
----------------


 
[`CredentialsContainer.create()`](credentialscontainer/create) Secure context
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with a new [`Credential`](credential) instance based on the provided options, or `null` if no `Credential` object can be created. In exceptional circumstances, the [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) may reject.

  
[`CredentialsContainer.get()`](credentialscontainer/get) Secure context
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with the [`Credential`](credential) instance that matches the provided parameters.

  
[`CredentialsContainer.preventSilentAccess()`](credentialscontainer/preventsilentaccess) Secure context
  Sets a flag that specifies whether automatic log in is allowed for future visits to the current origin, then returns an empty [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). For example, you might call this, after a user signs out of a website to ensure that they aren't automatically signed in on the next site visit. Earlier versions of the spec called this method `requireUserMediation()`. See [Browser compatibility](#browser_compatibility) for support details.

  
[`CredentialsContainer.store()`](credentialscontainer/store) Secure context
  Stores a set of credentials for a user, inside a provided [`Credential`](credential) instance and returns that instance in a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).

  
Examples
--------



```
// TBD

```

Specifications
--------------




| Specification |
| --- |
| [Credential Management Level 1 # credentialscontainer](https://w3c.github.io/webappsec-credential-management/#credentialscontainer) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CredentialsContainer` | 51 | 18 | 60 | No | 38 | 13 | 51 | 51 | 60 | 41 | 13 | 5.0 |
| `create` | 60 | 18 | 60 | No | 47 | 13 | 60 | 60 | 60 | 44 | 13 | 8.0 |
| `get` | 51 | 18 | 60 | No | 38 | 13 | 51 | 51 | 60 | 41 | 13 | 5.0 |
| `preventSilentAccess` | 6051–60 | 18 | 60 | No | 4738–47 | 13 | 6051–60 | 6051–60 | 60 | 4441–44 | 13 | 8.05.0–8.0 |
| `store` | 51 | 79 | 60 | No | 38 | 13 | 51 | 51 | 60 | 41 | 13 | 5.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer>

CSSAnimation
============



The `CSSAnimation` interface of the [Web Animations API](web_animations_api) represents an [`Animation`](animation) object.


 EventTarget Animation CSSAnimation

Instance properties
-------------------



*This interface inherits properties from its parent, [`Animation`](animation).*

  
[`CSSAnimation.animationName`](cssanimation/animationname) Read only 
  Returns the animation name as a string.

  

Instance methods
----------------


*This interface inherits methods from its parent, [`Animation`](animation).*


Examples
--------


### Inspecting the returned CSSAnimation



The animation in the following example is defined in CSS with the name `slide-in`. Calling [`Element.getAnimations()`](element/getanimations) returns an array of all [`Animation`](animation) objects. In our case this returns a `CSSAnimation` object, representing the animation created in CSS.

 
```
.animate {
  animation: slide-in 0.7s both;
}

@keyframes slide-in {
  0% {
    transform: translateY(-1000px);
  }
  100% {
    transform: translateY(0);
  }
}

```
 
```
let animations = document.querySelector(".animate").getAnimations();
console.log(animations[0]);

```


Specifications
--------------




| Specification |
| --- |
| [CSS Animations Level 2 # the-CSSAnimation-interface](https://w3c.github.io/csswg-drafts/css-animations-2/#the-CSSAnimation-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSAnimation` | 84 | 84 | 75 | No | 70 | 13.1 | 84 | 84 | 79 | 60 | 13.4 | 14.0 |
| `animationName` | 84 | 84 | 75 | No | 70 | 13.1 | 84 | 84 | 79 | 60 | 13.4 | 14.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSAnimation>

CSSConditionRule
================



An object implementing the `CSSConditionRule` interface represents a single condition CSS [at-rule](https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule), which consists of a condition and a statement block.

 Three objects derive from `CSSConditionRule`: [`CSSMediaRule`](cssmediarule), [`CSSContainerRule`](csscontainerrule) and [`CSSSupportsRule`](csssupportsrule).


 CSSRule CSSGroupingRule CSSConditionRule

Instance properties
-------------------



*Inherits properties from its ancestors [`CSSRule`](cssrule) and [`CSSGroupingRule`](cssgroupingrule).*

  [`CSSConditionRule.conditionText`](cssconditionrule/conditiontext)  Represents the text of the condition of the rule.

  

Instance methods
----------------


No specific methods; inherits methods from its ancestors [`CSSRule`](cssrule) and [`CSSGroupingRule`](cssgroupingrule).


Specifications
--------------




| Specification |
| --- |
| [CSS Conditional Rules Module Level 3 # the-cssconditionrule-interface](https://w3c.github.io/csswg-drafts/css-conditional-3/#the-cssconditionrule-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSConditionRule` | 56 | 12 | 20 | No | 43 | 14.1 | 56 | 56 | 20 | 43 | 14.5 | 6.0 |
| `conditionText` | 56 | 12 | 20 | No | 43 | 14.1 | 56 | 56 | 20 | 43 | 14.5 | 6.0 |


See also
--------


* [Using dynamic styling information](css_object_model/using_dynamic_styling_information)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSConditionRule>

CSSFontPaletteValuesRule
========================



The `CSSFontPaletteValuesRule` interface represents an [`@font-palette-values`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-palette-values) [at-rule](https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule).


 CSSRule CSSFontPaletteValuesRule

Instance properties
-------------------



*Inherits properties from its ancestor [`CSSRule`](cssrule).*

  
[`CSSFontPaletteValuesRule.name`](cssfontpalettevaluesrule/name) Read only 
  A string with the name of the font palette.

  
[`CSSFontPaletteValuesRule.fontFamily`](cssfontpalettevaluesrule/fontfamily) Read only 
  A string indicating the font families on which the rule has to be applied.

  
[`CSSFontPaletteValuesRule.basePalette`](cssfontpalettevaluesrule/basepalette) Read only 
  A string indicating the base palette associated with the rule.

  
[`CSSFontPaletteValuesRule.overrideColors`](cssfontpalettevaluesrule/overridecolors) Read only 
  A string indicating the colors of the base palette that are overwritten and the new colors.

  

Instance methods
----------------


*Inherits methods from its ancestor [`CSSRule`](cssrule).*


Examples
--------


### Read associated font family using CSSOM



This example first defines an [`@import`](https://developer.mozilla.org/en-US/docs/Web/CSS/@import) and an [`@font-palette-values`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-palette-values) at-rule. Then it reads the [`@font-palette-values`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-palette-values) rule and displays its name. As these rules live in the last stylesheet added to the document, the palette will be the second [`CSSRule`](cssrule) returned by the last stylesheet in the document (`document.styleSheets[document.styleSheets.length-1].cssRules`). So, `rules[1]` returns a [`CSSFontPaletteValuesRule`](cssfontpalettevaluesrule) object, from which we can access `fontFamily`.

 #### HTML

 
```
<pre id="log">The @font-palette-values at-rule font families:</pre>

```
 #### CSS

 
```
@import url(https://fonts.googleapis.com/css2?family=Bungee+Spice);

@font-palette-values --Alternate {
  font-family: "Bungee Spice";
  override-colors: 0 #00ffbb, 1 #007744;
}

.alternate {
  font-palette: --Alternate;
}

```
 #### JavaScript

 
```
const log = document.getElementById("log");

const rules = document.styleSheets[document.styleSheets.length - 1].cssRules;
const fontPaletteValuesRule = rules[1]; // aA CSSFontPaletteValuesRule interface
log.textContent += `${fontPaletteValuesRule.fontFamily}`;

```
 #### Result




Specifications
--------------




| Specification |
| --- |
| [CSS Fonts Module Level 4 # om-fontpalettevalues](https://w3c.github.io/csswg-drafts/css-fonts/#om-fontpalettevalues) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSFontPaletteValuesRule` | 101 | 101 | 107 | No | 87 | 15.4 | 101 | 101 | 107 | 70 | 15.4 | 19.0 |
| `basePalette` | 101 | 101 | 107 | No | 87 | 15.4 | 101 | 101 | 107 | 70 | 15.4 | 19.0 |
| `fontFamily` | 101 | 101 | 107 | No | 87 | 15.4 | 101 | 101 | 107 | 70 | 15.4 | 19.0 |
| `name` | 101 | 101 | 107 | No | 87 | 15.4 | 101 | 101 | 107 | 70 | 15.4 | 19.0 |
| `overrideColors` | 101 | 101 | 107 | No | 87 | 15.4 | 101 | 101 | 107 | 70 | 15.4 | 19.0 |


See also
--------


* [`@font-palette-values`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-palette-values)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSFontPaletteValuesRule>

CSSImageValue
=============



The `CSSImageValue` interface of the [CSS Typed Object Model API](css_object_model#css_typed_object_model) represents values for properties that take an image, for example [`background-image`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-image), [`list-style-image`](https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-image), or [`border-image-source`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-image-source).

 The CSSImageValue object represents an [`<image>`](https://developer.mozilla.org/en-US/docs/Web/CSS/image) that involves a URL, such as [`url()`](https://developer.mozilla.org/en-US/docs/Web/CSS/url) or [`image()`](https://developer.mozilla.org/en-US/docs/Web/CSS/image), but not [`linear-gradient()`](https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient) or [`element()`](https://developer.mozilla.org/en-US/docs/Web/CSS/element).


 CSSStyleValue CSSImageValue

Instance properties
-------------------


None.


Instance methods
----------------


*Inherits methods from [`CSSStyleValue`](cssstylevalue).*


Examples
--------



We create an element

 
```
<button>Magic Wand</button>

```
 We add some CSS, including a background image requesting a binary file:

 
```
button {
  display: inline-block;
  min-height: 100px;
  min-width: 100px;
  background: no-repeat 5% center url(magicwand.png) aqua;
}

```
 We get the element's style map. We then get() the background-image from the stylemap and stringify it:

 
```
// get the element
const button = document.querySelector("button");

// Retrieve all computed styles with computedStyleMap()
const allComputedStyles = button.computedStyleMap();

// Return the CSSImageValue Example
console.log(allComputedStyles.get("background-image"));
console.log(allComputedStyles.get("background-image").toString());

```



Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # imagevalue-objects](https://drafts.css-houdini.org/css-typed-om/#imagevalue-objects) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSImageValue` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |


See also
--------


* [`CSSKeywordValue`](csskeywordvalue)
* [`CSSNumericValue`](cssnumericvalue)
* [`CSSPositionValue`](csspositionvalue)
* [`CSSTransformValue`](csstransformvalue)
* [`CSSUnparsedValue`](cssunparsedvalue)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSImageValue>

CSSImportRule
=============



The `CSSImportRule` interface represents an [`@import`](https://developer.mozilla.org/en-US/docs/Web/CSS/@import) [at-rule](https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule).


 CSSRule CSSImportRule

Instance properties
-------------------



*Inherits properties from its ancestor [`CSSRule`](cssrule).*

  
[`CSSImportRule.href`](cssimportrule/href) Read only 
  Returns the URL specified by the [`@import`](https://developer.mozilla.org/en-US/docs/Web/CSS/@import) rule.

  
[`CSSImportRule.layerName`](cssimportrule/layername) Read only 
  Returns the name of the [cascade layer](https://developer.mozilla.org/en-US/docs/Web/CSS/@layer) declared in the [`@import`](https://developer.mozilla.org/en-US/docs/Web/CSS/@import) rule, the empty string if the layer is anonymous, the or `null` if the rule doesn't declare any.

  [`CSSImportRule.media`](cssimportrule/media)  Returns the value of the `media` attribute of the associated stylesheet.

  
[`CSSImportRule.styleSheet`](cssimportrule/stylesheet) Read only 
  Returns the associated stylesheet.

  

Instance methods
----------------


*Inherits methods from its ancestor [`CSSRule`](cssrule).*


Examples
--------



The document includes a single stylesheet which contains a single [`@import`](https://developer.mozilla.org/en-US/docs/Web/CSS/@import) rule. Therefore the first item in the list of CSS rules will be a `CSSImportRule`.

 
```
@import url("style.css") screen;

```
 
```
const myRules = document.styleSheets[0].cssRules;
console.log(myRules[0]); // A CSSImportRule instance object

```


Specifications
--------------




| Specification |
| --- |
| [CSS Object Model (CSSOM) # the-cssimportrule-interface](https://w3c.github.io/csswg-drafts/cssom/#the-cssimportrule-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSImportRule` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `href` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `layerName` | 99 | 99 | 97 | No | 85 | 15.4 | 99 | 99 | 97 | 68 | 15.4 | 18.0 |
| `media` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `styleSheet` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSImportRule>

CSSContainerRule
================



The `CSSContainerRule` interface represents a single CSS [`@container`](https://developer.mozilla.org/en-US/docs/Web/CSS/@container) rule.

  An object of this type can be used to get the query conditions for the [`@container`](https://developer.mozilla.org/en-US/docs/Web/CSS/@container), along with the container name if one is defined. Note that the container name and query together define the "condition text", which can be obtained using [`CSSConditionRule.conditionText`](cssconditionrule/conditiontext). 


 CSSRule CSSGroupingRule CSSConditionRule CSSContainerRule

Instance properties
-------------------



*Inherits properties from its ancestors [`CSSConditionRule`](cssconditionrule), [`CSSGroupingRule`](cssgroupingrule), and [`CSSRule`](cssrule).*

  
[`CSSContainerRule.containerName`](csscontainerrule/containername) Read only 
  Returns a string representing the name of an [`@container`](https://developer.mozilla.org/en-US/docs/Web/CSS/@container), or an empty string.

  
[`CSSContainerRule.containerQuery`](csscontainerrule/containerquery) Read only 
  Returns a string representing the set of features or "container conditions" that are evaluated to determine if the styles in the associated [`@container`](https://developer.mozilla.org/en-US/docs/Web/CSS/@container) are applied.

  

Instance methods
----------------


*No specific methods; inherits methods from its ancestors [`CSSConditionRule`](cssconditionrule), [`CSSGroupingRule`](cssgroupingrule), and [`CSSRule`](cssrule).*


Examples
--------


### Unnamed container rule



 The example below defines an unnamed [`@container`](https://developer.mozilla.org/en-US/docs/Web/CSS/@container) rule, and displays the properties of the associated [`CSSContainerRule`](csscontainerrule). The CSS is the same as in the `@container` example [Setting styles based on a container's size](https://developer.mozilla.org/en-US/docs/Web/CSS/@container#setting_styles_based_on_a_containers_size). 

 The first part of the code simply creates a list for logging the container rule properties, along with a JavaScript `log()` method to simplify adding the properties.

 
```
<div id="log">
  <h2>Log</h2>
  <ul></ul>
  <hr />
</div>

```
 
```
// Store reference to log list
const logList = document.querySelector("#log ul");
// Function to log data from underlying source
function log(result) {
  const listItem = document.createElement("li");
  listItem.textContent = result;
  logList.appendChild(listItem);
}

```
 Then we define the HTML for a `card` (`<div>`) contained within a `post`.

 
```
<div class="post">
  <div class="card">
    <h2>Card title</h2>
    <p>Card content</p>
  </div>
</div>

```
  The CSS for the example is shown below. As described in the corresponding [`@container`](https://developer.mozilla.org/en-US/docs/Web/CSS/@container) example, the CSS for the container element specifies the type of the container. The [`@container`](https://developer.mozilla.org/en-US/docs/Web/CSS/@container) then applies a new width, font-size and background color to the card if the width is less than 650px. 

 
```
<style id="examplestyles">
 /\* A container context based on inline size \*/
 .post {
 container-type: inline-size;
 }

 /\* Apply styles if the container is narrower than 650px \*/
 @container (width < 650px) {
 .card {
 width: 50%;
 background-color: gray;
 font-size: 1em;
 }
 }
</style>

```
  The code below gets the [`HTMLStyleElement`](htmlstyleelement) associated with the example using its id, and then uses its `sheet` property to get the [`StyleSheet`](stylesheet). From the `StyleSheet` we get the set of `cssRules` added to the sheet. Since we added added the `@container` as the second rule above, we can access the associated `CSSContainerRule` using the second entry, with index "1", in the `cssRules`. Last of all, we log the `containerName`, `containerQuery` and `conditionText` (inherited) properties. 

 
```
const exampleStylesheet = document.getElementById("examplestyles").sheet;
const exampleRules = exampleStylesheet.cssRules;
const containerRule = exampleRules[1]; // a CSSContainerRule representing the container rule.
log(`CSSContainerRule.containerName: "${containerRule.containerName}"`);
log(`CSSContainerRule.containerQuery: "${containerRule.containerQuery}"`);
log(`CSSContainerRule.conditionText: "${containerRule.conditionText}"`);

```
   **Note:** The styles for this example are defined in an inline HTML `style` element with an id in order to make it easy for the code to find the correct sheet. You might also locate the correct sheets for each example from the document by indexing against the length (e.g. `document.styleSheets[document.styleSheets.length-1]` but that makes working out correct sheet for each example more complicated). 

   The example output is shown below. The log section lists the `containerName`, which is an empty string as no name has been defined. The `containerQuery` and `conditionText` strings are also logged, and have the same value because there is no name defined. The card should change background and as the width of the page transitions through 650px. 




### Named container rule



 The example below defines a named [`@container`](https://developer.mozilla.org/en-US/docs/Web/CSS/@container) rule, and displays the properties of the associated [`CSSContainerRule`](csscontainerrule). The CSS is very similar to that in the `@container` example [Creating named container contexts](https://developer.mozilla.org/en-US/docs/Web/CSS/@container#creating_named_container_contexts). 

 First we define the HTML for a `card` (`<div>`) contained within a `post` (the example does not show the logging code, as this is the same as in the previous example).

 
```
<div class="post">
  <div class="card">
    <h2>Card title</h2>
    <p>Card content</p>
  </div>
</div>

```
  As described in [`@container`](https://developer.mozilla.org/en-US/docs/Web/CSS/@container), the CSS for the container element specifies the type of the container, and may also specify a name for the container. The card has a default font size, which is overridden for the `@container` named `sidebar` if the minimum width is greater than 700px. 

 
```
<style id="examplestyles">
 .post {
 container-type: inline-size;
 container-name: sidebar;
 }

 /\* Default heading styles for the card title \*/
 .card h2 {
 font-size: 1em;
 }

 @container sidebar (min-width: 700px) {
 .card {
 font-size: 2em;
 }
 }
</style>

```
  The code for getting the sheet and rules is almost identical to the previous example. The only difference is that in this example we have three CSS rules, so to get the associated `CSSContainerRule` we get the third entry in the `cssRules`. 

 
```
const exampleStylesheet = document.getElementById("examplestyles").sheet;
const exampleRules = exampleStylesheet.cssRules;
const containerRule = exampleRules[2]; // a CSSContainerRule representing the container rule.
log(`CSSContainerRule.containerName: "${containerRule.containerName}"`);
log(`CSSContainerRule.containerQuery: "${containerRule.containerQuery}"`);
log(`CSSContainerRule.conditionText: "${containerRule.conditionText}"`);

```
  The example output is shown below. The log section lists the `containerName` and `containerQuery` strings. The `conditionText` is also logged, and shows the combination of these two strings. The title in the card section should double in size as the width of the page goes over 700px. 




Specifications
--------------




| Specification |
| --- |
| [CSS Containment Module Level 3 # the-csscontainerrule-interface](https://w3c.github.io/csswg-drafts/css-contain-3/#the-csscontainerrule-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSContainerRule` | 105 | 105 | 110 | No | 91 | 16 | 105 | 105 | 110 | 72 | 16 | 20.0 |
| `containerName` | 111 | 111 | 110 | No | No | No | 111 | 111 | 110 | No | No | No |
| `containerQuery` | 111 | 111 | 110 | No | No | No | 111 | 111 | 110 | No | No | No |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSContainerRule>

CSSCounterStyleRule
===================



The `CSSCounterStyleRule` interface represents an [`@counter-style`](https://developer.mozilla.org/en-US/docs/Web/CSS/@counter-style) [at-rule](https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule).


 CSSRule CSSCounterStyleRule

Instance properties
-------------------



*This interface also inherits properties from its parent [`CSSRule`](cssrule).*

  [`CSSCounterStyleRule.name`](csscounterstylerule/name)  A string object that contains the serialization of the [`<custom-ident>`](https://developer.mozilla.org/en-US/docs/Web/CSS/custom-ident) defined as the `name` for the associated rule.

  [`CSSCounterStyleRule.system`](csscounterstylerule/system)  A string object that contains the serialization of the [`system`](https://developer.mozilla.org/en-US/docs/Web/CSS/@counter-style/system) descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string.

  [`CSSCounterStyleRule.symbols`](csscounterstylerule/symbols)  A string object that contains the serialization of the [`symbols`](https://developer.mozilla.org/en-US/docs/Web/CSS/@counter-style/symbols) descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string.

  [`CSSCounterStyleRule.additiveSymbols`](csscounterstylerule/additivesymbols)  A string object that contains the serialization of the [`additive-symbols`](https://developer.mozilla.org/en-US/docs/Web/CSS/@counter-style/additive-symbols) descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string.

  [`CSSCounterStyleRule.negative`](csscounterstylerule/negative)  A string object that contains the serialization of the [`negative`](https://developer.mozilla.org/en-US/docs/Web/CSS/@counter-style/negative) descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string.

  [`CSSCounterStyleRule.prefix`](csscounterstylerule/prefix)  A string object that contains the serialization of the [`prefix`](https://developer.mozilla.org/en-US/docs/Web/CSS/@counter-style/prefix) descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string.

  [`CSSCounterStyleRule.suffix`](csscounterstylerule/suffix)  A string object that contains the serialization of the [`suffix`](https://developer.mozilla.org/en-US/docs/Web/CSS/@counter-style/suffix) descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string.

  [`CSSCounterStyleRule.range`](csscounterstylerule/range)  A string object that contains the serialization of the [`range`](https://developer.mozilla.org/en-US/docs/Web/CSS/@counter-style/range) descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string.

  [`CSSCounterStyleRule.pad`](csscounterstylerule/pad)  A string object that contains the serialization of the [`pad`](https://developer.mozilla.org/en-US/docs/Web/CSS/@counter-style/pad) descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string.

  [`CSSCounterStyleRule.speakAs`](csscounterstylerule/speakas)  A string object that contains the serialization of the [`speak-as`](https://developer.mozilla.org/en-US/docs/Web/CSS/@counter-style/speak-as) descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string.

  [`CSSCounterStyleRule.fallback`](csscounterstylerule/fallback)  A string object that contains the serialization of the [`fallback`](https://developer.mozilla.org/en-US/docs/Web/CSS/@counter-style/fallback) descriptor defined for the associated rule. If the descriptor was not specified in the associated rule, the attribute returns an empty string.

  

Instance methods
----------------


*This interface doesn't implement any specific method but inherits methods from its parent [`CSSRule`](cssrule).*


Specifications
--------------




| Specification |
| --- |
| [CSS Counter Styles Level 3 # the-csscounterstylerule-interface](https://w3c.github.io/csswg-drafts/css-counter-styles/#the-csscounterstylerule-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSCounterStyleRule` | 91 | 91 | 33 | No | 77 | NoSee [bug 167645](https://webkit.org/b/167645). | 91 | 91 | 33 | 64 | NoSee [bug 167645](https://webkit.org/b/167645). | 16.0 |
| `additiveSymbols` | 91 | 91 | 33 | No | 77 | No | 91 | 91 | 33 | 64 | No | 16.0 |
| `fallback` | 91 | 91 | 33 | No | 77 | No | 91 | 91 | 33 | 64 | No | 16.0 |
| `name` | 91 | 91 | 33 | No | 77 | No | 91 | 91 | 33 | 64 | No | 16.0 |
| `negative` | 91 | 91 | 33 | No | 77 | No | 91 | 91 | 33 | 64 | No | 16.0 |
| `pad` | 91 | 91 | 33 | No | 77 | No | 91 | 91 | 33 | 64 | No | 16.0 |
| `prefix` | 91 | 91 | 33 | No | 77 | No | 91 | 91 | 33 | 64 | No | 16.0 |
| `range` | 91 | 91 | 33 | No | 77 | No | 91 | 91 | 33 | 64 | No | 16.0 |
| `speakAs` | 91 | 91 | 33 | No | 77 | No | 91 | 91 | 33 | 64 | No | 16.0 |
| `suffix` | 91 | 91 | 33 | No | 77 | No | 91 | 91 | 33 | 64 | No | 16.0 |
| `symbols` | 91 | 91 | 33 | No | 77 | No | 91 | 91 | 33 | 64 | No | 16.0 |
| `system` | 91 | 91 | 33 | No | 77 | No | 91 | 91 | 33 | 64 | No | 16.0 |


See also
--------


* [`@counter-style`](https://developer.mozilla.org/en-US/docs/Web/CSS/@counter-style)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSCounterStyleRule>

CSSFontFaceRule
===============



The `CSSFontFaceRule` interface represents an [`@font-face`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face) [at-rule](https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule).


 CSSRule CSSFontFaceRule

Instance properties
-------------------



*Inherits properties from its ancestor [`CSSRule`](cssrule).*

  
[`CSSFontFaceRule.style`](cssfontfacerule/style) Read only 
  Returns a [`CSSStyleDeclaration`](cssstyledeclaration).

  

Instance methods
----------------


*Inherits methods from its ancestor [`CSSRule`](cssrule).*


Examples
--------



This example uses the CSS found as an example on the [`@font-face`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face) page. The first [`CSSRule`](cssrule) returned will be a `CSSFontFaceRule`.

 
```
@font-face {
  font-family: MyHelvetica;
  src: local("Helvetica Neue Bold"), local("HelveticaNeue-Bold"),
    url(MgOpenModernaBold.ttf);
  font-weight: bold;
}

```
 
```
let myRules = document.styleSheets[0].cssRules;
console.log(myRules[0]); //a CSSFontFaceRule

```


Specifications
--------------




| Specification |
| --- |
| [CSS Fonts Module Level 4 # om-fontface](https://w3c.github.io/csswg-drafts/css-fonts/#om-fontface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSFontFaceRule` | 1 | 12 | 3.5 | 9 | ≤12.1 | 3.1 | 4.4 | 18 | 4 | ≤12.1 | 2 | 1.0 |
| `style` | 1 | 12 | 3.5 | 9 | ≤12.1 | 3.1 | 4.4 | 18 | 4 | ≤12.1 | 2 | 1.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSFontFaceRule>

CSSFontFeatureValuesRule
========================



The `CSSFontFeatureValuesRule` interface represents an [`@font-feature-values`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-feature-values) [at-rule](https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule), letting developers assign for each font face a common name to specify features indices to be used in [`font-variant-alternates`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant-alternates).


 CSSRule CSSFontFeatureValuesRule

Instance properties
-------------------



*Inherits properties from its ancestor [`CSSRule`](cssrule).*

  [`CSSFontFeatureValuesRule.fontFamily`](cssfontfeaturevaluesrule/fontfamily)  A string that identifies the font family this rule applies to.

  

Instance methods
----------------


*Inherits methods from its ancestor [`CSSRule`](cssrule).*


Examples
--------


### Read font family



In this example, we declare two [`@font-feature-values`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-feature-values) one for the *Font One* font family, and the other for *Font Two*. We then use the CSSOM to read these font families, displaying them into the log.

 #### HTML

 
```
<pre id="log"></pre>

```
 #### CSS

 
```
/\* At-rule for "nice-style" in Font One \*/
@font-feature-values Font One {
  @styleset {
    nice-style: 12;
  }
}

/\* At-rule for "nice-style" in Font Two \*/
@font-feature-values Font Two {
  @styleset {
    nice-style: 4;
  }
}

/\* Apply the at-rules with a single declaration \*/
.nice-look {
  font-variant-alternates: styleset(nice-style);
}

```
 #### JavaScript

 
```
const log = document.getElementById("log");
const rules = document.styleSheets[document.styleSheets.length - 1].cssRules;

const fontOne = rules[0]; // A CSSFontFeatureValuesRule
log.textContent = `The 1st '@font-feature-values' family: "${fontOne.fontFamily}".\n`;

const fontTwo = rules[1]; // Another CSSFontFeatureValuesRule
log.textContent += `The 2nd '@font-feature-values' family: "${fontTwo.fontFamily}".`;

```



Specifications
--------------




| Specification |
| --- |
| [CSS Fonts Module Level 4 # cssfontfeaturevaluesrule](https://w3c.github.io/csswg-drafts/css-fonts/#cssfontfeaturevaluesrule) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSFontFeatureValuesRule` | 111 | 111 | 34 | No | 97 | 16.2 | 111 | 111 | 34 | No | 16.2 | No |
| `annotation` | 111 | No | No | No | No | No | 111 | 111 | No | No | No | No |
| `characterVariant` | 111 | No | No | No | No | No | 111 | 111 | No | No | No | No |
| `fontFamily` | 111 | 111 | 34 | No | 97 | 16.2 | 111 | 111 | 34 | No | 16.2 | No |
| `ornaments` | 111 | No | No | No | No | No | 111 | 111 | No | No | No | No |
| `styleset` | 111 | No | No | No | No | No | 111 | 111 | No | No | No | No |
| `stylistic` | 111 | No | No | No | No | No | 111 | 111 | No | No | No | No |
| `swash` | 111 | No | No | No | No | No | 111 | 111 | No | No | No | No |


See also
--------


* [`@font-feature-values`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-feature-values)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSFontFeatureValuesRule>

CSSGroupingRule
===============



The `CSSGroupingRule` interface of the [CSS Object Model](css_object_model) represents any CSS [at-rule](https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule) that contains other rules nested within it.


 CSSRule CSSGroupingRule

Instance properties
-------------------



*This interface also inherits properties from [`CSSRule`](cssrule).*

  
[`CSSGroupingRule.cssRules`](cssgroupingrule/cssrules) Read only 
  Returns a [`CSSRuleList`](cssrulelist) of the CSS rules in the media rule.

  

Instance methods
----------------



*This interface also inherits methods from [`CSSRule`](cssrule).*

  [`CSSGroupingRule.deleteRule`](cssgroupingrule/deleterule)  Deletes a rule from the style sheet.

  [`CSSGroupingRule.insertRule`](cssgroupingrule/insertrule)  Inserts a new style rule into the current style sheet.

  

Specifications
--------------




| Specification |
| --- |
| [CSS Object Model (CSSOM) # the-cssgroupingrule-interface](https://w3c.github.io/csswg-drafts/cssom/#the-cssgroupingrule-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSGroupingRule` | 45 | 12 | 20 | No | 32 | 14.1 | 45 | 45 | 20 | 32 | 14.5 | 5.0 |
| `cssRules` | 45 | 12 | 20 | No | 32 | 14.1 | 45 | 45 | 20 | 32 | 14.5 | 5.0 |
| `deleteRule` | 45 | 12 | 20 | No | 32 | 14.1 | 45 | 45 | 20 | 32 | 14.5 | 5.0 |
| `insertRule` | 45 | 12 | 20 | No | 32 | 14.1 | 45 | 45 | 20 | 32 | 14.5 | 5.0 |


See also
--------


* [Using dynamic styling information](css_object_model/using_dynamic_styling_information)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSGroupingRule>

CSSKeyframeRule
===============



The `CSSKeyframeRule` interface describes an object representing a set of styles for a given keyframe. It corresponds to the contents of a single keyframe of a [`@keyframes`](https://developer.mozilla.org/en-US/docs/Web/CSS/@keyframes) [at-rule](https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule).


 CSSRule CSSKeyframeRule

Instance properties
-------------------



*Inherits properties from its ancestor [`CSSRule`](cssrule).*

  [`CSSKeyframeRule.keyText`](csskeyframerule/keytext)  Represents the key of the keyframe, like `'10%'`, `'75%'`. The `from` keyword maps to `'0%'` and the `to` keyword maps to `'100%'`.

  
[`CSSKeyframeRule.style`](csskeyframerule/style) Read only 
  Returns a [`CSSStyleDeclaration`](cssstyledeclaration) of the CSS style associated with the keyframe.

  

Instance methods
----------------


*No specific methods; inherits methods from its ancestor [`CSSRule`](cssrule).*


Examples
--------



 The CSS includes a keyframes at-rule. This will be the first [`CSSRule`](cssrule) returned by `document.styleSheets[0].cssRules`. `myRules[0]` returns a [`CSSKeyframesRule`](csskeyframesrule) object, which will contain individual `CSSKeyFrameRule` objects for each keyframe. 

 
```
@keyframes slidein {
  from {
    transform: translateX(0%);
  }

  to {
    transform: translateX(100%);
  }
}

```
 
```
let myRules = document.styleSheets[0].cssRules;
let keyframes = myRules[0]; // a CSSKeyframesRule
console.log(keyframes[0]); // a CSSKeyframeRule representing an individual keyframe.

```


Specifications
--------------




| Specification |
| --- |
| [CSS Animations Level 1 # interface-csskeyframerule](https://w3c.github.io/csswg-drafts/css-animations/#interface-csskeyframerule) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSKeyframeRule` | 311–31 | 12 | 485–48 | 10 | 1815–1812–15 | 94–9 | 4.4.31–4.4.3 | 3118–31 | 485–48 | 1814–1812–14 | 93.2–9 | 2.01.0–2.0 |
| `keyText` | 1 | 12 | 5 | 10 | 12 | 4 | 4.4 | 18 | 5 | 12 | 4 | 1.0 |
| `style` | 1 | 12 | 5 | 10 | 12 | 4 | 4.4 | 18 | 5 | 12 | 3.2 | 1.0 |


See also
--------


* [`@keyframes`](https://developer.mozilla.org/en-US/docs/Web/CSS/@keyframes)
* [`CSSKeyFramesRule`](csskeyframesrule)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSKeyframeRule>

CSSKeyframesRule
================



The `CSSKeyframesRule` interface describes an object representing a complete set of keyframes for a CSS animation. It corresponds to the contents of a whole [`@keyframes`](https://developer.mozilla.org/en-US/docs/Web/CSS/@keyframes) [at-rule](https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule).


 CSSRule CSSKeyframesRule

Instance properties
-------------------



*Inherits properties from its ancestor [`CSSRule`](cssrule).*

  [`CSSKeyframesRule.name`](csskeyframesrule/name)  Represents the name of the keyframes, used by the [`animation-name`](https://developer.mozilla.org/en-US/docs/Web/CSS/animation-name) property.

  
[`CSSKeyframesRule.cssRules`](csskeyframesrule/cssrules) Read only 
  Returns a [`CSSRuleList`](cssrulelist) of the keyframes in the list.

  

Instance methods
----------------



*Inherits methods from its ancestor [`CSSRule`](cssrule).*

  [`CSSKeyframesRule.appendRule()`](csskeyframesrule/appendrule)  Inserts a new keyframe rule into the current CSSKeyframesRule. The parameter is a string containing a keyframe in the same format as an entry of a [`@keyframes`](https://developer.mozilla.org/en-US/docs/Web/CSS/@keyframes) at-rule. If it contains more than one keyframe rule, a [`DOMException`](domexception) with a `SYNTAX_ERR` is thrown.

  [`CSSKeyframesRule.deleteRule()`](csskeyframesrule/deleterule)  Deletes a keyframe rule from the current CSSKeyframesRule. The parameter is the index of the keyframe to be deleted, expressed as a string resolving as a number between `0%` and `100%`.

  [`CSSKeyframesRule.findRule()`](csskeyframesrule/findrule)  Returns a keyframe rule corresponding to the given key. The key is a string containing an index of the keyframe to be returned, resolving to a percentage between `0%` and `100%`. If no such keyframe exists, `findRule` returns `null`.

  

Example
-------



 The CSS includes a keyframes at-rule. This will be the first [`CSSRule`](cssrule) returned by `document.styleSheets[0].cssRules`. `myRules[0]` returns a `CSSKeyframesRule` object. 

 
```
@keyframes slidein {
  from {
    transform: translateX(0%);
  }

  to {
    transform: translateX(100%);
  }
}

```
 
```
let myRules = document.styleSheets[0].cssRules;
let keyframes = myRules[0]; // a CSSKeyframesRule

```


Specifications
--------------




| Specification |
| --- |
| [CSS Animations Level 1 # interface-csskeyframesrule](https://w3c.github.io/csswg-drafts/css-animations/#interface-csskeyframesrule) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSKeyframesRule` | 311–31 | 12 | 485–48 | 10 | 1815–1812.1–1512–12.1 | 9.14–9.1 | 4.4.31–4.4.3 | 3118–31 | 485–48 | 1814–1812.1–1412–12.1 | 9.33.2–9.3 | 2.01.0–2.0 |
| `appendRule` | 411–45 | 12 | 215–21 | 10 | 2815–3112–15 | 9.14 | 414.4–45 | 4118–45 | 215–21 | 2814–3212–14 | 9.33.2 | 4.01.0–5.0 |
| `cssRules` | 1 | 12 | 5 | 10 | 12 | 4 | 4.4 | 18 | 5 | 12 | 3.2 | 1.0 |
| `deleteRule` | 1 | 12 | 5 | 10 | 12 | 4 | 4.4 | 18 | 5 | 12 | 3.2 | 1.0 |
| `findRule` | 1 | 12 | 5 | 10 | 12 | 4 | 4.4 | 18 | 5 | 12 | 3.2 | 1.0 |
| `length` | No | No | 109 | No | No | No | No | No | 109 | No | No | No |
| `name` | 1 | 12 | 5 | 10 | 12 | 4 | 4.4 | 18 | 5 | 12 | 3.2 | 1.0 |


See also
--------


* [`@keyframes`](https://developer.mozilla.org/en-US/docs/Web/CSS/@keyframes)
* [`CSSKeyFrameRule`](csskeyframerule)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSKeyframesRule>

CSSKeywordValue
===============



The `CSSKeywordValue` interface of the [CSS Typed Object Model API](css_object_model#css_typed_object_model) creates an object to represent CSS keywords and other identifiers.

 The interface instance name is a [stringifier](https://developer.mozilla.org/en-US/docs/Glossary/Stringifier) meaning that when used anywhere a string is expected it will return the value of `CSSKeyword.value`.


 CSSStyleValue CSSKeywordValue

Constructor
-----------


 [`CSSKeywordValue()`](csskeywordvalue/csskeywordvalue)  Creates a new `CSSKeywordValue` object.

  
Instance properties
-------------------


 [`CSSKeywordValue.value`](csskeywordvalue/value)  Returns or sets the value of the `CSSKeywordValue`.

  
Instance methods
----------------


*Inherits methods from [`CSSStyleValue`](cssstylevalue).*


Examples
--------



The following example resets the CSS [`display`](https://developer.mozilla.org/en-US/docs/Web/CSS/display) property to its defaults, setting the inline [`style`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/style) attribute to `style="display: initial"` if viewed in the [developer tools inspector](https://firefox-source-docs.mozilla.org/devtools-user/page_inspector/how_to/select_an_element/index.html).

 
```
let myElement = document.getElementById("myElement").attributeStyleMap;
myElement.set("display", new CSSKeywordValue("initial"));

console.log(myElement.get("display").value); // 'initial'

```



Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # keywordvalue-objects](https://drafts.css-houdini.org/css-typed-om/#keywordvalue-objects) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSKeywordValue` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `CSSKeywordValue` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `value` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |


See also
--------


* [`CSSImageValue`](cssimagevalue)
* [`CSSNumericValue`](cssnumericvalue)
* [`CSSPositionValue`](csspositionvalue)
* [`CSSTransformValue`](csstransformvalue)
* [`CSSUnparsedValue`](cssunparsedvalue)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSKeywordValue>

CSSLayerBlockRule
=================



The `CSSLayerBlockRule` represents a [`@layer`](https://developer.mozilla.org/en-US/docs/Web/CSS/@layer) block rule. It is a grouping at-rule meaning that it can contain other rules, and is associated to a given cascade layer, identified by its *name*.


 CSSRule CSSGroupingRule CSSLayerBlockRule

Instance properties
-------------------



*Also inherits properties from its parent interface, [`CSSGroupingRule`](cssgroupingrule).*

 * [`CSSLayerBlockRule.name`](csslayerblockrule/name) Read only 
	+ A string containing the name of the associated cascade layer.



Instance methods
----------------


*Inherits methods from its parent interface, [`CSSGroupingRule`](cssgroupingrule).*


Examples
--------


### HTML



```
<p>I am displayed in <code>color: rebeccapurple</code>.</p>

```

### CSS



```
@layer special {
  p {
    color: rebeccapurple;
  }
}

```

### JavaScript



```
const item = document.getElementsByTagName("p")[0];
const rules = document.styleSheets[1].cssRules;
// Note that stylesheet #1 is the stylesheet associated with this embedded example,
// while stylesheet #0 is the stylesheet associated with the whole MDN page

const layer = rules[0]; // A CSSLayerBlockRule

item.textContent = `The CSSLayerBlockRule is for the "${layer.name}" layer`;

```

### Result



Specifications
--------------




| Specification |
| --- |
| [CSS Cascading and Inheritance Level 5 # csslayerblockrule](https://w3c.github.io/csswg-drafts/css-cascade-5/#csslayerblockrule) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSLayerBlockRule` | 99 | 99 | 97 | No | 85 | 15.4 | 99 | 99 | 97 | 68 | 15.4 | 18.0 |
| `name` | 99 | 99 | 97 | No | 85 | 15.4 | 99 | 99 | 97 | 68 | 15.4 | 18.0 |


See also
--------


* [`@layer`](https://developer.mozilla.org/en-US/docs/Web/CSS/@layer)
* [`CSSLayerStatementRule`](csslayerstatementrule)
* [Learn CSS cascade layers](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Cascade_layers)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSLayerBlockRule>

CSSLayerStatementRule
=====================



The `CSSLayerStatementRule` represents a [`@layer`](https://developer.mozilla.org/en-US/docs/Web/CSS/@layer) statement rule. Unlike [`CSSLayerBlockRule`](csslayerblockrule), it doesn't contain other rules and merely defines one or several layers by providing their names.

 This rule allows to explicitly declare the ordering layer that is in an apparent way at the beginning of a CSS file: the layer order is defined by the order of first occurrence of each layer name. Declaring them with a statement allows the reader to understand the layer order. It also allows inline and imported layers to be interleaved, which is not possible when using the `CSSLayerBlockRule` syntax.


 CSSRule CSSLayerStatementRule

Instance properties
-------------------



*Also inherits properties from its parent interface, [`CSSRule`](cssrule).*

 * [`CSSLayerStatementRule.nameList`](csslayerstatementrule/namelist) Read only 
	+ An array of strings, that represent the name of each cascade layer by the rule



Examples
--------


### HTML



```
<p></p>

```

### CSS



```
@layer layerName, layerName2;

```

### JavaScript



```
const item = document.getElementsByTagName("p")[0];
const rules = document.styleSheets[1].cssRules;
// Note that stylesheet #1 is the stylesheet associated with this embedded example,
// while stylesheet #0 is the stylesheet associated with the whole MDN page

const layer = rules[0]; // A CSSLayerStatementRule

item.textContent = `The CSS @layer statement declares the following layers: ${layer.nameList.join(
 ", "
)}.`;

```

### Result



Specifications
--------------




| Specification |
| --- |
| [CSS Cascading and Inheritance Level 5 # csslayerstatementrule](https://w3c.github.io/csswg-drafts/css-cascade-5/#csslayerstatementrule) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSLayerStatementRule` | 99 | 99 | 97 | No | 85 | 15.4 | 99 | 99 | 97 | 68 | 15.4 | 18.0 |
| `nameList` | 99 | 99 | 97 | No | 85 | 15.4 | 99 | 99 | 97 | 68 | 15.4 | 18.0 |


See also
--------


* [`@layer`](https://developer.mozilla.org/en-US/docs/Web/CSS/@layer)
* [The `@layer` statement at-rule for named layers](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Cascade_layers#the_layer_statement_at-rule_for_named_layers)
* [`CSSLayerBlockRule`](csslayerblockrule)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSLayerStatementRule>

CSSMathInvert
=============



The `CSSMathInvert` interface of the [CSS\_Object\_Model#css\_typed\_object\_model](css_object_model#css_typed_object_model) represents a CSS [`calc()`](https://developer.mozilla.org/en-US/docs/Web/CSS/calc) used as `calc(1 / <value>).` It inherits properties and methods from its parent [`CSSNumericValue`](cssnumericvalue).


 CSSStyleValue CSSNumericValue CSSMathValue CSSMathInvert

Constructor
-----------


 [`CSSMathInvert()`](cssmathinvert/cssmathinvert)  Creates a new `CSSMathInvert` object.

  
Instance properties
-------------------


 
[`CSSMathInvert.value`](cssmathinvert/value) Read only 
  Returns a [`CSSNumericValue`](cssnumericvalue) object.

  
Static methods
--------------


*The interface may also inherit methods from its parent interface, [`CSSMathValue`](cssmathvalue).*


Instance methods
----------------


*The interface may also inherit methods from its parent interface, [`CSSMathValue`](cssmathvalue).*


Examples
--------


To do


Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # cssmathinvert](https://drafts.css-houdini.org/css-typed-om/#cssmathinvert) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSMathInvert` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `CSSMathInvert` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `value` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSMathInvert>

CSSMathMax
==========



The `CSSMathMax` interface of the [CSS\_Object\_Model#css\_typed\_object\_model](css_object_model#css_typed_object_model) represents the CSS [`max()`](https://developer.mozilla.org/en-US/docs/Web/CSS/max) function. It inherits properties and methods from its parent [`CSSNumericValue`](cssnumericvalue).


 CSSStyleValue CSSNumericValue CSSMathValue CSSMathMax

Constructor
-----------


 
[`CSSMathMax()`](cssmathmax/cssmathmax)  Experimental 
  Creates a new `CSSMathMax` object.

  
Instance properties
-------------------


 
[`CSSMathMax.values`](cssmathmax/values) Read only 
  Returns a [`CSSNumericArray`](cssnumericarray) object which contains one or more [`CSSNumericValue`](cssnumericvalue) objects.

  
Static methods
--------------


*The interface may also inherit methods from its parent interface, [`CSSMathValue`](cssmathvalue).*


Instance methods
----------------


*The interface may also inherit methods from its parent interface, [`CSSMathValue`](cssmathvalue).*


Examples
--------


To do


Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # cssmathmax](https://drafts.css-houdini.org/css-typed-om/#cssmathmax) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSMathMax` | 66 | 79 | No | No | 53 | No | 66 | 66 | No | 47 | No | 9.0 |
| `CSSMathMax` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `values` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSMathMax>

CSSMathMin
==========



The `CSSMathMin` interface of the [CSS\_Object\_Model#css\_typed\_object\_model](css_object_model#css_typed_object_model) represents the CSS [`min()`](https://developer.mozilla.org/en-US/docs/Web/CSS/min) function. It inherits properties and methods from its parent [`CSSNumericValue`](cssnumericvalue).


 CSSStyleValue CSSNumericValue CSSMathValue CSSMathMin

Constructor
-----------


 
[`CSSMathMin()`](cssmathmin/cssmathmin)  Experimental 
  Creates a new `CSSMathMin` object.

  
Instance properties
-------------------


 
[`CSSMathMin.values`](cssmathmin/values) Read only 
  Returns a [`CSSNumericArray`](cssnumericarray) object which contains one or more [`CSSNumericValue`](cssnumericvalue) objects.

  
Static methods
--------------


*The interface may also inherit methods from its parent interface, [`CSSMathValue`](cssmathvalue).*


Instance methods
----------------


*The interface may also inherit methods from its parent interface, [`CSSMathValue`](cssmathvalue).*


Examples
--------


To do


Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # cssmathmin](https://drafts.css-houdini.org/css-typed-om/#cssmathmin) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSMathMin` | 66 | 79 | No | No | 53 | No | 66 | 66 | No | 47 | No | 9.0 |
| `CSSMathMin` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `values` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSMathMin>

CSSMathNegate
=============



The `CSSMathNegate` interface of the [CSS\_Object\_Model#css\_typed\_object\_model](css_object_model#css_typed_object_model) negates the value passed into it. It inherits properties and methods from its parent [`CSSNumericValue`](cssnumericvalue).


 CSSStyleValue CSSNumericValue CSSMathValue CSSMathNegate

Constructor
-----------


 [`CSSMathNegate()`](cssmathnegate/cssmathnegate)  Creates a new `CSSMathNegate` object.

  
Instance properties
-------------------


 
[`CSSMathNegate.value`](cssmathnegate/value) Read only 
  Returns a [`CSSNumericValue`](cssnumericvalue) object.

  
Static methods
--------------


*The interface may also inherit methods from its parent interface, [`CSSMathValue`](cssmathvalue).*


Instance methods
----------------


*The interface may also inherit methods from its parent interface, [`CSSMathValue`](cssmathvalue).*


Examples
--------


To do


Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # cssmathnegate](https://drafts.css-houdini.org/css-typed-om/#cssmathnegate) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSMathNegate` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `CSSMathNegate` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `value` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSMathNegate>

CSSMathProduct
==============



The `CSSMathProduct` interface of the [CSS\_Object\_Model#css\_typed\_object\_model](css_object_model#css_typed_object_model) represents the result obtained by calling [`add()`](cssnumericvalue/add), [`sub()`](cssnumericvalue/sub), or [`toSum()`](cssnumericvalue/tosum) on [`CSSNumericValue`](cssnumericvalue). It inherits properties and methods from its parent [`CSSNumericValue`](cssnumericvalue).


 CSSStyleValue CSSNumericValue CSSMathValue CSSMathProduct

Constructor
-----------


 
[`CSSMathProduct()`](cssmathproduct/cssmathproduct)  Experimental 
  Creates a new `CSSMathProduct` object.

  
Instance properties
-------------------


 [`CSSMathProduct.values`](cssmathproduct/values)  Returns a [`CSSNumericArray`](cssnumericarray) object which contains one or more [`CSSNumericValue`](cssnumericvalue) objects.

  
Static methods
--------------


*The interface may also inherit methods from its parent interface, [`CSSMathValue`](cssmathvalue).*


Instance methods
----------------


*The interface may also inherit methods from its parent interface, [`CSSMathValue`](cssmathvalue).*


Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # cssmathproduct](https://drafts.css-houdini.org/css-typed-om/#cssmathproduct) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSMathProduct` | 66 | 79 | No | No | 53 | No | 66 | 66 | No | 47 | No | 9.0 |
| `CSSMathProduct` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `values` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSMathProduct>

CSSMathSum
==========



The `CSSMathSum` interface of the [CSS\_Object\_Model#css\_typed\_object\_model](css_object_model#css_typed_object_model) represents the result obtained by calling [`add()`](cssnumericvalue/add), [`sub()`](cssnumericvalue/sub), or [`toSum()`](cssnumericvalue/tosum) on [`CSSNumericValue`](cssnumericvalue).

 A CSSMathSum is the object type returned when the [`StylePropertyMapReadOnly.get()`](stylepropertymapreadonly/get) method is used on a CSS property whose value is created with a [`calc()`](https://developer.mozilla.org/en-US/docs/Web/CSS/calc) function.


 CSSStyleValue CSSNumericValue CSSMathValue CSSMathSum

Constructor
-----------


 
[`CSSMathSum()`](cssmathsum/cssmathsum)  Experimental 
  Creates a new `CSSMathSum` object.

  
Instance properties
-------------------


 [`CSSMathSum.values`](cssmathsum/values)  Returns a [`CSSNumericArray`](cssnumericarray) object which contains one or more [`CSSNumericValue`](cssnumericvalue) objects.

  
Static methods
--------------


*The interface may also inherit methods from its parent interface, [`CSSMathValue`](cssmathvalue).*


Instance methods
----------------


*The interface may also inherit methods from its parent interface, [`CSSMathValue`](cssmathvalue).*


Event handlers
--------------


No


Examples
--------



We create an element with a [`width`](https://developer.mozilla.org/en-US/docs/Web/CSS/width) determined using a [`calc()`](https://developer.mozilla.org/en-US/docs/Web/CSS/calc) function, then [`console.log()`](console/log) the `operator` and `values`, and dig into the values a bit.

 
```
<div>has width</div>

```
 We assign a `width`

 
```
div {
  width: calc(30% - 20px);
}

```
 We add the JavaScript

 
```
const styleMap = document.querySelector("div").computedStyleMap();

console.log(styleMap.get("width")); // CSSMathSum {values: CSSNumericArray, operator: "sum"}
console.log(styleMap.get("width").operator); // 'sum'
console.log(styleMap.get("width").values); // CSSNumericArray {0: CSSUnitValue, 1: CSSUnitValue, length: 2}
console.log(styleMap.get("width").values[0]); // CSSUnitValue {value: 30, unit: "percent"}
console.log(styleMap.get("width").values[0].value); // 30
console.log(styleMap.get("width").values[0].unit); // 'percent'
console.log(styleMap.get("width").values[1]); // CSSUnitValue {value: -20, unit: "px"}
console.log(styleMap.get("width").values[1].value); // -20
console.log(styleMap.get("width").values[1].unit); // 'px'

```

 The specification is still evolving. In the future we may write the last three lines as:

 
```
console.log(styleMap.get("width").values[1]); // CSSMathNegate {value: CSSUnitValue, operator: "negate"}
console.log(styleMap.get("width").values[1].value); // CSSUnitValue {value: 20, unit: "px"}
console.log(styleMap.get("width").values[1].value.unit); // 'px'

```


Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # cssmathsum](https://drafts.css-houdini.org/css-typed-om/#cssmathsum) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSMathSum` | 66 | 79 | No | No | 53 | No | 66 | 66 | No | 47 | No | 9.0 |
| `CSSMathSum` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `values` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSMathSum>

CSSMathValue
============



The `CSSMathValue` interface of the [CSS\_Object\_Model#css\_typed\_object\_model](css_object_model#css_typed_object_model) a base class for classes representing complex numeric values.


 CSSStyleValue CSSNumericValue CSSMathValue

Interfaces based on CSSMathValue
--------------------------------



Below is a list of interfaces based on the CSSMathValue interface.

 * [`CSSMathInvert`](cssmathinvert)
* [`CSSMathMax`](cssmathmax)
* [`CSSMathMin`](cssmathmin)
* [`CSSMathNegate`](cssmathnegate)
* [`CSSMathProduct`](cssmathproduct)
* [`CSSMathSum`](cssmathsum)



Instance properties
-------------------


 [`CSSMathValue.operator`](cssmathvalue/operator)  Indicates the operator that the current subtype represents.

  
Static methods
--------------


*The interface may also inherit methods from its parent interface, [`CSSNumericValue`](cssnumericvalue).*


Instance methods
----------------


*The interface may also inherit methods from its parent interface, [`CSSNumericValue`](cssnumericvalue).*


Event handlers
--------------


No


Examples
--------



We create an element with a [`width`](https://developer.mozilla.org/en-US/docs/Web/CSS/width) determined using a [`calc()`](https://developer.mozilla.org/en-US/docs/Web/CSS/calc) function, then [`console.log()`](console/log) the `operator`.

 
```
<div>has width</div>

```
 We assign a `width` with a calculation

 
```
div {
  width: calc(30% - 20px);
}

```
 We add the JavaScript

 
```
const styleMap = document.querySelector("div").computedStyleMap();

console.log(styleMap.get("width")); // CSSMathSum {values: CSSNumericArray, operator: "sum"}
console.log(styleMap.get("width").operator); // 'sum'
console.log(styleMap.get("width").values[1].value); // -20

```

 The `CSSMathValue.operator` returns '`sum`' because `styleMap.get('width').values[1].value );` is `-20`: adding a negative number.



Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # complex-numeric](https://drafts.css-houdini.org/css-typed-om/#complex-numeric) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSMathValue` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `operator` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSMathValue>

CSSMatrixComponent
==================



The `CSSMatrixComponent` interface of the [CSS\_Object\_Model#css\_typed\_object\_model](css_object_model#css_typed_object_model) represents the [matrix()](https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/matrix) and [matrix3d()](https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/matrix3d) values of the individual [`transform`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform) property in CSS. It inherits properties and methods from its parent [`CSSTransformValue`](csstransformvalue).


 CSSTransformComponent CSSMatrixComponent

Constructor
-----------


 [`CSSMatrixComponent()`](cssmatrixcomponent/cssmatrixcomponent)  Creates a new `CSSMatrixComponent` object.

  
Instance properties
-------------------


 [`matrix`](cssmatrixcomponent/matrix)  A matrix.

  
Examples
--------


To do.


Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # cssmatrixcomponent](https://drafts.css-houdini.org/css-typed-om/#cssmatrixcomponent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSMatrixComponent` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `CSSMatrixComponent` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `matrix` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSMatrixComponent>

CSSMediaRule
============



The `CSSMediaRule` interface represents a single CSS [`@media`](https://developer.mozilla.org/en-US/docs/Web/CSS/@media) rule.


 CSSRule CSSGroupingRule CSSConditionRule CSSMediaRule

Instance properties
-------------------



*Inherits properties from its ancestors [`CSSConditionRule`](cssconditionrule), [`CSSGroupingRule`](cssgroupingrule), and [`CSSRule`](cssrule).*

  
[`CSSMediaRule.media`](cssmediarule/media) Read only 
  Returns a [`MediaList`](medialist) representing the intended destination medium for style information.

  

Instance methods
----------------


*No specific methods; inherits methods from its ancestors [`CSSConditionRule`](cssconditionrule), [`CSSGroupingRule`](cssgroupingrule), and [`CSSRule`](cssrule).*


Examples
--------



 The CSS below includes a media query with one style rule. As this rule lives in the last stylesheet added to the document, it will be the first CSSRule returned by the last stylesheet in the document (`document.styleSheets[document.styleSheets.length-1].cssRules`). `myRules[0]` returns a [`CSSMediaRule`](cssmediarule) object, from which we can get the `mediaText`. 

 
```
<p id="log"></p>

```
 
```
@media (min-width: 500px) {
  body {
    color: blue;
  }
}

```
 
```
const log = document.getElementById("log");
const myRules = document.styleSheets[document.styleSheets.length - 1].cssRules;
const mediaList = myRules[0]; // a CSSMediaRule representing the media query.
log.textContent += `${mediaList.media.mediaText}`;

```



Specifications
--------------




| Specification |
| --- |
| [CSS Conditional Rules Module Level 3 # the-cssmediarule-interface](https://w3c.github.io/csswg-drafts/css-conditional-3/#the-cssmediarule-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSMediaRule` | 1 | 12 | 1Before Firefox 20, `conditionText` could not be set. | 9 | ≤12.1 | 3 | 4.4 | 18 | 4Before Firefox 20, `conditionText` could not be set. | ≤12.1 | 1 | 1.0 |
| `media` | 1 | 12 | 1 | 9 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSMediaRule>

CSSNamespaceRule
================



The `CSSNamespaceRule` interface describes an object representing a single CSS [`@namespace`](https://developer.mozilla.org/en-US/docs/Web/CSS/@namespace) [at-rule](https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule).


 CSSRule CSSNamespaceRule

Instance properties
-------------------



*Inherits properties from its ancestor [`CSSRule`](cssrule).*

  [`CSSNamespaceRule.namespaceURI`](cssnamespacerule/namespaceuri)  Returns a string containing the text of the URI of the given namespace.

  [`CSSNamespaceRule.prefix`](cssnamespacerule/prefix)  Returns a string with the name of the prefix associated to this namespace. If there is no such prefix, returns an empty string.

  

Instance methods
----------------


*Inherits methods from its ancestor [`CSSRule`](cssrule).*


Examples
--------



The stylesheet includes a namespace as the only rule. Therefore the first [`CSSRule`](cssrule) returned will be a `CSSNamespaceRule`.

 
```
@namespace url(http://www.w3.org/1999/xhtml);

```
 
```
let myRules = document.styleSheets[0].cssRules;
console.log(myRules[0]); //a CSSNamespaceRule

```


Specifications
--------------




| Specification |
| --- |
| [CSS Object Model (CSSOM) # the-cssnamespacerule-interface](https://w3c.github.io/csswg-drafts/cssom/#the-cssnamespacerule-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSNamespaceRule` | 47 | 12 | 53 | 9 | 36 | 10.1 | 47 | 47 | 53 | 36 | 10.3 | 5.0 |
| `namespaceURI` | 47 | 12 | 59 | 9 | 36 | 10.1 | 47 | 47 | 59 | 36 | 10.3 | 5.0 |
| `prefix` | 47 | 12 | 59 | 9 | 36 | 10.1 | 47 | 47 | 59 | 36 | 10.3 | 5.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSNamespaceRule>

CSSPerspective
==============



The `CSSPerspective` interface of the [CSS\_Object\_Model#css\_typed\_object\_model](css_object_model#css_typed_object_model) represents the [perspective()](https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/perspective) value of the individual [`transform`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform) property in CSS. It inherits properties and methods from its parent [`CSSTransformValue`](csstransformvalue).


 CSSTransformComponent CSSPerspective

Constructor
-----------


 [`CSSPerspective()`](cssperspective/cssperspective)  Creates a new `CSSPerspective` object.

  
Instance properties
-------------------


 [`length`](cssperspective/length)  Returns or sets the distance from z=0.

  
Examples
--------


To do


Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # cssperspective](https://drafts.css-houdini.org/css-typed-om/#cssperspective) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSPerspective` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `CSSPerspective` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `length` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSPerspective>

CSSPositionValue
================



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.


**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The `CSSPositionValue` interface of the [CSS Typed Object Model API](css_object_model#css_typed_object_model) represents values for properties that take a position, for example [`object-position`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position).



Constructor
-----------


 
[`CSSPositionValue()`](csspositionvalue/csspositionvalue)  Non-standard   Deprecated 
  Creates a new `CSSPositionValue` object.

  
Instance properties
-------------------


 
[`CSSPositionValue.x`](csspositionvalue/x)  Non-standard   Deprecated 
  Returns the item's position along the web page's horizontal axis.

  
[`CSSPositionValue.y`](csspositionvalue/y)  Non-standard   Deprecated 
  Returns the item's position along the vertical axis.

  
Instance methods
----------------


None.


Examples
--------



The following example positions a container `<div>` 5 pixels from the top and 10 pixels from the left of the page.

 
```
const replacedEl = document.getElementById("image");
const position = new CSSPositionValue(CSS.px(35), CSS.px(40));

replacedEl.attributeStyleMap.set("object-position", position);
console.log(position.x.value, position.y.value);
console.log(replacedEl.computedStyleMap().get("object-position"));

```
 We set the [`object-position`](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) property, then check the values returned.




Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSPositionValue` | 66 | 79 | No | No | 53 | No | 66 | 66 | No | 47 | No | 9.0 |
| `CSSPositionValue` | 66 | 79 | No | No | 53 | No | 66 | 66 | No | 47 | No | 9.0 |
| `x` | 66 | 79 | No | No | 53 | No | 66 | 66 | No | 47 | No | 9.0 |
| `y` | 66 | 79 | No | No | 53 | No | 66 | 66 | No | 47 | No | 9.0 |


See also
--------


* [`CSSImageValue`](cssimagevalue)
* [`CSSKeywordValue`](csskeywordvalue)
* [`CSSNumericValue`](cssnumericvalue)
* [`CSSTransformValue`](csstransformvalue)
* [`CSSUnparsedValue`](cssunparsedvalue)
* [Using the CSS Typed OM](css_typed_om_api/guide)
* [CSS Typed Object Model API](css_typed_om_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSPositionValue>

CSSPrimitiveValue
=================



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The `CSSPrimitiveValue` interface derives from the [`CSSValue`](cssvalue) interface and represents the current computed value of a CSS property.

   **Note:** This interface was part of an attempt to create a typed CSS Object Model. This attempt has been abandoned, and most browsers do not implement it. 

 To achieve your purpose, you can use:

 * the untyped [CSS Object Model](css_object_model), widely supported, or
* the modern [CSS Typed Object Model API](css_typed_om_api), less supported and considered experimental.

  This interface represents a single CSS value. It may be used to determine the value of a specific style property currently set in a block or to set a specific style property explicitly within the block. An instance of this interface might be obtained from the [`getPropertyCSSValue()`](cssstyledeclaration/getpropertycssvalue) method of the [`CSSStyleDeclaration`](cssstyledeclaration) interface. A `CSSPrimitiveValue` object only occurs in a context of a CSS property.

 Conversions are allowed between absolute values (from millimeters to centimeters, from degrees to radians, and so on) but not between relative values. (For example, a pixel value cannot be converted to a centimeter value.) Percentage values can't be converted since they are relative to the parent value (or another property value). There is one exception for color percentage values: since a color percentage value is relative to the range 0-255, a color percentage value can be converted to a number (see also the `RGBColor` interface).



Instance properties
-------------------



*Inherits properties from its parent, [`CSSValue`](cssvalue)*.

  
[`CSSPrimitiveValue.primitiveType`](cssprimitivevalue/primitivetype) Read only   Deprecated 
  An `unsigned short` representing the type of the value. Possible values are:

 

| Constant | Description |
| --- | --- |
| `CSS_ATTR` | The value is an [`attr()`](https://developer.mozilla.org/en-US/docs/Web/CSS/attr) function. The value can be obtained by using the `getStringValue()` method. |
| `CSS_CM` | The value is a [`<length>`](https://developer.mozilla.org/en-US/docs/Web/CSS/length) in centimeters. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_COUNTER` | The value is a [counter or counters](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Counter_Styles/Using_CSS_counters) function. The value can be obtained by using the `getCounterValue()` method. |
| `CSS_DEG` | The value is an [`<angle>`](https://developer.mozilla.org/en-US/docs/Web/CSS/angle) in degrees. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_DIMENSION` | The value is a [`<number>`](https://developer.mozilla.org/en-US/docs/Web/CSS/number) with an unknown dimension. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_EMS` | The value is a [`<length>`](https://developer.mozilla.org/en-US/docs/Web/CSS/length) in em units. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_EXS` | The value is a [`<length>`](https://developer.mozilla.org/en-US/docs/Web/CSS/length) in ex units. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_GRAD` | The value is an [`<angle>`](https://developer.mozilla.org/en-US/docs/Web/CSS/angle) in grads. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_HZ` | The value is a [`<frequency>`](https://developer.mozilla.org/en-US/docs/Web/CSS/frequency) in Hertz. The value can be obtained by using the getFloatValue method. |
| `CSS_IDENT` | The value is an identifier. The value can be obtained by using the `getStringValue()` method. |
| `CSS_IN` | The value is a [`<length>`](https://developer.mozilla.org/en-US/docs/Web/CSS/length) in inches. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_KHZ` | The value is a [`<frequency>`](https://developer.mozilla.org/en-US/docs/Web/CSS/frequency) in Kilohertz. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_MM` | The value is a [`<length>`](https://developer.mozilla.org/en-US/docs/Web/CSS/length) in millimeters. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_MS` | The value is a [`<time>`](https://developer.mozilla.org/en-US/docs/Web/CSS/time) in milliseconds. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_NUMBER` | The value is a simple [`<number>`](https://developer.mozilla.org/en-US/docs/Web/CSS/number). The value can be obtained by using the `getFloatValue()` method. |
| `CSS_PC` | The value is a [`<length>`](https://developer.mozilla.org/en-US/docs/Web/CSS/length) in picas. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_PERCENTAGE` | The value is a [`<percentage>`](https://developer.mozilla.org/en-US/docs/Web/CSS/percentage). The value can be obtained by using the `getFloatValue()` method. |
| `CSS_PT` | The value is a [`<length>`](https://developer.mozilla.org/en-US/docs/Web/CSS/length) in points. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_PX` | The value is a [`<length>`](https://developer.mozilla.org/en-US/docs/Web/CSS/length) in pixels. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_RAD` | The value is an [`<angle>`](https://developer.mozilla.org/en-US/docs/Web/CSS/angle) in radians. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_RECT` | The value is a [`rect()`](https://developer.mozilla.org/en-US/docs/Web/CSS/shape#syntax) function. The value can be obtained by using the `getRectValue()` method. |
| `CSS_RGBCOLOR` | The value is an [`<color>`](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). The value can be obtained by using the `getRGBColorValue()` method. |
| `CSS_S` | The value is a [`<time>`](https://developer.mozilla.org/en-US/docs/Web/CSS/time) in seconds. The value can be obtained by using the `getFloatValue()` method. |
| `CSS_STRING` | The value is a [`<string>`](https://developer.mozilla.org/en-US/docs/Web/CSS/string). The value can be obtained by using the `getStringValue()` method. |
| `CSS_UNKNOWN` | The value is not a recognized CSS2 value. The value can only be obtained by using the [`cssText`](cssvalue/csstext) attribute. |
| `CSS_URI` | The value is a [`url()`](https://developer.mozilla.org/en-US/docs/Web/CSS/url). The value can be obtained by using the `getStringValue()` method. |

  

Instance methods
----------------


 
[`CSSPrimitiveValue.getCounterValue()`](cssprimitivevalue/getcountervalue)  Deprecated 
  This method is used to get the [counter](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Counter_Styles/Using_CSS_counters) value. If this CSS value doesn't contain a counter value, a [`DOMException`](domexception) is raised. Modification to the corresponding style property can be achieved using the `Counter` interface.

  
[`CSSPrimitiveValue.getFloatValue()`](cssprimitivevalue/getfloatvalue)  Deprecated 
  This method is used to get a float value in a specified unit. If this CSS value doesn't contain a float value or can't be converted into the specified unit, a [`DOMException`](domexception) is raised.

  
[`CSSPrimitiveValue.getRGBColorValue()`](cssprimitivevalue/getrgbcolorvalue)  Deprecated 
  This method is used to get the RGB color. If this CSS value doesn't contain a RGB color value, a [`DOMException`](domexception) is raised. Modification to the corresponding style property can be achieved using the `RGBColor` interface.

  
[`CSSPrimitiveValue.getRectValue()`](cssprimitivevalue/getrectvalue)  Deprecated 
  This method is used to get the Rect value. If this CSS value doesn't contain a rect value, a [`DOMException`](domexception) is raised. Modification to the corresponding style property can be achieved using the `Rect` interface.

  
[`CSSPrimitiveValue.getStringValue()`](cssprimitivevalue/getstringvalue)  Deprecated 
  This method is used to get the string value. If the CSS value doesn't contain a string value, a [`DOMException`](domexception) is raised.

  
[`CSSPrimitiveValue.setFloatValue()`](cssprimitivevalue/setfloatvalue)  Deprecated 
  A method to set the float value with a specified unit. If the property attached with this value can not accept the specified unit or the float value, the value will be unchanged and a [`DOMException`](domexception) will be raised.

  
[`CSSPrimitiveValue.setStringValue()`](cssprimitivevalue/setstringvalue)  Deprecated 
  A method to set the string value with the specified unit. If the property attached to this value can't accept the specified unit or the string value, the value will be unchanged and a [`DOMException`](domexception) will be raised.

  
Specifications
--------------



 This feature was originally defined in the [DOM Style Level 2](https://www.w3.org/TR/DOM-Level-2-Style/) specification, but has been dropped from any standardization effort since then. 

 It has been superseded by a modern, but incompatible, [CSS Typed Object Model API](css_typed_om_api) that is now on the standard track.



Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSPrimitiveValue` | 1–40 | No | 1–62 | No | ≤12.1–27 | 3 | 4.4–40 | 18–40 | 4–62 | ≤12.1–27 | 1 | 1.0–4.0 |
| `getCounterValue` | 1–40 | No | 20–62 | No | 15–27 | 3 | 4.4–40 | 18–40 | 20–62 | 14–27 | 1 | 1.0–4.0 |
| `getFloatValue` | 1–40 | No | 20–62 | No | ≤12.1–27 | 3 | 4.4–40 | 18–40 | 20–62 | ≤12.1–27 | 1 | 1.0–4.0 |
| `getRGBColorValue` | 1–40 | No | 20–62 | No | 15–27 | 3 | 4.4–40 | 18–40 | 20–62 | 14–27 | 1 | 1.0–4.0 |
| `getRectValue` | 1–40 | No | 20–62 | No | 15–27 | 3 | 4.4–40 | 18–40 | 20–62 | 14–27 | 1 | 1.0–4.0 |
| `getStringValue` | 1–40 | No | 20–62 | No | 15–27 | 3 | 4.4–40 | 18–40 | 20–62 | 14–27 | 1 | 1.0–4.0 |
| `primitiveType` | No | No | 20–62 | No | No | 7 | No | No | 20–62 | No | 7 | No |
| `setFloatValue` | 1–40 | No | 20–62 | No | 15–27 | 3 | 4.4–40 | 18–40 | 20–62 | 14–27 | 1 | 1.0–4.0 |
| `setStringValue` | 1–40 | No | 20–62 | No | 15–27 | 3 | 4.4–40 | 18–40 | 20–62 | 14–27 | 1 | 1.0–4.0 |


See also
--------


* [`CSSValue`](cssvalue)
* [`CSSValueList`](cssvaluelist)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSPrimitiveValue>

CSSPropertyRule
===============



The `CSSPropertyRule` interface of the [CSS\_Properties\_and\_Values\_API](css_properties_and_values_api) represents a single CSS [`@property`](https://developer.mozilla.org/en-US/docs/Web/CSS/@property) rule.


 CSSRule CSSPropertyRule

Instance properties
-------------------



*Inherits properties from its ancestor [`CSSRule`](cssrule).*

  
[`CSSPropertyRule.inherits`](csspropertyrule/inherits) Read only 
  Returns the inherit flag of the custom property.

  
[`CSSPropertyRule.initialvalue`](csspropertyrule/initialvalue) Read only 
  Returns the initial value of the custom property.

  
[`CSSPropertyRule.name`](csspropertyrule/name) Read only 
  Returns the name of the custom property.

  
[`CSSPropertyRule.syntax`](csspropertyrule/syntax) Read only 
  Returns the literal syntax of the custom property.

  

Instance methods
----------------


*No specific methods; inherits methods from its ancestor [`CSSRule`](cssrule).*


Examples
--------



This stylesheet contains a single [`@property`](https://developer.mozilla.org/en-US/docs/Web/CSS/@property) rule. The first [`CSSRule`](cssrule) returned will be a `CSSPropertyRule` with the properties and values as defined by the rule in CSS.

 
```
@property --property-name {
  syntax: "<color>";
  inherits: false;
  initial-value: #c0ffee;
}

```
 
```
let myRules = document.styleSheets[0].cssRules;
console.log(myRules[0]); //a CSSPropertyRule

```


Specifications
--------------




| Specification |
| --- |
| [CSS Properties and Values API Level 1 # the-css-property-rule-interface](https://drafts.css-houdini.org/css-properties-values-api/#the-css-property-rule-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSPropertyRule` | 85 | 85 | No | No | 71 | 16.4 | 85 | 85 | No | 60 | 16.4 | 14.0 |
| `inherits` | 85 | 85 | No | No | 71 | 16.4 | 85 | 85 | No | 60 | 16.4 | 14.0 |
| `initialValue` | 85 | 85 | No | No | 71 | 16.4 | 85 | 85 | No | 60 | 16.4 | 14.0 |
| `name` | 85 | 85 | No | No | 71 | 16.4 | 85 | 85 | No | 60 | 16.4 | 14.0 |
| `syntax` | 85 | 85 | No | No | 71 | 16.4 | 85 | 85 | No | 60 | 16.4 | 14.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSPropertyRule>

CSSRuleList
===========



A `CSSRuleList` represents an ordered collection of read-only [`CSSRule`](cssrule) objects.

 While the `CSSRuleList` object is read-only, and cannot be directly modified, it is considered a `live` object, as the content can change over time.

 To edit the underlying rules returned by `CSSRule` objects, use [`CSSStyleSheet.insertRule()`](cssstylesheet/insertrule) and [`CSSStyleSheet.deleteRule()`](cssstylesheet/deleterule), which are methods of [`CSSStyleSheet`](cssstylesheet).

 The interface has no constructor. An instance of `CSSRuleList` is returned by [`CSSStyleSheet.cssRules`](cssstylesheet/cssrules) and [`CSSKeyframesRule.cssRules`](csskeyframesrule/cssrules).

  **Note:** This interface was an [attempt to create an unmodifiable list](https://stackoverflow.com/questions/74630989/why-use-domstringlist-rather-than-an-array/74641156#74641156) and only continues to be supported to not break code that's already using it. Modern APIs use types that wrap around ECMAScript array types instead, so you can treat them like ECMAScript arrays, and at the same time impose additional semantics on their usage (such as making their items read-only).

 

Instance properties
-------------------


 
[`CSSRuleList.length`](cssrulelist/length) Read only 
  Returns an integer representing the number of [`CSSRule`](cssrule) objects in the collection.

  
Instance methods
----------------


 [`CSSRuleList.item()`](cssrulelist/item)  Gets a single [`CSSRule`](cssrule).

  
Examples
--------



In the following example there is a stylesheet with three rules. Using [`CSSStyleSheet.cssRules`](cssstylesheet/cssrules) returns a `CSSRuleList`, which is printed to the console.

 The number of rules in the list is printed to the console using [`CSSRuleList.length`](cssrulelist/length). The first [`CSSRule`](cssrule) can be returned by using `0` as the parameter for [`CSSRuleList.item`](cssrulelist/item), in the example this will return the rules set for the `body` selector.



### CSS



```
body {
  font-family: system-ui, -apple-system, sans-serif;
  margin: 2em;
}

.container {
  display: grid;
  grid-template-columns: repeat(auto-fill, 200px);
}

.container > \* {
  background-color: #3740ff;
  color: #fff;
}

```

### JavaScript



```
let myRules = document.styleSheets[0].cssRules;
console.log(myRules);
console.log(myRules.length);
console.log(myRules[0]);

```

Specifications
--------------




| Specification |
| --- |
| [CSS Object Model (CSSOM) # the-cssrulelist-interface](https://w3c.github.io/csswg-drafts/cssom/#the-cssrulelist-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSRuleList` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `item` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `length` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* [`CSSRule`](cssrule)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSRuleList>

CSSScale
========



The `CSSScale` interface of the [CSS\_Object\_Model#css\_typed\_object\_model](css_object_model#css_typed_object_model) represents the [scale()](https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/scale) and [scale3d()](https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/scale3d) values of the individual [`transform`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform) property in CSS. It inherits properties and methods from its parent [`CSSTransformValue`](csstransformvalue).


 CSSTransformComponent CSSScale

Constructor
-----------


 [`CSSScale()`](cssscale/cssscale)  Creates a new `CSSScale` object.

  
Instance properties
-------------------


 [`x`](cssscale/x)  Returns or sets the x-axis value.

  [`y`](cssscale/y)  Returns or sets the y-axis value.

  [`z`](cssscale/z)  Returns or sets the z-axis value.

  
Examples
--------


To do.


Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # cssscale](https://drafts.css-houdini.org/css-typed-om/#cssscale) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSScale` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `CSSScale` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `x` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `y` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `z` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSScale>

CSSSkew
=======



The `CSSSkew` interface of the [CSS\_Object\_Model#css\_typed\_object\_model](css_object_model#css_typed_object_model) is part of the [`CSSTransformValue`](csstransformvalue) interface. It represents the [`skew()`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/skew) value of the individual [`transform`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform) property in CSS.


 CSSTransformComponent CSSSkew

Constructor
-----------


 [`CSSSkew()`](cssskew/cssskew)  Creates a new `CSSSkew` object.

  
Instance properties
-------------------


 [`ax`](cssskew/ax)  Returns or sets the x-axis value.

  [`ay`](cssskew/ay)  Returns or sets the y-axis value.

  
Examples
--------


To Do


Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # cssskew](https://drafts.css-houdini.org/css-typed-om/#cssskew) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSSkew` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `CSSSkew` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `ax` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `ay` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSSkew>

CSSNumericArray
===============


The `CSSNumericArray` interface of the [CSS\_Object\_Model#css\_typed\_object\_model](css_object_model#css_typed_object_model) contains a list of [`CSSNumericValue`](cssnumericvalue) objects.


Instance properties
-------------------


 
[`CSSNumericArray.length`](cssnumericarray/length) Read only 
  Returns how many [`CSSNumericValue`](cssnumericvalue) objects are contained within the `CSSNumericArray`.

  
Examples
--------


To do.


Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # cssnumericarray](https://drafts.css-houdini.org/css-typed-om/#cssnumericarray) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@iterator` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `CSSNumericArray` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `entries` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `forEach` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `keys` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `length` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `values` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSNumericArray>

CSSNumericValue
===============



The `CSSNumericValue` interface of the [CSS Typed Object Model API](css_object_model#css_typed_object_model) represents operations that all numeric values can perform.


 CSSStyleValue CSSNumericValue

Interfaces based on CSSNumericValue
-----------------------------------



Below is a list of interfaces based on the CSSNumericValue interface.

 * `CSSMathClamp`
* [`CSSMathInvert`](cssmathinvert)
* [`CSSMathMax`](cssmathmax)
* [`CSSMathMin`](cssmathmin)
* [`CSSMathNegate`](cssmathnegate)
* [`CSSMathProduct`](cssmathproduct)
* [`CSSMathSum`](cssmathsum)
* [`CSSMathValue`](cssmathvalue)
* [`CSSNumericArray`](cssnumericarray)
* [`CSSUnitValue`](cssunitvalue)



Instance properties
-------------------


None.


Static methods
--------------


 [`CSSNumericValue.parse`](cssnumericvalue/parse)  Allows a `CSSNumericValue` to be constructed directly from a string containing CSS.

  
Instance methods
----------------


 [`CSSNumericValue.add`](cssnumericvalue/add)  Adds a supplied number to the `CSSNumericValue`.

  [`CSSNumericValue.sub`](cssnumericvalue/sub)  Subtracts a supplied number from the `CSSNumericValue`.

  [`CSSNumericValue.mul`](cssnumericvalue/mul)  Multiplies the `CSSNumericValue` by the supplied value.

  [`CSSNumericValue.div`](cssnumericvalue/div)  Divides the `CSSNumericValue` by the supplied value.

  [`CSSNumericValue.min`](cssnumericvalue/min)  Returns the minimum value passed

  [`CSSNumericValue.max`](cssnumericvalue/max)  Returns the maximum value passed

  [`CSSNumericValue.equals`](cssnumericvalue/equals)  *True* if all the values are the exact same type and value, in the same order. Otherwise, *false.*

  [`CSSNumericValue.to`](cssnumericvalue/to)  Converts `value` into another one with the specified *unit.*

  [`CSSNumericValue.toSum`](cssnumericvalue/tosum)  Converts an existing `CSSNumericValue` into a [`CSSMathSum`](cssmathsum) object with values of a specified unit.

  [`CSSNumericValue.type`](cssnumericvalue/type)  Returns the type of `CSSNumericValue`, one of `angle`, `flex`, `frequency`, `length`, `resolution`, `percent`, `percentHint`, or `time`.

  
Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # numeric-value](https://drafts.css-houdini.org/css-typed-om/#numeric-value) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSNumericValue` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `add` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `div` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `equals` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `max` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `min` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `mul` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `parse` | 66Not exposed to PaintWorklet. | 79Not exposed to PaintWorklet. | No | No | 53Not exposed to PaintWorklet. | 16.4 | 66Not exposed to PaintWorklet. | 66Not exposed to PaintWorklet. | No | 47Not exposed to PaintWorklet. | 16.4 | 9.0Not exposed to PaintWorklet. |
| `sub` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `to` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `toSum` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `type` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |


See also
--------


* [`CSSImageValue`](cssimagevalue)
* [`CSSKeywordValue`](csskeywordvalue)
* [`CSSPositionValue`](csspositionvalue)
* [`CSSTransformValue`](csstransformvalue)
* [`CSSUnparsedValue`](cssunparsedvalue)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSNumericValue>

CSSPageRule
===========



`CSSPageRule` represents a single CSS [`@page`](https://developer.mozilla.org/en-US/docs/Web/CSS/@page) rule.


 CSSRule CSSGroupingRule CSSPageRule

Instance properties
-------------------



*Inherits properties from its ancestor [`CSSRule`](cssrule).*

  [`CSSPageRule.selectorText`](csspagerule/selectortext)  Represents the text of the page selector associated with the at-rule.

  
[`CSSPageRule.style`](csspagerule/style) Read only 
  Returns the [declaration block](css_object_model/css_declaration_block) associated with the at-rule.

  

Instance methods
----------------


*Inherits methods from its ancestor [`CSSRule`](cssrule).*


Examples
--------



The stylesheet includes a single [`@page`](https://developer.mozilla.org/en-US/docs/Web/CSS/@page) rule, therefore the first (and only) rule returned will be a `CSSPageRule`.

 
```
@page {
  margin: 1cm;
}

```
 
```
let myRules = document.styleSheets[0].cssRules;
console.log(myRules[0]); // a CSSPageRule

```


Specifications
--------------




| Specification |
| --- |
| [CSS Object Model (CSSOM) # the-csspagerule-interface](https://w3c.github.io/csswg-drafts/cssom/#the-csspagerule-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSPageRule` | 1 | 12 | 19 | 9 | ≤12.1 | 3 | 4.4 | 18 | 19 | ≤12.1 | 1 | 1.0 |
| `selectorText` | 1 | 12 | 110 | 9 | ≤12.1 | 3 | 4.4 | 18 | 110 | ≤12.1 | 1 | 1.0 |
| `style` | 1 | 12 | 19 | 9 | ≤12.1 | 3 | 4.4 | 18 | 19 | ≤12.1 | 1 | 1.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSPageRule>

CSSPseudoElement
================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `CSSPseudoElement` interface represents a pseudo-element that may be the target of an event or animated using the [Web Animations API](web_animations_api). Instances of this interface may be obtained by calling `Element.pseudo()`.


 EventTarget CSSPseudoElement

Instance properties
-------------------


 
[`CSSPseudoElement.element`](csspseudoelement/element)  Experimental  Read only 
  Returns the originating/parent [`Element`](element) of the pseudo-element.

  
[`CSSPseudoElement.type`](csspseudoelement/type)  Experimental  Read only 
  Returns the pseudo-element selector as a string.

  
Instance methods
----------------



*`CSSPseudoElement` extends [`EventTarget`](eventtarget), so it inherits the following methods:*

  [`EventTarget.addEventListener()`](eventtarget/addeventlistener)  Registers an event handler of a specific event type on the pseudo-element.

  [`EventTarget.dispatchEvent()`](eventtarget/dispatchevent)  Dispatches an event to this pseudo-element.

  [`EventTarget.removeEventListener()`](eventtarget/removeeventlistener)  Removes an event listener from the pseudo-element.

  

Examples
--------


### Basic example using Element.pseudo



Using pseudo-elements, most modern browsers will automatically add quotation marks around text inside a [`<q>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q) element. (A style rule may be needed to add quotation marks in older browsers.) The example below demonstrates the basic properties of the `CSSPseudoElement` object representing the opening quotation mark.

 
```
const element = document.querySelector("q");
const cssPseudoElement = element.pseudo("::before");
console.log(cssPseudoElement.element); // Outputs [object HTMLQuoteElement]
console.log(cssPseudoElement.type); // Outputs '::before'

```


Specifications
--------------




| Specification |
| --- |
| [CSS Pseudo-Elements Module Level 4 # CSSPseudoElement-interface](https://w3c.github.io/csswg-drafts/css-pseudo/#CSSPseudoElement-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSPseudoElement` | No | No | 75 | No | No | No | No | No | No | No | No | No |
| `element` | No | No | 75 | No | No | No | No | No | No | No | No | No |
| `type` | No | No | 75 | No | No | No | No | No | No | No | No | No |


See also
--------


* `Element.pseudo()`
* [Web Animations API](web_animations_api)
* [`Element.animate()`](element/animate)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSPseudoElement>

CSSRotate
=========



The `CSSRotate` interface of the [CSS\_Object\_Model#css\_typed\_object\_model](css_object_model#css_typed_object_model) represents the rotate value of the individual [`transform`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform) property in CSS. It inherits properties and methods from its parent [`CSSTransformValue`](csstransformvalue).


 CSSTransformComponent CSSRotate

Constructor
-----------


 [`CSSRotate()`](cssrotate/cssrotate)  Creates a new `CSSRotate` object.

  
Instance properties
-------------------


 [`x`](cssrotate/x)  Returns or sets the x-axis value.

  [`y`](cssrotate/y)  Returns or sets the y-axis value.

  [`z`](cssrotate/z)  Returns or sets the z-axis value.

  [`angle`](cssrotate/angle)  Returns or sets the angle value.

  
Examples
--------


To do.


Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # cssrotate](https://drafts.css-houdini.org/css-typed-om/#cssrotate) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSRotate` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `CSSRotate` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `angle` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `x` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `y` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `z` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSRotate>

CSSRule
=======



The `CSSRule` interface represents a single CSS rule. There are several types of rules which inherit properties from `CSSRule`.

 * [`CSSGroupingRule`](cssgroupingrule)
* [`CSSStyleRule`](cssstylerule)
* [`CSSImportRule`](cssimportrule)
* [`CSSMediaRule`](cssmediarule)
* [`CSSFontFaceRule`](cssfontfacerule)
* [`CSSPageRule`](csspagerule)
* [`CSSNamespaceRule`](cssnamespacerule)
* [`CSSKeyframesRule`](csskeyframesrule)
* [`CSSKeyframeRule`](csskeyframerule)
* [`CSSCounterStyleRule`](csscounterstylerule)
* [`CSSSupportsRule`](csssupportsrule)
* [`CSSFontFeatureValuesRule`](cssfontfeaturevaluesrule)
* [`CSSFontPaletteValuesRule`](cssfontpalettevaluesrule)
* [`CSSLayerBlockRule`](csslayerblockrule)
* [`CSSLayerStatementRule`](csslayerstatementrule)
* [`CSSPropertyRule`](csspropertyrule)



Instance properties
-------------------



The `CSSRule` interface specifies the properties common to all rules, while properties unique to specific rule types are specified in the more specialized interfaces for those rules' respective types.

  [`CSSRule.cssText`](cssrule/csstext)  Represents the textual representation of the rule, e.g. "`h1,h2 { font-size: 16pt }`" or "`@import 'url'`". To access or modify parts of the rule (e.g. the value of "font-size" in the example) use the properties on the [specialized interface for the rule's type](#type_constants).

  
[`CSSRule.parentRule`](cssrule/parentrule) Read only 
  Returns the containing rule, otherwise `null`. E.g. if this rule is a style rule inside an [`@media`](https://developer.mozilla.org/en-US/docs/Web/CSS/@media) block, the parent rule would be that [`CSSMediaRule`](cssmediarule).

  
[`CSSRule.parentStyleSheet`](cssrule/parentstylesheet) Read only 
  Returns the [`CSSStyleSheet`](cssstylesheet) object for the style sheet that contains this rule

  
[`CSSRule.type`](cssrule/type) Read only   Deprecated 
  Returns one of the Type constants to determine which type of rule is represented.

  

Examples
--------



References to a `CSSRule` may be obtained by looking at a [`CSSStyleSheet`](cssstylesheet)'s `cssRules` list.

 
```
let myRules = document.styleSheets[0].cssRules; // Returns a CSSRuleList
console.log(myRules);

```


Specifications
--------------




| Specification |
| --- |
| [CSS Object Model (CSSOM) # the-cssrule-interface](https://w3c.github.io/csswg-drafts/cssom/#the-cssrule-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSRule` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `cssText` | 1 | 12 | 1 | 9The property normalizes rules and does not return the original verbatim rule text. For example, `border-width: 1px; border-style:solid; border-color:white;` returns `border: 1px solid white;`. | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `parentRule` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `parentStyleSheet` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `type` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* [Using dynamic styling information](css_object_model/using_dynamic_styling_information)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSRule>

CSSStyleRule
============



The `CSSStyleRule` interface represents a single CSS style rule.


 CSSRule CSSStyleRule

Instance properties
-------------------



*Inherits properties from its ancestor [`CSSRule`](cssrule).*

  [`CSSStyleRule.selectorText`](cssstylerule/selectortext)  Returns the textual representation of the selector for this rule, e.g. `"h1,h2"`.

  
[`CSSStyleRule.style`](cssstylerule/style) Read only 
  Returns the [`CSSStyleDeclaration`](cssstyledeclaration) object for the rule.

  
[`CSSStyleRule.styleMap`](cssstylerule/stylemap) Read only 
  Returns a [`StylePropertyMap`](stylepropertymap) object which provides access to the rule's property-value pairs.

  

Instance methods
----------------


*No specific methods; inherits methods from its ancestor [`CSSRule`](cssrule).*


Examples
--------



 The CSS includes one style rule. This will be the first [`CSSRule`](cssrule) returned by `document.styleSheets[0].cssRules`. `myRules[0]` therefore returns a [`CSSStyleRule`](cssstylerule) object representing the rule defined for `h1`. 

 
```
h1 {
  color: pink;
}

```
 
```
let myRules = document.styleSheets[0].cssRules;
console.log(myRules[0]); // a CSSStyleRule representing the h1.

```


Specifications
--------------




| Specification |
| --- |
| [CSS Object Model (CSSOM) # the-cssstylerule-interface](https://w3c.github.io/csswg-drafts/cssom/#the-cssstylerule-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSStyleRule` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `selectorText` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `style` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `styleMap` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleRule>

CSSSkewX
========



The `CSSSkewX` interface of the [CSS\_Object\_Model#css\_typed\_object\_model](css_object_model#css_typed_object_model) represents the [`skewX()`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/skewX) value of the individual [`transform`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform) property in CSS. It inherits properties and methods from its parent [`CSSTransformValue`](csstransformvalue).


 CSSTransformComponent CSSSkewX

Constructor
-----------


 [`CSSSkewX()`](cssskewx/cssskewx)  Creates a new `CSSSkewX` object.

  
Instance properties
-------------------


 [`ax`](cssskewx/ax)  Returns or sets the x-axis value.

  
Examples
--------


To Do


Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # cssskewx](https://drafts.css-houdini.org/css-typed-om/#cssskewx) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSSkewX` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `CSSSkewX` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `ax` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSSkewX>

CSSSkewY
========



The `CSSSkewY` interface of the [CSS\_Object\_Model#css\_typed\_object\_model](css_object_model#css_typed_object_model) represents the [`skewY()`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/skewY) value of the individual [`transform`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform) property in CSS. It inherits properties and methods from its parent [`CSSTransformValue`](csstransformvalue).


 CSSTransformComponent CSSSkewY

Constructor
-----------


 [`CSSSkewY()`](cssskewy/cssskewy)  Creates a new `CSSSkewY` object.

  
Instance properties
-------------------



*Inherits properties from its ancestor* [`CSSTransformValue`](csstransformvalue).

  [`ay`](cssskewy/ay)  Returns or sets the y-axis value.

  

Instance methods
----------------


*Inherits methods from its ancestor* [`CSSTransformValue`](csstransformvalue).


Examples
--------


To Do


Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # cssskewy](https://drafts.css-houdini.org/css-typed-om/#cssskewy) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSSkewY` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `CSSSkewY` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `ay` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSSkewY>

CSSStyleDeclaration
===================



The `CSSStyleDeclaration` interface represents an object that is a CSS declaration block, and exposes style information and various style-related methods and properties.

 A `CSSStyleDeclaration` object can be exposed using three different APIs:

 * Via [`HTMLElement.style`](htmlelement/style), which deals with the inline styles of a single element (e.g., `<div style="…">`).
* Via the [`CSSStyleSheet`](cssstylesheet) API. For example, `document.styleSheets[0].cssRules[0].style` returns a `CSSStyleDeclaration` object on the first CSS rule in the document's first stylesheet.
* Via [`Window.getComputedStyle()`](window/getcomputedstyle), which exposes the `CSSStyleDeclaration` object as a **read-only** interface.



Attributes
----------


 [`CSSStyleDeclaration.cssText`](cssstyledeclaration/csstext)  Textual representation of the declaration block, if and only if it is exposed via [`HTMLElement.style`](htmlelement/style). Setting this attribute changes the inline style. If you want a text representation of a computed declaration block, you can get it with `JSON.stringify()`.

  
[`CSSStyleDeclaration.length`](cssstyledeclaration/length) Read only 
  The number of properties. See the [`item()`](cssstyledeclaration/item) method below.

  
[`CSSStyleDeclaration.parentRule`](cssstyledeclaration/parentrule) Read only 
  The containing [`CSSRule`](cssrule).

  
### CSS Properties


 [`CSSStyleDeclaration.cssFloat`](cssstyledeclaration/cssfloat)  Special alias for the [`float`](https://developer.mozilla.org/en-US/docs/Web/CSS/float) CSS property.

  `CSSStyleDeclaration` named properties  Dashed and camel-cased attributes for all supported CSS properties.

  
Instance methods
----------------


 [`CSSStyleDeclaration.getPropertyPriority()`](cssstyledeclaration/getpropertypriority)  Returns the optional priority, "important".

  [`CSSStyleDeclaration.getPropertyValue()`](cssstyledeclaration/getpropertyvalue)  Returns the property value given a property name.

  [`CSSStyleDeclaration.item()`](cssstyledeclaration/item)  Returns a CSS property name by its index, or the empty string if the index is out-of-bounds.

  [`CSSStyleDeclaration.removeProperty()`](cssstyledeclaration/removeproperty)  Removes a property from the CSS declaration block.

  [`CSSStyleDeclaration.setProperty()`](cssstyledeclaration/setproperty)  Modifies an existing CSS property or creates a new CSS property in the declaration block.

  
[`CSSStyleDeclaration.getPropertyCSSValue()`](cssstyledeclaration/getpropertycssvalue)  Deprecated 
  **Only supported via getComputedStyle in Firefox.** Returns the property value as a [`CSSPrimitiveValue`](cssprimitivevalue) or `null` for [shorthand properties](https://developer.mozilla.org/en-US/docs/Web/CSS/Shorthand_properties).

  
Example
-------



```
const styleObj = document.styleSheets[0].cssRules[0].style;
console.log(styleObj.cssText);

for (let i = styleObj.length; i--; ) {
  const nameString = styleObj[i];
  styleObj.removeProperty(nameString);
}

console.log(styleObj.cssText);

```

Specifications
--------------




| Specification |
| --- |
| [CSS Object Model (CSSOM) # the-cssstyledeclaration-interface](https://w3c.github.io/csswg-drafts/cssom/#the-cssstyledeclaration-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@iterator` | 51 | 18 | 36 | No | 38 | 11 | 51 | 51 | 36 | 41 | 11 | 5.0 |
| `CSSStyleDeclaration` | 1 | 12 | 1 | 5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `cssFloat` | 1 | 12 | 1–17 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4–17 | ≤12.1 | 1 | 1.0 |
| `cssText` | 1 | 12 | 1 | 5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `getPropertyCSSValue` | 1–40See [bug 331608](https://crbug.com/331608). | NoSee [bug 331608](https://crbug.com/331608). | 1–61Only returns a result if called on the result of `getComputedStyle()`. | No | 15–27See [bug 331608](https://crbug.com/331608). | 1 | 4.4–41See [bug 331608](https://crbug.com/331608). | 18–40See [bug 331608](https://crbug.com/331608). | 4–61 | 14–27See [bug 331608](https://crbug.com/331608). | 1 | 1.0–4.0See [bug 331608](https://crbug.com/331608). |
| `getPropertyPriority` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `getPropertyValue` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `item` | 1 | 12 | 1 | 9 | ≤12.1 | 6 | 4.4 | 18 | 4 | ≤12.1 | 6 | 1.0 |
| `length` | 1 | 12 | 1 | 9 | ≤12.1 | 6 | 4.4 | 18 | 4 | ≤12.1 | 6 | 1.0 |
| `parentRule` | 1 | 12 | 1 | 9 | 15 | 1 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `removeProperty` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `setProperty` | 1 | 12 | 1 | 9 | 9 | 6 | 4.4 | 18 | 4 | 10.1 | 6 | 1.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration>

CSSStyleSheet
=============



The `CSSStyleSheet` interface represents a single [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS) stylesheet, and lets you inspect and modify the list of rules contained in the stylesheet. It inherits properties and methods from its parent, [`StyleSheet`](stylesheet).


 StyleSheet CSSStyleSheet A stylesheet consists of a collection of [`CSSRule`](cssrule) objects representing each of the rules in the stylesheet. The rules are contained in a [`CSSRuleList`](cssrulelist), which can be obtained from the stylesheet's [`cssRules`](cssstylesheet/cssrules) property.

 For example, one rule might be a [`CSSStyleRule`](cssstylerule) object containing a style such as:

 
```
h1,
h2 {
  font-size: 16pt;
}

```
 Another rule might be an *at-rule* such as [`@import`](https://developer.mozilla.org/en-US/docs/Web/CSS/@import) or [`@media`](https://developer.mozilla.org/en-US/docs/Web/CSS/@media), and so forth.

 See the [Obtaining a StyleSheet](#obtaining_a_stylesheet) section for the various ways a `CSSStyleSheet` object can be obtained. A `CSSStyleSheet` object can also be directly constructed. The constructor, and the [`CSSStyleSheet.replace()`](cssstylesheet/replace), and [`CSSStyleSheet.replaceSync()`](cssstylesheet/replacesync) methods are newer additions to the specification, enabling *Constructable Stylesheets*.



Constructor
-----------


 [`CSSStyleSheet()`](cssstylesheet/cssstylesheet)  Creates a new `CSSStyleSheet` object.

  
Instance properties
-------------------



*Inherits properties from its parent, [`StyleSheet`](stylesheet).*

  
[`CSSStyleSheet.cssRules`](cssstylesheet/cssrules) Read only 
  Returns a live [`CSSRuleList`](cssrulelist) which maintains an up-to-date list of the [`CSSRule`](cssrule) objects that comprise the stylesheet.

  **Note:** In some browsers, if a stylesheet is loaded from a different domain, accessing `cssRules` results in a `SecurityError`.

   
[`CSSStyleSheet.ownerRule`](cssstylesheet/ownerrule) Read only 
  If this stylesheet is imported into the document using an [`@import`](https://developer.mozilla.org/en-US/docs/Web/CSS/@import) rule, the `ownerRule` property returns the corresponding [`CSSImportRule`](cssimportrule); otherwise, this property's value is `null`.

  

Instance methods
----------------



*Inherits methods from its parent, [`StyleSheet`](stylesheet).*

  [`CSSStyleSheet.deleteRule()`](cssstylesheet/deleterule)  Deletes the rule at the specified index into the stylesheet's rule list.

  [`CSSStyleSheet.insertRule()`](cssstylesheet/insertrule)  Inserts a new rule at the specified position in the stylesheet, given the textual representation of the rule.

  [`CSSStyleSheet.replace()`](cssstylesheet/replace)  Asynchronously replaces the content of the stylesheet and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with the updated `CSSStyleSheet`.

  [`CSSStyleSheet.replaceSync()`](cssstylesheet/replacesync)  Synchronously replaces the content of the stylesheet.

  

Legacy properties
-----------------



*These properties are legacy properties as introduced by Microsoft; these are maintained for compatibility with existing sites.*

  
[`rules`](cssstylesheet/rules) Read only   Deprecated 
  The `rules` property is functionally identical to the standard [`cssRules`](cssstylesheet/cssrules) property; it returns a live [`CSSRuleList`](cssrulelist) which maintains an up-to-date list of all of the rules in the style sheet.

  

Legacy methods
--------------



*These methods are legacy methods as introduced by Microsoft; these are maintained for compatibility with existing sites.*

  
[`addRule()`](cssstylesheet/addrule)  Deprecated 
  Adds a new rule to the stylesheet given the selector to which the style applies and the style block to apply to the matching elements.

 This differs from [`insertRule()`](cssstylesheet/insertrule), which takes the textual representation of the entire rule as a single string.

  
[`removeRule()`](cssstylesheet/removerule)  Deprecated 
  Functionally identical to [`deleteRule()`](cssstylesheet/deleterule); removes the rule at the specified index from the stylesheet's rule list.

  

Obtaining a StyleSheet
----------------------



A stylesheet is associated with at most one [`Document`](document), which it applies to (unless [disabled](stylesheet/disabled)). A list of `CSSStyleSheet` objects for a given document can be obtained using the [`Document.styleSheets`](document/stylesheets) property. A specific style sheet can also be accessed from its *owner* object (`Node` or `CSSImportRule`), if any.

 A `CSSStyleSheet` object is created and inserted into the document's [`Document.styleSheets`](document/stylesheets) list automatically by the browser, when a stylesheet is loaded for a document.

 A (possibly incomplete) list of ways a stylesheet can be associated with a document follows:

 

| Reason for the style sheet to be associated with the document | Appears in `document.styleSheets` list | Getting the owner element/rule given the style sheet object | The interface for the owner object | Getting the CSSStyleSheet object from the owner |
| --- | --- | --- | --- | --- |
| [`<style>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style) and [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link) elements in the document  | Yes | [`.ownerNode`](stylesheet/ownernode) | [`HTMLLinkElement`](htmllinkelement),[`HTMLStyleElement`](htmlstyleelement),or [`SVGStyleElement`](svgstyleelement) | [`HTMLLinkElement.sheet`](htmllinkelement/sheet),[`HTMLStyleElement.sheet`](htmlstyleelement/sheet),or [`SVGStyleElement.sheet`](svgstyleelement/sheet) |
|  CSS [`@import`](https://developer.mozilla.org/en-US/docs/Web/CSS/@import) rule in other style sheets applied to the document  | Yes | [`.ownerRule`](cssstylesheet/ownerrule) | [`CSSImportRule`](cssimportrule) | [`.styleSheet`](cssimportrule/stylesheet) |
| `<?xml-stylesheet ?>` processing instruction in the (non-HTML) document  | Yes | [`.ownerNode`](stylesheet/ownernode) | [`ProcessingInstruction`](processinginstruction) | [`.sheet`](processinginstruction/sheet) |
| HTTP Link Header | Yes | *N/A* | N/A | N/A |
| User agent (default) style sheets | No | N/A | N/A | N/A |



Specifications
--------------




| Specification |
| --- |
| [CSS Object Model (CSSOM) # the-cssstylesheet-interface](https://w3c.github.io/csswg-drafts/cssom/#the-cssstylesheet-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSStyleSheet` | 73 | 79 | 101 | No | 53 | 16.4 | 73 | 73 | 101 | 47 | 16.4 | 9.0 |
| `CSSStyleSheet` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `addRule` | 1 | 12 | 68 | 9 | 15 | 1 | 4.4 | 18 | 68 | 14 | 1 | 1.0 |
| `cssRules` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `deleteRule` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `insertRule` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `ownerRule` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `removeRule` | 1 | 12 | 68 | 9 | 15 | 3 | 4.4 | 18 | 68 | 14 | 1 | 1.0 |
| `replace` | 73 | 79 | 101 | No | 60 | 16.4 | 73 | 73 | 101 | 52 | 16.4 | 11.0 |
| `replaceSync` | 73 | 79 | 101 | No | 60 | 16.4 | 73 | 73 | 101 | 52 | 16.4 | 11.0 |
| `rules` | 1 | 12 | 68 | 9 | 15 | 1 | 4.4 | 18 | 68 | 14 | 1 | 1.0 |


See also
--------


* [CSS Object Model](css_object_model)
* [Using dynamic styling information](css_object_model/using_dynamic_styling_information)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet>

CSSStyleValue
=============


The `CSSStyleValue` interface of the [CSS Typed Object Model API](css_object_model#css_typed_object_model) is the base class of all CSS values accessible through the Typed OM API. An instance of this class may be used anywhere a string is expected.


Interfaces based on CSSStyleValue
---------------------------------



Below is a list of interfaces based on the `CSSStyleValue` interface.

 * [`CSSImageValue`](cssimagevalue)
* [`CSSKeywordValue`](csskeywordvalue)
* [`CSSNumericValue`](cssnumericvalue)
* [`CSSPositionValue`](csspositionvalue)
* [`CSSTransformValue`](csstransformvalue)
* [`CSSUnparsedValue`](cssunparsedvalue)



Instance methods
----------------


 [`CSSStyleValue.parse()`](cssstylevalue/parse)  Sets a specific CSS property to the specified values and returns the first value as a [`CSSStyleValue`](cssstylevalue) object.

  [`CSSStyleValue.parseAll()`](cssstylevalue/parseall)  Sets all occurrences of a specific CSS property to the specified value and returns an array of [`CSSStyleValue`](cssstylevalue) objects, each containing one of the supplied values.

  
Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # stylevalue-objects](https://drafts.css-houdini.org/css-typed-om/#stylevalue-objects) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSStyleValue` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `parse` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `parseAll` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `toString` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleValue>

CSSSupportsRule
===============



The `CSSSupportsRule` interface represents a single CSS [`@supports`](https://developer.mozilla.org/en-US/docs/Web/CSS/@supports) [at-rule](https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule).


 CSSRule CSSGroupingRule CSSConditionRule CSSSupportsRule

Instance properties
-------------------


*Inherits properties from its ancestors [`CSSConditionRule`](cssconditionrule), [`CSSGroupingRule`](cssgroupingrule), and [`CSSRule`](cssrule).*


Instance methods
----------------


*Inherits methods from its ancestors [`CSSConditionRule`](cssconditionrule), [`CSSGroupingRule`](cssgroupingrule), and [`CSSRule`](cssrule).*


Examples
--------



 The CSS includes a CSS feature query using the [`@supports`](https://developer.mozilla.org/en-US/docs/Web/CSS/@supports) [at-rule](https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule), containing one style rule. This will be the first CSSRule returned by `document.styleSheets[0].cssRules`. `myRules[0]` therefore returns a [`CSSSupportsRule`](csssupportsrule) object. 

 
```
@supports (display: grid) {
  body {
    color: blue;
  }
}

```
 
```
let myRules = document.styleSheets[0].cssRules;
console.log(myRules[0]); // a CSSSupportsRule representing the feature query.

```


Specifications
--------------




| Specification |
| --- |
| [CSS Conditional Rules Module Level 3 # the-csssupportsrule-interface](https://w3c.github.io/csswg-drafts/css-conditional-3/#the-csssupportsrule-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSSupportsRule` | 28 | 12 | 22 | No | 12.1 | 9 | 4.4 | 28 | 22 | 1512.1–14 | 9 | 1.5 |


See also
--------


* [`@supports`](https://developer.mozilla.org/en-US/docs/Web/CSS/@supports)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSSupportsRule>

CSSTransformComponent
=====================


The `CSSTransformComponent` interface of the [CSS\_Object\_Model#css\_typed\_object\_model](css_object_model#css_typed_object_model) is part of the [`CSSTransformValue`](csstransformvalue) interface.


Instance properties
-------------------


 
[`CSSTransformComponent.is2D`](csstransformcomponent/is2d) Read only 
  Returns a boolean indicting whether the transform is 2D or 3D.

  
Instance methods
----------------


 [`CSSTransformComponent.toMatrix()`](csstransformcomponent/tomatrix)  Returns a new [`DOMMatrix`](dommatrix) object.

  [`CSSTransformComponent.toString()`](csstransformcomponent/tostring)  A string in the form of a CSS [`Transforms function`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function).

 This will use the value of `is2D` to return either a 2D or 3D transform. For example if the component represents [`CSSRotate`](cssrotate) and `is2D` is false then the string returned will be in the form of the CSS transformation [`rotate3D()`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/rotate3d) function. If true the string returned will be in the form of the 2-dimensional [`rotate3D()`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/rotate) function.

  
Examples
--------


To do


Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # csstransformcomponent](https://drafts.css-houdini.org/css-typed-om/#csstransformcomponent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSTransformComponent` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `is2D` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `toMatrix` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `toString` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSTransformComponent>

CSSTransformValue
=================



The `CSSTransformValue` interface of the [CSS\_Object\_Model#css\_typed\_object\_model](css_object_model#css_typed_object_model) represents `transform-list` values as used by the CSS [`transform`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform) property.


 CSSStyleValue CSSTransformValue

Interfaces based on CSSTransformValue
-------------------------------------



Below is a list of interfaces based on the `CSSTransformValue` interface.

 * [`CSSTranslate`](csstranslate)
* [`CSSRotate`](cssrotate)
* [`CSSScale`](cssscale)
* [`CSSSkew`](cssskew)
* [`CSSSkewX`](cssskewx)
* [`CSSSkewY`](cssskewy)
* [`CSSPerspective`](cssperspective)
* [`CSSMatrixComponent`](cssmatrixcomponent)



Constructor
-----------


 [`CSSTransformValue()`](csstransformvalue/csstransformvalue)  Creates a new `CSSTransformValue` object.

  
Instance properties
-------------------


 
[`CSSTransformValue.length`](csstransformvalue/length) Read only 
  Returns how many transform components are contained within the `CSSTransformValue`.

  
[`CSSTransformValue.is2D`](csstransformvalue/is2d) Read only 
  Returns a boolean indicating whether the transform is 2D or 3D.

  
Instance methods
----------------



*Inherits methods from its ancestor [`CSSStyleValue`](cssstylevalue).*

  [`CSSTransformValue.toMatrix()`](csstransformvalue/tomatrix)  Returns a new [`DOMMatrix`](dommatrix) object.

  [`CSSUnparsedValue.entries()`](cssunparsedvalue/entries)  Returns an array of a given object's own enumerable property `[key, value]` pairs in the same order as that provided by a [`for...in`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

  [`CSSUnparsedValue.forEach()`](cssunparsedvalue/foreach)  Executes a provided function once for each element of the `CSSTransformValue` object.

  [`CSSUnparsedValue.keys()`](cssunparsedvalue/keys)  Returns a new *array iterator* object that contains the keys for each index in the `CSSTransformValue` object.

  [`CSSUnparsedValue.values()`](cssunparsedvalue/values)  Returns a new *array iterator* object that contains the values for each index in the `CSSTransformValue` object.

  

Examples
--------


To Do.


Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # transformvalue-objects](https://drafts.css-houdini.org/css-typed-om/#transformvalue-objects) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@iterator` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `CSSTransformValue` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `CSSTransformValue` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `entries` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `forEach` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `is2D` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `keys` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `length` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `toMatrix` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `values` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSTransformValue>

CSSTransition
=============



The `CSSTransition` interface of the [Web Animations API](web_animations_api) represents an [`Animation`](animation) object used for a [CSS Transition](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions).


 EventTarget Animation CSSTransition

Instance properties
-------------------



*This interface inherits properties from its parent, [`Animation`](animation).*

  
[`CSSTransition.transitionProperty`](csstransition/transitionproperty) Read only 
  Returns the transition CSS property name as a string.

  

Instance methods
----------------



*This interface inherits methods from its parent, [`Animation`](animation).*

 No specific methods.



Examples
--------


### Inspecting the returned CSSTransition



The transition in the following example changes the width of the box on hover. Calling [`Element.getAnimations()`](element/getanimations) returns an array of all [`Animation`](animation) objects. In our case this returns a `CSSTransition` object, representing the animation created.

 
```
.box {
  background-color: #165baa;
  color: #fff;
  width: 100px;
  height: 100px;
  transition: width 4s;
}

.box:hover {
  width: 200px;
}

```
 
```
const item = document.querySelector(".box");
item.addEventListener("transitionrun", () => {
  let animations = document.querySelector(".box").getAnimations();
  console.log(animations[0]);
});

```


Specifications
--------------




| Specification |
| --- |
| [CSS Transitions Level 2 # the-CSSTransition-interface](https://w3c.github.io/csswg-drafts/css-transitions-2/#the-CSSTransition-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSTransition` | 84 | 84 | 75 | No | 70 | 13.1 | 84 | 84 | 79 | 60 | 13.4 | 14.0 |
| `transitionProperty` | 84 | 84 | 75 | No | 70 | 13.1 | 84 | 84 | 79 | 60 | 13.4 | 14.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSTransition>

CSSTranslate
============



The `CSSTranslate` interface of the [CSS\_Object\_Model#css\_typed\_object\_model](css_object_model#css_typed_object_model) represents the [translate()](https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/translate) value of the individual [`transform`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform) property in CSS. It inherits properties and methods from its parent [`CSSTransformValue`](csstransformvalue).


 CSSTransformComponent CSSTranslate

Constructor
-----------


 [`CSSTranslate()`](csstranslate/csstranslate)  Creates a new `CSSTranslate` object.

  
Instance properties
-------------------


 [`x`](csstranslate/x)  Returns or sets the x-axis value.

  [`y`](csstranslate/y)  Returns or sets the y-axis value.

  [`z`](csstranslate/z)  Returns or sets the z-axis value.

  
Examples
--------


To do.


Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # csstranslate](https://drafts.css-houdini.org/css-typed-om/#csstranslate) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSTranslate` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `CSSTranslate` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `x` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `y` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `z` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSTranslate>

CSSUnitValue
============



The `CSSUnitValue` interface of the [CSS\_Object\_Model#css\_typed\_object\_model](css_object_model#css_typed_object_model) represents values that contain a single unit type. For example, "42px" would be represented by a `CSSNumericValue`.


 CSSStyleValue CSSNumericValue CSSUnitValue

Constructor
-----------


 [`CSSUnitValue()`](cssunitvalue/cssunitvalue)  Creates a new `CSSUnitValue` object.

  
Instance properties
-------------------


 [`CSSUnitValue.value`](cssunitvalue/value)  Returns a double indicating the number of units.

  [`CSSUnitValue.unit`](cssunitvalue/unit)  Returns a string indicating the type of unit.

  
Static methods
--------------


*The interface may also inherit methods from its parent interface, [`CSSNumericValue`](cssnumericvalue).*


Instance methods
----------------


*The interface may also inherit methods from its parent interface, [`CSSNumericValue`](cssnumericvalue).*


Event handlers
--------------


None.


Examples
--------



The following shows a method of creating a [`CSSPositionValue`](csspositionvalue) from individual `CSSUnitValue` constructors.

 
```
let pos = new CSSPositionValue(
  new CSSUnitValue(5, "px"),
  new CSSUnitValue(10, "px")
);

```


Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # simple-numeric](https://drafts.css-houdini.org/css-typed-om/#simple-numeric) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSUnitValue` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `CSSUnitValue` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `unit` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `value` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSUnitValue>

CSSUnparsedValue
================



The `CSSUnparsedValue` interface of the [CSS\_Object\_Model#css\_typed\_object\_model](css_object_model#css_typed_object_model) represents property values that reference [custom properties](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Variables). It consists of a list of string fragments and variable references.

 Custom properties are represented by `CSSUnparsedValue` and [`var()`](https://developer.mozilla.org/en-US/docs/Web/CSS/var) references are represented using [`CSSVariableReferenceValue`](cssvariablereferencevalue).


 CSSStyleValue CSSUnparsedValue

Constructor
-----------


 [`CSSUnparsedValue()`](cssunparsedvalue/cssunparsedvalue)  Creates a new `CSSUnparsedValue` object.

  
Instance properties
-------------------


 [`CSSUnparsedValue.length`](cssunparsedvalue/length)  Returns the number of items in the `CSSUnparsedValue` object.

  
Instance methods
----------------


 [`CSSUnparsedValue.entries()`](cssunparsedvalue/entries)  Returns an array of a given object's own enumerable property `[key, value]` pairs in the same order as that provided by a [`for...in`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

  [`CSSUnparsedValue.forEach()`](cssunparsedvalue/foreach)  Executes a provided function once for each element of the `CSSUnparsedValue` object.

  [`CSSUnparsedValue.keys()`](cssunparsedvalue/keys)  Returns a new *array iterator* object that contains the keys for each index in the `CSSUnparsedValue` object.

  [`CSSUnparsedValue.values()`](cssunparsedvalue/values)  Returns a new *array iterator* object that contains the values for each index in the `CSSUnparsedValue` object.

  
Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # cssunparsedvalue](https://drafts.css-houdini.org/css-typed-om/#cssunparsedvalue) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@iterator` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `CSSUnparsedValue` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `CSSUnparsedValue` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `entries` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `forEach` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `keys` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `length` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `values` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |


See also
--------


* [`CSSImageValue`](cssimagevalue)
* [`CSSKeywordValue`](csskeywordvalue)
* [`CSSNumericValue`](cssnumericvalue)
* [`CSSPositionValue`](csspositionvalue)
* [`CSSTransformValue`](csstransformvalue)
* [Using the CSS Typed OM](css_typed_om_api/guide)
* [CSS Typed Object Model API](css_typed_om_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSUnparsedValue>

CSSValue
========



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The `CSSValue` interface represents the current computed value of a CSS property.

   **Note:** This interface was part of an attempt to create a typed CSS Object Model. This attempt has been abandoned, and most browsers do not implement it. 

 To achieve your purpose, you can use:

 * the untyped [CSS Object Model](css_object_model), widely supported, or
* the modern [CSS Typed Object Model API](css_typed_om_api), less supported and considered experimental.

 

Instance properties
-------------------


 
[`CSSValue.cssText`](cssvalue/csstext)  Deprecated 
  A string representing the current value.

  
[`CSSValue.cssValueType`](cssvalue/cssvaluetype) Read only   Deprecated 
  An `unsigned short` representing a code defining the type of the value. Possible values are:

 

| Constant | Description |
| --- | --- |
| `CSS_CUSTOM` | The value is a custom value. |
| `CSS_INHERIT` | The value is inherited and the `cssText` contains `"inherit"`. |
| `CSS_PRIMITIVE_VALUE` | The value is a primitive value and an instance of the [`CSSPrimitiveValue`](cssprimitivevalue) interface can be obtained by using binding-specific casting methods on this instance of the `CSSValue` interface. |
| `CSS_VALUE_LIST` | The value is a `CSSValue` list and an instance of the [`CSSValueList`](cssvaluelist) interface can be obtained by using binding-specific casting methods on this instance of the `CSSValue` interface. |

  
Specifications
--------------



 This feature was originally defined in the [DOM Style Level 2](https://www.w3.org/TR/DOM-Level-2-Style/) specification, but has been dropped from any standardization effort since then. 

 It has been superseded by a modern, but incompatible, [CSS Typed Object Model API](css_typed_om_api) that is now on the standard track.



Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSValue` | No | No | 1–62 | No | No | 3 | No | No | 4–62 | No | 1 | No |
| `cssText` | No | No | 1–62 | No | No | 7 | No | No | 4–62 | No | 7 | No |
| `cssValueType` | No | No | 1–62 | No | No | 7 | No | No | 4–62 | No | 7 | No |


See also
--------


* [`CSSPrimitiveValue`](cssprimitivevalue)
* [`CSSValueList`](cssvaluelist)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSValue>

CSSValueList
============



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The `CSSValueList` interface derives from the [`CSSValue`](cssvalue) interface and provides the abstraction of an ordered collection of CSS values.

   **Note:** This interface was part of an attempt to create a typed CSS Object Model. This attempt has been abandoned, and most browsers do not implement it. 

 To achieve your purpose, you can use:

 * the untyped [CSS Object Model](css_object_model), widely supported, or
* the modern [CSS Typed Object Model API](css_typed_om_api), less supported and considered experimental.

  Some properties allow an empty list in their syntax. In that case, these properties take the `none` identifier. So, an empty list means that the property has the value `none`.

 The items in the `CSSValueList` are accessible via an integral index, starting from 0.



Instance properties
-------------------



*Inherits properties from its parent, [`CSSValue`](cssvalue)*.

  
[`CSSValueList.length`](cssvaluelist/length) Read only   Deprecated 
  An `unsigned long` representing the number of `CSSValues` in the list.

  

Instance methods
----------------


 
[`CSSValueList.item()`](cssvaluelist/item)  Deprecated 
  This method is used to retrieve a [`CSSValue`](cssvalue) by ordinal index. The order in this collection represents the order of the values in the CSS style property. If index is greater than or equal to the number of values in the list, this returns `null`.

  
Specifications
--------------



 This feature was originally defined in the [DOM Style Level 2](https://www.w3.org/TR/DOM-Level-2-Style/) specification, but has been dropped from any standardization effort since then. 

 It has been superseded by a modern, but incompatible, [CSS Typed Object Model API](css_typed_om_api) that is now on the standard track.



Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSValueList` | No | No | 1–62 | No | No | 3 | No | No | 4–62 | No | 1 | No |
| `item` | No | No | 1–62 | No | No | 3 | No | No | 4–62 | No | 1 | No |
| `length` | No | No | 1–62 | No | No | 10 | No | No | 4–62 | No | 10 | No |


See also
--------


* [`CSSPrimitiveValue`](cssprimitivevalue)
* [`CSSValue`](cssvalue)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSValueList>

CSSVariableReferenceValue
=========================


The `CSSVariableReferenceValue` interface of the [CSS\_Object\_Model#css\_typed\_object\_model](css_object_model#css_typed_object_model) allows you to create a custom name for a built-in CSS value. This object functionality is sometimes called a "CSS variable" and serves the same purpose as the [`var()`](https://developer.mozilla.org/en-US/docs/Web/CSS/var) function. The custom name must begin with two dashes.


Constructor
-----------


 [`CSSVariableReferenceValue()`](cssvariablereferencevalue/cssvariablereferencevalue)  Creates a new `CSSVariableReferenceValue` object.

  
Instance properties
-------------------


 [`CSSVariableReferenceValue.variable`](cssvariablereferencevalue/variable)  Returns the custom name passed to the constructor.

  
[`CSSVariableReferenceValue.fallback`](cssvariablereferencevalue/fallback) Read only 
  Returns the built-in CSS value for the custom name.

  
Instance methods
----------------


None.


Specifications
--------------




| Specification |
| --- |
| [CSS Typed OM Level 1 # cssvariablereferencevalue](https://drafts.css-houdini.org/css-typed-om/#cssvariablereferencevalue) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CSSVariableReferenceValue` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `CSSVariableReferenceValue` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `fallback` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `variable` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CSSVariableReferenceValue>

CustomElementRegistry
=====================


The `CustomElementRegistry` interface provides methods for registering custom elements and querying registered elements. To get an instance of it, use the [`window.customElements`](window/customelements) property.


Instance methods
----------------


 [`CustomElementRegistry.define()`](customelementregistry/define)  Defines a new [custom element](web_components/using_custom_elements).

  [`CustomElementRegistry.get()`](customelementregistry/get)  Returns the constructor for the named custom element, or [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) if the custom element is not defined.

  [`CustomElementRegistry.upgrade()`](customelementregistry/upgrade)  Upgrades a custom element directly, even before it is connected to its shadow root.

  [`CustomElementRegistry.whenDefined()`](customelementregistry/whendefined)  Returns an empty [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves when a custom element becomes defined with the given name. If such a custom element is already defined, the returned promise is immediately fulfilled.

  
Examples
--------



The following code is taken from our [word-count-web-component](https://github.com/mdn/web-components-examples/tree/main/word-count-web-component) example ([see it live also](https://mdn.github.io/web-components-examples/word-count-web-component/)). Note how we use the [`CustomElementRegistry.define()`](customelementregistry/define) method to define the custom element after creating its class.

 
```
// Create a class for the element
class WordCount extends HTMLParagraphElement {
  constructor() {
    // Always call super first in constructor
    super();

    // count words in element's parent element
    const wcParent = this.parentNode;

    function countWords(node) {
      const text = node.innerText || node.textContent;
      return text
        .trim()
        .split(/\s+/g)
        .filter((a) => a.trim().length > 0).length;
    }

    const count = `Words: ${countWords(wcParent)}`;

    // Create a shadow root
    const shadow = this.attachShadow({ mode: "open" });

    // Create text node and add word count to it
    const text = document.createElement("span");
    text.textContent = count;

    // Append it to the shadow root
    shadow.appendChild(text);

    // Update count when element content changes
    setInterval(() => {
      const count = `Words: ${countWords(wcParent)}`;
      text.textContent = count;
    }, 200);
  }
}

// Define the new element
customElements.define("word-count", WordCount, { extends: "p" });

```
  **Note:** The `CustomElementRegistry` is available through the [`Window.customElements`](window/customelements) property.

 

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # custom-elements-api](https://html.spec.whatwg.org/multipage/custom-elements.html#custom-elements-api) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CustomElementRegistry` | 54 | 79 | 63 | No | 41 | 10.1 | 54 | 54 | 63 | 41 | 10.3 | 6.0 |
| `builtin_element_support` | 67 | 79 | 63 | No | 54 | NoSee [bug 182671](https://webkit.org/b/182671). | 67 | 67 | 63 | 48 | NoSee [bug 182671](https://webkit.org/b/182671). | 9.0 |
| `define` | 54 | 79 | 63 | No | 41 | 10.1 | 54 | 54 | 63 | 41 | 10.3 | 6.0 |
| `get` | 54 | 79 | 63 | No | 41 | 10.1 | 54 | 54 | 63 | 41 | 10.3 | 6.0 |
| `upgrade` | 68 | 79 | 63 | No | 55 | 12.1 | 68 | 68 | 63 | 48 | 12.2 | 10.0 |
| `whenDefined` | 54 | 79 | 63 | No | 41 | 10.1 | 54 | 54 | 63 | 41 | 10.3 | 6.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry>

CustomEvent
===========



The `CustomEvent` interface represents events initialized by an application for any purpose.


 **Note:** This feature is available in [Web Workers](web_workers_api)

   Event CustomEvent

Constructor
-----------


 [`CustomEvent()`](customevent/customevent)  Creates a new `CustomEvent`.

  
Instance properties
-------------------



*This interface inherits properties from its parent, [`Event`](event).*

  
[`CustomEvent.detail`](customevent/detail) Read only 
  Returns any data passed when initializing the event.

  

Instance methods
----------------



*This interface inherits methods from its parent, [`Event`](event).*

  
[`CustomEvent.initCustomEvent()`](customevent/initcustomevent)  Deprecated 
  Initializes a `CustomEvent` object. If the event has already been dispatched, this method does nothing.

  

Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-customevent](https://dom.spec.whatwg.org/#interface-customevent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `CustomEvent` | 15 | 12 | 11 | No | 11.6 | 6 | 4.4 | 18 | 14 | 12 | 6 | 1.0 |
| `CustomEvent` | 5 | 12 | 6 | 9 | 11 | 5 | 3 | 18 | 6 | 11 | 5 | 1.0 |
| `detail` | 5 | 12 | 6 | 9 | 11.6 | 5 | 3 | 18 | 6 | 12 | 5 | 1.0 |
| `initCustomEvent` | 5 | 12 | 6 | 9 | 11 | 5 | 3 | 18 | 6 | 11 | 5 | 7.0 |
| `worker_support` | 43 | 17 | 48 | No | 30 | 12 | 43 | 43 | 48 | 30 | 12 | 4.0 |


See also
--------


* [`Window.postMessage()`](window/postmessage)
* [Creating and triggering events](https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent>

CustomStateSet
==============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `CustomStateSet` interface of the [Document Object Model](document_object_model) stores a list of possible states for a custom element to be in, and allows states to be added and removed from the set.



Description
-----------



An HTML form element, such as a checkbox has different *states*, "checked" and "unchecked". Likewise, developers creating custom elements need to assign possible states to these elements. The `CustomStateList` allows these states to be stored, and accessed from the custom element.

 An instance of `CustomStateList` is returned by [`ElementInternals.states`](elementinternals/states). The `CustomStateList` object is described as *setlike*, and therefore the methods behave in a similar manner to those on a [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set).

 Each value stored in a `CustomStateList` is a `<dashed-ident>`, in the format `--mystate`.



### Interaction with CSS


 States are stored as a `<dashed-ident>` as this format can then be accessed from CSS using the *custom state pseudo-class*. In the same way that you can use CSS to determine if a checkbox is checked using the [`:checked`](https://developer.mozilla.org/en-US/docs/Web/CSS/:checked) pseudo-class, you can use a custom state pseudo-class to select a custom element that is in a certain state. 


Instance properties
-------------------


 
[`CustomStateSet.size`](customstateset/size)  Experimental 
  Returns the number of values in the `CustomStateSet`.

  
Instance methods
----------------


 
[`CustomStateSet.add()`](customstateset/add)  Experimental 
  Adds a value to the set, first checking that the *value* is a `<dashed-ident>`.

  
[`CustomStateSet.clear()`](customstateset/clear)  Experimental 
  Removes all elements from the `CustomStateSet` object.

  
[`CustomStateSet.delete()`](customstateset/delete)  Experimental 
  Removes one value from the `CustomStateSet` object.

  
[`CustomStateSet.entries()`](customstateset/entries)  Experimental 
  Returns a new iterator with the values for each element in the `CustomStateSet` in insertion order.

  
[`CustomStateSet.forEach()`](customstateset/foreach)  Experimental 
  Executes a provided function for each value in the `CustomStateSet` object.

  
[`CustomStateSet.has()`](customstateset/has)  Experimental 
  Returns a [`Boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean) asserting whether an element is present with the given value.

  
[`CustomStateSet.keys()`](customstateset/keys)  Experimental 
  An alias for [`CustomStateSet.values()`](customstateset/values).

  
[`CustomStateSet.values()`](customstateset/values)  Experimental 
  Returns a new iterator object that yields the values for each element in the `CustomStateSet` object in insertion order.

  
Examples
--------



The following function adds and removes the state `--checked` to a `CustomStateSet`, then prints to the console `true` or `false` as the custom checkbox is checked or unchecked.

 The state of the element can be accessed from CSS using the custom state pseudo-class `--checked`.

 
```
class MyCustomElement extends HTMLElement {
  set checked(flag) {
    if (flag) {
      this._internals.states.add("--checked");
    } else {
      this._internals.states.delete("--checked");
    }

    console.log(this._internals.states.has("--checked"));
  }
}

```
 
```
labeled-checkbox {
  border: dashed red;
}
labeled-checkbox:--checked {
  border: solid;
}

```


Specifications
--------------




| Specification |
| --- |
| [Custom State Pseudo Class # customstateset](https://wicg.github.io/custom-state-pseudo-class/#customstateset) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@iterator` | 90 | 90 | No | No | 76 | No | 90 | 90 | No | 64 | No | 15.0 |
| `CustomStateSet` | 90 | 90 | No | No | 76 | No | 90 | 90 | No | 64 | No | 15.0 |
| `add` | 90 | 90 | No | No | 76 | No | 90 | 90 | No | 64 | No | 15.0 |
| `clear` | 90 | 90 | No | No | 76 | No | 90 | 90 | No | 64 | No | 15.0 |
| `delete` | 90 | 90 | No | No | 76 | No | 90 | 90 | No | 64 | No | 15.0 |
| `entries` | 90 | 90 | No | No | 76 | No | 90 | 90 | No | 64 | No | 15.0 |
| `forEach` | 90 | 90 | No | No | 76 | No | 90 | 90 | No | 64 | No | 15.0 |
| `has` | 90 | 90 | No | No | 76 | No | 90 | 90 | No | 64 | No | 15.0 |
| `keys` | 90 | 90 | No | No | 76 | No | 90 | 90 | No | 64 | No | 15.0 |
| `size` | 90 | 90 | No | No | 76 | No | 90 | 90 | No | 64 | No | 15.0 |
| `values` | 90 | 90 | No | No | 76 | No | 90 | 90 | No | 64 | No | 15.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/CustomStateSet>

DataTransfer
============



The `DataTransfer` object is used to hold the data that is being dragged during a drag and drop operation. It may hold one or more data items, each of one or more data types. For more information about drag and drop, see [HTML Drag and Drop API](html_drag_and_drop_api).

 This object is available from the [`dataTransfer`](dragevent/datatransfer) property of all [`drag events`](dragevent).



Constructor
-----------


 [`DataTransfer()`](datatransfer/datatransfer)  Creates and returns a new `DataTransfer` object.

  
Instance properties
-------------------


### Standard properties


 [`DataTransfer.dropEffect`](datatransfer/dropeffect)  Gets the type of drag-and-drop operation currently selected or sets the operation to a new type. The value must be `none`, `copy`, `link` or `move`.

  [`DataTransfer.effectAllowed`](datatransfer/effectallowed)  Provides all of the types of operations that are possible. Must be one of `none`, `copy`, `copyLink`, `copyMove`, `link`, `linkMove`, `move`, `all` or `uninitialized`.

  [`DataTransfer.files`](datatransfer/files)  Contains a list of all the local files available on the data transfer. If the drag operation doesn't involve dragging files, this property is an empty list.

  
[`DataTransfer.items`](datatransfer/items) Read only 
  Gives a [`DataTransferItemList`](datatransferitemlist) object which is a list of all of the drag data.

  
[`DataTransfer.types`](datatransfer/types) Read only 
  An array of strings giving the formats that were set in the [`dragstart`](htmlelement/dragstart_event) event.

  
### Gecko properties


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.


Instance methods
----------------


### Standard methods


 [`DataTransfer.clearData()`](datatransfer/cleardata)  Remove the data associated with a given type. The type argument is optional. If the type is empty or not specified, the data associated with all types is removed. If data for the specified type does not exist, or the data transfer contains no data, this method will have no effect.

  [`DataTransfer.getData()`](datatransfer/getdata)  Retrieves the data for a given type, or an empty string if data for that type does not exist or the data transfer contains no data.

  [`DataTransfer.setData()`](datatransfer/setdata)  Set the data for a given type. If data for the type does not exist, it is added at the end, such that the last item in the types list will be the new format. If data for the type already exists, the existing data is replaced in the same position.

  [`DataTransfer.setDragImage()`](datatransfer/setdragimage)  Set the image to be used for dragging if a custom one is desired.

  
### Gecko methods


**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.


Examples
--------


Every method and property listed in this document has its own reference page and each reference page either directly includes an example of the interface or has a link to an example.


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-datatransfer-interface](https://html.spec.whatwg.org/multipage/dnd.html#the-datatransfer-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DataTransfer` | 59 | 17 | 62 | No | 46 | 14.1 | 59 | 59 | 62 | 44 | 14.5 | 8.0 |
| `DataTransfer` | 3 | 12 | 3.5As of Firefox 52, the [`DataTransfer.types`](https://developer.mozilla.org/docs/Web/API/DataTransfer/types) property returns a frozen array of [`DOMString`](https://developer.mozilla.org/docs/Web/API/DOMString)s as per spec, rather than a [`DOMStringList`](https://developer.mozilla.org/docs/Web/API/DOMStringList). | 8 | 12 | 4 | ≤37 | 18 | 4As of Firefox 52, the [`DataTransfer.types`](https://developer.mozilla.org/docs/Web/API/DataTransfer/types) property returns a frozen array of [`DOMString`](https://developer.mozilla.org/docs/Web/API/DOMString)s as per spec, rather than a [`DOMStringList`](https://developer.mozilla.org/docs/Web/API/DOMStringList). | 12 | 3.2 | 1.0 |
| `addElement` | No | No | 3.5 | No | No | No | No | No | 4 | No | No | No |
| `clearData` | 3 | 12 | 3.5 | 8 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `dropEffect` | 3 | 12 | 3.5 | 8 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `effectAllowed` | 3 | 12 | 3.5 | 8 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `files` | 3 | 12 | 3.6 | 10 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `getData` | 3 | 12 | 3.5 | 8 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `items` | 4 | 12 | 50 | No | 12 | 11.1 | ≤37 | 18 | 52 | 12 | 11.3 | 1.0 |
| `mozCursor` | No | No | 3.5 | No | No | No | No | No | 4 | No | No | No |
| `mozSourceNode` | No | No | 4 | No | No | No | No | No | 4 | No | No | No |
| `mozUserCancelled` | No | No | 3.5 | No | No | No | No | No | 4 | No | No | No |
| `setData` | 3 | 12 | 3.5 | 8 | 12 | 5 | ≤37 | 18 | 4 | 12 | 5 | 1.0 |
| `setDragImage` | 3 | 18 | 3.5 | No | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `types` | 3 | 12 | 3.5 | 10["The property returns a [`DOMStringList`](https://developer.mozilla.org/docs/Web/API/DOMStringList).", "`Text` is returned instead of `text/plain`"] | ≤12.1As of Opera 12, `Text` is returned instead of `text/plain` | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |


See also
--------


* [Drag and drop](html_drag_and_drop_api)
* [Drag Operations](html_drag_and_drop_api/drag_operations)
* [Recommended Drag Types](html_drag_and_drop_api/recommended_drag_types)
* [DataTransfer test - Paste or Drag](https://codepen.io/tech_query/pen/MqGgap)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer>

DataTransferItem
================



The `DataTransferItem` object represents one drag data item. During a *drag operation*, each [`drag event`](dragevent) has a [`dataTransfer`](dragevent/datatransfer) property which contains a [`list`](datatransferitemlist) of drag data items. Each item in the list is a `DataTransferItem` object.

 This interface has no constructor.



Instance properties
-------------------


 
[`DataTransferItem.kind`](datatransferitem/kind) Read only 
  The *kind* of drag data item, `string` or `file`.

  
[`DataTransferItem.type`](datatransferitem/type) Read only 
  The drag data item's type, typically a MIME type.

  
Instance methods
----------------


 [`DataTransferItem.getAsFile()`](datatransferitem/getasfile)  Returns the [`File`](file) object associated with the drag data item (or null if the drag item is not a file).

  
[`DataTransferItem.getAsFileSystemHandle()`](datatransferitem/getasfilesystemhandle)  Experimental 
  Returns a [`FileSystemFileHandle`](filesystemfilehandle) if the dragged item is a file, or a [`FileSystemDirectoryHandle`](filesystemdirectoryhandle) if the dragged item is a directory.

  [`DataTransferItem.getAsString()`](datatransferitem/getasstring)  Invokes the specified callback with the drag data item string as its argument.

  [`DataTransferItem.webkitGetAsEntry()`](datatransferitem/webkitgetasentry)  Returns an object based on [`FileSystemEntry`](filesystementry) representing the selected file's entry in its file system. This will generally be either a [`FileSystemFileEntry`](filesystemfileentry) or [`FileSystemDirectoryEntry`](filesystemdirectoryentry) object.

  
Example
-------


All of this interface's methods and properties have their own reference page, and each reference page has an example of its usage.


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-datatransferitem-interface](https://html.spec.whatwg.org/multipage/dnd.html#the-datatransferitem-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DataTransferItem` | 11 | 12 | 50 | No | 12 | 5.1 | 4 | 18 | 50 | ≤14 | 5 | 1.0 |
| `getAsFile` | 11 | 12 | 50 | No | 12 | 5.1 | 4 | 18 | 50 | ≤14 | 5 | 1.0 |
| `getAsFileSystemHandle` | 86 | 86 | No | No | 72 | No | No | No | No | No | No | No |
| `getAsString` | 11 | 12 | 50 | No | 12 | 5.1 | 4 | 18 | 50 | ≤14 | 5 | 1.0 |
| `kind` | 11 | 12 | 50 | No | 12 | 5.1 | 4 | 18 | 50 | ≤14 | 5 | 1.0 |
| `type` | 11 | 12 | 50 | No | 12 | 5.1 | 4 | 18 | 50 | ≤14 | 5 | 1.0 |
| `webkitGetAsEntry` | 13 | 14 | 50 | No | 15 | 11.1 | No | 18 | 50 | 14 | 11.3 | 1.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem>

DeviceMotionEvent
=================



The `DeviceMotionEvent` interface provides web developers with information about the speed of changes for the device's position and orientation.

  **Warning:** Currently, Firefox and Chrome do not handle the coordinates the same way. Take care about this while using them.

 
 Event DeviceMotionEvent

Constructor
-----------


 [`DeviceMotionEvent()`](devicemotionevent/devicemotionevent)  Creates a new `DeviceMotionEvent`.

  
Instance properties
-------------------


 
[`DeviceMotionEvent.acceleration`](devicemotionevent/acceleration) Read only 
  An object giving the acceleration of the device on the three axis X, Y and Z. Acceleration is expressed in [m/s²](https://en.wikipedia.org/wiki/Meter_per_second_squared).

  
[`DeviceMotionEvent.accelerationIncludingGravity`](devicemotionevent/accelerationincludinggravity) Read only 
  An object giving the acceleration of the device on the three axis X, Y and Z with the effect of gravity. Acceleration is expressed in [m/s²](https://en.wikipedia.org/wiki/Meter_per_second_squared).

  
[`DeviceMotionEvent.rotationRate`](devicemotionevent/rotationrate) Read only 
  An object giving the rate of change of the device's orientation on the three orientation axis alpha, beta and gamma. Rotation rate is expressed in degrees per seconds.

  
[`DeviceMotionEvent.interval`](devicemotionevent/interval) Read only 
  A number representing the interval of time, in milliseconds, at which data is obtained from the device.

  
Example
-------



```
window.addEventListener("devicemotion", (event) => {
  console.log(`${event.acceleration.x} m/s2`);
});

```

Specifications
--------------




| Specification |
| --- |
| [DeviceOrientation Event Specification # devicemotion](https://w3c.github.io/deviceorientation/#devicemotion) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DeviceMotionEvent` | 59 | 14 | 29 | No | 46 | No | 59 | 59 | 29 | 43 | No | 7.0 |
| `DeviceMotionEvent` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |
| `acceleration` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |
| `accelerationIncludingGravity` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |
| `interval` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |
| `requestPermission` | No | No | No | No | No | No | No | No | No | No | 14.5 | No |
| `rotationRate` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |


See also
--------


* [`deviceorientation`](window/deviceorientation_event)
* [`DeviceOrientationEvent`](deviceorientationevent)
* [`devicemotion`](window/devicemotion_event)
* [`Accelerometer`](accelerometer)
* [`LinearAccelerationSensor`](linearaccelerationsensor)
* [Detecting device orientation](device_orientation_events/detecting_device_orientation)
* [Orientation and motion data explained](device_orientation_events/orientation_and_motion_data_explained)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent>

DeviceMotionEventAcceleration
=============================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `DeviceMotionEventAcceleration` object provides information about the amount of acceleration the device is experiencing along all three axes.



Instance properties
-------------------


 
[`DeviceMotionEventAcceleration.x`](devicemotioneventacceleration/x) Read only 
  The amount of acceleration along the X axis.

  
[`DeviceMotionEventAcceleration.y`](devicemotioneventacceleration/y) Read only 
  The amount of acceleration along the Y axis.

  
[`DeviceMotionEventAcceleration.z`](devicemotioneventacceleration/z) Read only 
  The amount of acceleration along the Z axis.

  
Specifications
--------------




| Specification |
| --- |
| [DeviceOrientation Event Specification # devicemotioneventacceleration](https://w3c.github.io/deviceorientation/#devicemotioneventacceleration) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DeviceMotionEventAcceleration` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |
| `x` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |
| `y` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |
| `z` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEventAcceleration>

DirectoryEntrySync
==================



**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.


**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The `DirectoryEntrySync` interface represents a directory in a file system. It includes methods for creating, reading, looking up, and recursively removing files in a directory.

   **Warning:** This interface is deprecated and is no more on the standard track. *Do not use it anymore.* Use the [File and Directory Entries API](file_and_directory_entries_api) instead. 

 

Basic concepts
--------------


If you want to create subdirectories, you have to create each child directory in sequence. If you try to create a directory using a full path that includes parent directories that do not exist yet, you get an error. So create the hierarchy by recursively adding a new path after creating the parent directory.


### Example



The `getFile()` method returns a `FileEntrySync`, which represents a file in the file system. The following creates an empty file called `logs.txt` in the root directory.

 
```
const fileEntry = fs.root.getFile("logs.txt", { create: true });

```
 The `getDirectory()` method returns a `DirectoryEntrySync`, which represents a file in the file system. The following creates a new directory called `project_dir` in the root directory.

 
```
const dirEntry = fs.root.getDirectory("project\_dir", { create: true });

```


Method overview
---------------


* [createReader()](#createreader)
* [getFile()](#getfile)
* [getDirectory()](#getdirectory)
* [removeRecursively()](#removerecursively)

Instance methods
----------------


### createReader()



Creates a new `DirectoryReaderSync` to read entries from this directory.

 #### Syntax

 
```
createReader();

```
 ##### Returns

  [`DirectoryReaderSync`](directoryreadersync)  Represents a directory in a file system.

   ##### Parameter

 None

 ##### Exceptions

 This method can raise a [`DOMException`](domexception) with the following codes:

 

| Exception | Description |
| --- | --- |
| `NOT_FOUND_ERR` | The directory does not exist. |
| `SECURITY_ERR` | The browser determined that it was not safe to look up the metadata. [ todo: Explain why ] |



### getFile()



Depending on how you've set the `options` parameter, the method either creates a file or looks up an existing file.

 #### Syntax

 
```
getFile(path)
getFile(path, options)

```
 ##### Parameter

  `path`  Either an absolute path or a relative path from the directory to the file to be looked up or created. You cannot create a file whose immediate parent does not exist. Create the parent directory first.

  `options`  (optional) An object literal describing the behavior of the method. If the file does not exist, it is created.

   

| Object literal | Condition | Result |
| --- | --- | --- |
| `create: true``exclusive: true` | Path already exists | An error is thrown. |
| `create: true``exclusive: false` | Path doesn't exist and no other error occurs | A file is created. If a file already exists, no error is thrown. |
| `create: false`(`exclusive` is ignored) | Path exists | The file is returned. |
| `create: false`(`exclusive` is ignored) | Path doesn't exist | An error is thrown. |
| `create: false`(`exclusive` is ignored) | Path exists, but is a directory | An error is thrown. |

 ##### Returns

  [`FileEntrySync`](fileentrysync)  Represents a file in a file system.

   ##### Exceptions

 This method can raise a [`DOMException`](domexception) with the following codes:

 

| Exception | Description |
| --- | --- |
| `ENCODING_ERR` | The path supplied is invalid. |
| `NOT_FOUND_ERR` | The path was structurally correct, but refers to a resource that does not exist. |
| `NO_MODIFICATION_ALLOWED_ERR` | This is a permission issue. The target directory or file is not writable. |
| `PATH_EXISTS_ERR` | The file already exists. You cannot create another one with the same path. |
| `QUOTA_EXCEEDED_ERROR` | The operation would cause the application to exceed its storage quota. |
| `SECURITY_ERR` | The application does not have permission to access the element referred to by path. [ todo: Explain why ] |
| `TYPE_MISMATCH_ERR` | The path supplied exists, but it is not a directory. |



### getDirectory()



Creates or looks up a directory. The method is similar to `getFile()` with DirectoryEntrySync being passed.

 #### Syntax

 
```
getDirectory(path)
getDirectory(path, options)

```
 ##### Parameter

  `path`  Either an absolute path or a relative path from the directory to the file to be looked up or created. You cannot create a file whose immediate parent does not exist. Create the parent directory first.

  `options`  (optional) An object literal describing the behavior of the method if the file does not exist.

   

| Object literal | Condition | Result |
| --- | --- | --- |
| `create: true``exclusive: true` | Path already exists | An error is thrown. |
| `create: true``exclusive: false` | Path doesn't exist and no other error occurs | A directory is created. If a file already exists, no error is thrown. |
| `create: false`(`exclusive` is ignored) | Path exists | The directory is returned. |
| `create: false`(`exclusive` is ignored) | Path doesn't exist | An error is thrown. |
| `create: false`(`exclusive` is ignored) | Path exists, but is a directory | An error is thrown. |

 ##### Returns

  [`DirectoryEntrySync`](directoryreadersync)  Represents a directory in a file system.

   ##### Exceptions

 This method can raise a [`DOMException`](domexception) with the following codes:

 

| Exception | Description |
| --- | --- |
| `ENCODING_ERR` | The path supplied is invalid. |
| `NOT_FOUND_ERR` | The path was structurally correct, but refers to a resource that does not exist. |
| `NO_MODIFICATION_ALLOWED_ERR` | This is a permission issue. The target directory or file is not writable. |
| `PATH_EXISTS_ERR` | The file already exists. You cannot create another one with the same path. |
| `QUOTA_EXCEEDED_ERROR` | The operation would cause the application to exceed its storage quota. |
| `SECURITY_ERR` | The application does not have permission to access the element referred to by path. [ todo: Explain why ] |
| `TYPE_MISMATCH_ERR` | The path supplied exists, but it is not a directory. |



### removeRecursively()



Deletes a directory and all of its contents. You cannot delete the root directory of a file system.

 If you delete a directory that contains a file that cannot be removed or if an error occurs while the deletion is in progress, some of the contents might not be deleted. Catch these cases with error callbacks and retry the deletion.

 #### Syntax

 
```
removeRecursively()

```
 ##### Parameter

 None

 ##### Returns


[`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) ##### Exceptions

 This method can raise a [`DOMException`](domexception) with the following codes:

 

| Exception | Description |
| --- | --- |
| `NOT_FOUND_ERR` | The target directory does not exist. |
| `INVALID_STATE_ERR` |  This directory is not longer valid for some reason other than being deleted. [todo: Explain more ] |
| `NO_MODIFICATION_ALLOWED_ERR` |  One of the following is not writable: the directory, its parent directory, and some of the content in the directory.  |
| `SECURITY_ERR` |  The application does not have permission to access the target directory, its parent, or some of its contents.  |



Specifications
--------------


 This feature is not part of any current specification. It is no longer on track to become a standard. Use the [File and Directory Entries API](file_and_directory_entries_api) instead. 


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DirectoryEntrySync` | 13 | 79 | No | No | No | No | 37 | 18 | No | No | No | 1.0 |


See also
--------


* [File and Directory Entries API](file_and_directory_entries_api)
* [Introduction to the File and Directory Entries API](file_and_directory_entries_api/introduction)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DirectoryEntrySync>

DirectoryReaderSync
===================



**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.


**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The `DirectoryReaderSync` interface lets you read the entries in a directory.

   **Warning:** This interface is deprecated and is no more on the standard track. *Do not use it anymore.* Use the [File and Directory Entries API](file_and_directory_entries_api) instead. 

 

Basic concepts
--------------


Before you call the only method in this interface, [`readEntries()`](#readentries), create the [`DirectoryEntrySync`](directoryentrysync) object. But DirectoryEntrySync (as well as [`FileEntrySync`](fileentrysync)) is not a data type that you can pass between a calling app and Web Worker thread. It's not a big deal, because you don't really need to have the main app and the worker thread see the same JavaScript object; you just need them to access the same files. You can do that by passing a list of `filesystem:` URLs—which are just strings—instead of a list of entries. You can also use the `filesystem:` URL to look up the entry with `resolveLocalFileSystemURL()`. That gets you back to a DirectoryEntrySync (as well as FileEntrySync) object.


### Example



In the following code snippet from [HTML5Rocks (web.dev)](https://web.dev/filesystem-sync/), we create Web Workers and pass data from it to the main app.

 
```
// Taking care of the browser-specific prefixes.
window.resolveLocalFileSystemURL =
  window.resolveLocalFileSystemURL || window.webkitResolveLocalFileSystemURL;

// Create web workers
const worker = new Worker("worker.js");
worker.onmessage = (e) => {
  const urls = e.data.entries;
  urls.forEach((url) => {
    window.resolveLocalFileSystemURL(url, (fileEntry) => {
      // Print out file's name.
      console.log(fileEntry.name);
    });
  });
};

worker.postMessage({ cmd: "list" });

```
 The following is `worker.js` code that gets the contents of the directory.

 
```
// worker.js

// Taking care of the browser-specific prefixes.
self.requestFileSystemSync =
  self.webkitRequestFileSystemSync || self.requestFileSystemSync;

// Global for holding the list of entry file system URLs.
const paths = [];

function getAllEntries(dirReader) {
  const entries = dirReader.readEntries();

  for (const entry of entries) {
    // Stash this entry's filesystem in URL
    paths.push(entry.toURL());

    // If this is a directory, traverse.
    if (entry.isDirectory) {
      getAllEntries(entry.createReader());
    }
  }
}

// Forward the error to main app.
function onError(e) {
  postMessage(`ERROR: ${e.toString()}`);
}

self.onmessage = (e) => {
  const cmd = e.data.cmd;

  // Ignore everything else except our 'list' command.
  if (!cmd || cmd !== "list") {
    return;
  }

  try {
    const fs = requestFileSystemSync(TEMPORARY, 1024 \* 1024 /\*1MB\*/);

    getAllEntries(fs.root.createReader());

    self.postMessage({ entries: paths });
  } catch (e) {
    onError(e);
  }
};

```


Method
------


### readEntries()



Returns a list of entries from a specific directory. Call this method until an empty array is returned.

 #### Syntax

 
```
readEntries()

```
 ##### Return value

 Array containing [`FileEntrySync`](fileentrysync) and [`DirectoryEntrySync`](directoryentrysync)

 ##### Parameter

 None

 ##### Exceptions

 This method can raise a [DOMException](domexception) with the following codes:

 

| Exception | Description |
| --- | --- |
| `NOT_FOUND_ERR` | The directory does not exist. |
| `INVALID_STATE_ERR` | The directory has been modified since the first call to readEntries was processed. |
| `SECURITY_ERR` | The browser determined that it was not safe to look up the metadata. |



Specifications
--------------


This feature is not part of any specification anymore. It is no longer on track to become a standard.


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DirectoryReaderSync` | 13 | 79 | No | No | No | No | 37 | 18 | No | No | No | 1.0 |


See also
--------


* [File and Directory Entries API](file_and_directory_entries_api)
* [Introduction to the File and Directory Entries API](file_and_directory_entries_api/introduction)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DirectoryReaderSync>

DataTransferItemList
====================



The `DataTransferItemList` object is a list of [`DataTransferItem`](datatransferitem) objects representing items being dragged. During a *drag operation*, each [`DragEvent`](dragevent) has a [`dataTransfer`](dragevent/datatransfer) property and that property is a `DataTransferItemList`.

 The individual items can be accessed using the [bracket notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#bracket_notation) `[]`.

 This interface has no constructor.



Instance properties
-------------------


 
[`DataTransferItemList.length`](datatransferitemlist/length) Read only 
  An `unsigned long` that is the number of drag items in the list.

  
Instance methods
----------------


 [`DataTransferItemList.add()`](datatransferitemlist/add)  Adds an item (either a [`File`](file) object or a string) to the drag item list and returns a [`DataTransferItem`](datatransferitem) object for the new item.

  [`DataTransferItemList.remove()`](datatransferitemlist/remove)  Removes the drag item from the list at the given index.

  [`DataTransferItemList.clear()`](datatransferitemlist/clear)  Removes all of the drag items from the list.

  `DataTransferItemList.operator[]`  Getter that returns a [`DataTransferItem`](datatransferitem) at the given index.

  
Example
-------


This example shows how to use drag and drop.


### JavaScript



```
function dragstartHandler(ev) {
  console.log("dragStart");

  // Add this element's id to the drag payload so the drop handler will
  // know which element to add to its tree
  const dataList = ev.dataTransfer.items;
  dataList.add(ev.target.id, "text/plain");

  // Add some other items to the drag payload
  dataList.add("<p>Paragraph…</p>", "text/html");
  dataList.add("http://www.example.org", "text/uri-list");
}

function dropHandler(ev) {
  console.log("Drop");
  ev.preventDefault();

  // Loop through the dropped items and log their data
  for (const item of ev.dataTransfer.items) {
    if (item.kind === "string" && item.type.match(/^text\/plain/)) {
      // This item is the target node
      item.getAsString((s) => {
        ev.target.appendChild(document.getElementById(s));
      });
    } else if (item.kind === "string" && item.type.match(/^text\/html/)) {
      // Drag data item is HTML
      item.getAsString((s) => {
        console.log(`… Drop: HTML = ${s}`);
      });
    } else if (item.kind === "string" && item.type.match(/^text\/uri-list/)) {
      // Drag data item is URI
      item.getAsString((s) => {
        console.log(`… Drop: URI = ${s}`);
      });
    }
  }
}

function dragoverHandler(ev) {
  console.log("dragOver");
  ev.preventDefault();

  // Set the dropEffect to move
  ev.dataTransfer.dropEffect = "move";
}

function dragendHandler(ev) {
  console.log("dragEnd");
  const dataList = ev.dataTransfer.items;

  // Clear any remaining drag data
  dataList.clear();
}

```

### HTML



```
<div>
  <p
 id="source"
 ondragstart="dragstartHandler(event);"
 ondragend="dragendHandler(event);"
 draggable="true">
    Select this element, drag it to the Drop Zone and then release the selection
    to move the element.
  </p>
</div>
<div
 id="target"
 ondrop="dropHandler(event);"
 ondragover="dragoverHandler(event);">
  Drop Zone
</div>

```

### CSS



```
div {
  margin: 0em;
  padding: 2em;
}

#source {
  color: blue;
  border: 1px solid black;
}

#target {
  border: 1px solid black;
}

```

### Result



Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-datatransferitemlist-interface](https://html.spec.whatwg.org/multipage/dnd.html#the-datatransferitemlist-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DataTransferItemList` | 13 | 12 | 50 | No | 12 | 6 | 4.4 | 18 | 50 | ≤14 | 6 | 1.0 |
| `add` | 13 | 12 | 50 | No | 12 | 6 | 4.4 | 18 | 50 | ≤14 | 6 | 1.0 |
| `clear` | 13 | 12 | 50 | No | 12 | 6 | 4.4 | 18 | 50 | ≤14 | 6 | 1.0 |
| `length` | 13 | 12 | 50 | No | 12 | 6 | 4.4 | 18 | 50 | ≤14 | 6 | 1.0 |
| `remove` | 31 | 12 | 50 | No | 12 | 6 | 4.4.3 | 31 | 50 | ≤14 | 6 | 2.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItemList>

DecompressionStream
===================


The `DecompressionStream` interface of the [Compression Streams API](compression_streams_api) is an API for decompressing a stream of data.


Constructor
-----------


 [`DecompressionStream()`](decompressionstream/decompressionstream)  Creates a new `DecompressionStream`

  
Instance properties
-------------------


 [`DecompressionStream.readable`](decompressionstream/readable)  Returns the [`ReadableStream`](readablestream) instance controlled by this object.

  [`DecompressionStream.writable`](decompressionstream/writable)  Returns the [`WritableStream`](writablestream) instance controlled by this object.

  
Examples
--------



In this example a blob is decompressed using gzip compression.

 
```
const ds = new DecompressionStream("gzip");
const decompressedStream = blob.stream().pipeThrough(ds);

```


Specifications
--------------




| Specification |
| --- |
| [Compression Streams # decompression-stream](https://wicg.github.io/compression/#decompression-stream) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DecompressionStream` | 80 | 80 | No | No | 67 | 16.4 | 80 | 80 | No | 57 | 16.4 | 13.0 |
| `DecompressionStream` | 80 | 80 | No | No | 67 | 16.4 | 80 | 80 | No | 57 | 16.4 | 13.0 |
| `readable` | 80 | 80 | No | No | 67 | 16.4 | 80 | 80 | No | 57 | 16.4 | 13.0 |
| `writable` | 80 | 80 | No | No | 67 | 16.4 | 80 | 80 | No | 57 | 16.4 | 13.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DecompressionStream>

DedicatedWorkerGlobalScope
==========================



The `DedicatedWorkerGlobalScope` object (the [`Worker`](worker) global scope) is accessible through the [`self`](window/self) keyword. Some additional global functions, namespaces objects, and constructors, not typically associated with the worker global scope, but available on it, are listed in the [JavaScript Reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference). See also: [Functions available to workers](web_workers_api/functions_and_classes_available_to_workers).


 EventTarget WorkerGlobalScope DedicatedWorkerGlobalScope

Instance properties
-------------------



*This interface inherits properties from the [`WorkerGlobalScope`](workerglobalscope) interface, and its parent [`EventTarget`](eventtarget).*

  
[`DedicatedWorkerGlobalScope.name`](dedicatedworkerglobalscope/name) Read only 
  The name that the [`Worker`](worker) was (optionally) given when it was created using the [`Worker()`](worker/worker) constructor. This is mainly useful for debugging purposes.

  

### Instance properties inherited from WorkerGlobalScope


 
[`DedicatedWorkerGlobalScope.caches`](caches) Read only 
  Returns the [`CacheStorage`](cachestorage) object associated with the current context. This object enables functionality such as storing assets for offline use, and generating custom responses to requests.

  
[`DedicatedWorkerGlobalScope.console`](workerglobalscope/console) Read only   Non-standard 
  Returns the [`console`](console) associated with the worker.

  
[`DedicatedWorkerGlobalScope.fonts`](workerglobalscope/fonts) Read only 
  Returns the [`FontFaceSet`](fontfaceset) associated with the worker.

  
[`DedicatedWorkerGlobalScope.indexedDB`](indexeddb) Read only 
  Provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an [`IDBFactory`](idbfactory) object.

  
[`DedicatedWorkerGlobalScope.isSecureContext`](issecurecontext) Read only 
  Returns a boolean indicating whether the current context is secure (`true`) or not (`false`).

  
[`DedicatedWorkerGlobalScope.location`](workerglobalscope/location) Read only 
  Returns the [`WorkerLocation`](workerlocation) associated with the worker. `WorkerLocation` is a specific location object, mostly a subset of the [`Location`](location) for browsing scopes, but adapted to workers.

  
[`DedicatedWorkerGlobalScope.navigator`](workerglobalscope/navigator) Read only 
  Returns the [`WorkerNavigator`](workernavigator) associated with the worker. `WorkerNavigator` is a specific navigator object, mostly a subset of the [`Navigator`](navigator) for browsing scopes, but adapted to workers.

  
[`DedicatedWorkerGlobalScope.origin`](origin) Read only 
  Returns the global object's origin, serialized as a string.

  
[`DedicatedWorkerGlobalScope.performance`](performance_property) Read only 
  Returns the [`Performance`](performance) object associated with the worker, which is a regular performance object, but with a subset of its properties and methods available.

  
[`DedicatedWorkerGlobalScope.scheduler`](window/scheduler) Read only 
  Returns the [`Scheduler`](scheduler) object associated with the current context. This is the entry point for using the [Prioritized Task Scheduling API](prioritized_task_scheduling_api).

  [`DedicatedWorkerGlobalScope.self`](workerglobalscope/self)  Returns an object reference to the `DedicatedWorkerGlobalScope` object itself.

  
Instance methods
----------------



*This interface inherits methods from the [`WorkerGlobalScope`](workerglobalscope) interface, and its parent [`EventTarget`](eventtarget).*

  [`DedicatedWorkerGlobalScope.close()`](dedicatedworkerglobalscope/close)  Discards any tasks queued in the `WorkerGlobalScope`'s event loop, effectively closing this particular scope.

  [`DedicatedWorkerGlobalScope.postMessage()`](dedicatedworkerglobalscope/postmessage)  Sends a message — which can consist of `any` JavaScript object — to the parent document that first spawned the worker.

  

### Inherited from WorkerGlobalScope


 [`DedicatedWorkerGlobalScope.atob()`](atob)  Decodes a string of data which has been encoded using base-64 encoding.

  [`DedicatedWorkerGlobalScope.btoa()`](btoa)  Creates a base-64 encoded ASCII string from a string of binary data.

  [`DedicatedWorkerGlobalScope.cancelAnimationFrame()`](window/cancelanimationframe)  Cancels a callback scheduled by requestAnimationFrame.

  [`DedicatedWorkerGlobalScope.clearInterval()`](clearinterval)  Cancels the repeated execution set using [`setInterval`](setinterval).

  [`DedicatedWorkerGlobalScope.clearTimeout()`](cleartimeout)  Cancels the repeated execution set using [`setTimeout`](settimeout).

  
[`DedicatedWorkerGlobalScope.dump()`](workerglobalscope/dump)  Deprecated   Non-standard 
  Writes a message to the console.

  [`DedicatedWorkerGlobalScope.importScripts()`](workerglobalscope/importscripts)  Imports one or more scripts into the worker's scope. You can specify as many as you'd like, separated by commas. For example: `importScripts('foo.js', 'bar.js');`

  [`DedicatedWorkerGlobalScope.requestAnimationFrame()`](window/requestanimationframe)  Requests the browser to execute a callback function before painting the next frame.

  [`DedicatedWorkerGlobalScope.setInterval()`](setinterval)  Schedules the execution of a function every X milliseconds.

  [`DedicatedWorkerGlobalScope.setTimeout()`](settimeout)  Sets a delay for executing a function.

  
Events
------


 [`message`](dedicatedworkerglobalscope/message_event)  Fired when the worker receives a message from its parent.

  [`messageerror`](dedicatedworkerglobalscope/messageerror_event)  Fired when a worker receives a message that can't be deserialized.

  
Specifications
--------------




| Specification |
| --- |
| [HTML Standard # dedicated-workers-and-the-dedicatedworkerglobalscope-interface](https://html.spec.whatwg.org/multipage/workers.html#dedicated-workers-and-the-dedicatedworkerglobalscope-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DedicatedWorkerGlobalScope` | 4 | 12 | 3.5 | 10 | 10.6 | 4 | 4.4 | 18 | 4 | 11 | 5 | 1.0 |
| `cancelAnimationFrame` | 69 | 79 | 99 | No | 56 | 16.4 | 67 | 69 | 99 | 48 | 16.4 | 10.0 |
| `close` | 4 | 12 | 3.5 | 10 | 10.6 | 4 | 4.4 | 18 | 4 | 11 | 5 | 1.0 |
| `message_event` | 4 | 12 | 3.5 | 10 | 10.6 | 4 | ≤37 | 18 | 4 | 11.5 | 5 | 1.0 |
| `messageerror_event` | 60 | 18 | 57 | No | 47 | 16.4See [bug 171216](https://webkit.org/b/171216). | 60 | 60 | 57 | 47 | 16.4See [bug 171216](https://webkit.org/b/171216). | 8.0 |
| `name` | 70 | 18 | 55 | No | 57 | 12.1 | 70 | 70 | 55 | 49 | 12.2 | 10.0 |
| `postMessage` | 4 | 12 | 3.5 | 10 | 10.6 | 4 | 4.4 | 18 | 4 | 11 | 5 | 1.0 |
| `requestAnimationFrame` | 69 | 79 | 99 | No | 56 | 16.4 | 67 | 69 | 99 | 48 | 16.4 | 10.0 |
| `rtctransform_event` | No | No | No | No | No | 15.4 | No | No | No | No | 15.4 | No |


See also
--------


* [`Worker`](worker)
* [`WorkerGlobalScope`](workerglobalscope)
* [Using web workers](web_workers_api/using_web_workers)
* [Functions available to workers](web_workers_api/functions_and_classes_available_to_workers)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DedicatedWorkerGlobalScope>

DelayNode
=========



The `DelayNode` interface represents a [delay-line](https://en.wikipedia.org/wiki/Digital_delay_line); an [`AudioNode`](audionode) audio-processing module that causes a delay between the arrival of an input data and its propagation to the output.

 A `DelayNode` always has exactly one input and one output, both with the same amount of channels.

  ![The DelayNode acts as a delay-line, here with a value of 1s.] 

 When creating a graph that has a cycle, it is mandatory to have at least one `DelayNode` in the cycle, or the nodes taking part in the cycle will be muted.


 EventTarget AudioNode DelayNode 

|  |  |
| --- | --- |
| Number of inputs | `1` |
| Number of outputs | `1` |
| Channel count mode | `"max"` |
| Channel count | `2` (not used in the default count mode) |
| Channel interpretation | `"speakers"` |



Constructor
-----------


 [`DelayNode()`](delaynode/delaynode)  Creates a new instance of an DelayNode object instance. As an alternative, you can use the [`BaseAudioContext.createDelay()`](baseaudiocontext/createdelay) factory method; see [Creating an AudioNode](audionode#creating_an_audionode).

  
Instance properties
-------------------



*Inherits properties from its parent, [`AudioNode`](audionode).*

  
[`DelayNode.delayTime`](delaynode/delaytime) Read only 
  An [a-rate](audioparam#a-rate) [`AudioParam`](audioparam) representing the amount of delay to apply, specified in seconds.

  

Instance methods
----------------


*No specific methods; inherits methods from its parent, [`AudioNode`](audionode).*


Example
-------


See [`BaseAudioContext.createDelay()`](baseaudiocontext/createdelay#examples) for example code.


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # DelayNode](https://webaudio.github.io/web-audio-api/#DelayNode) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DelayNode` | 55 | 79 | 53 | No | 42 | 14.1 | 55 | 55 | 53 | 42 | 14.5 | 6.0 |
| `DelayNode` | 24 | 12 | 25 | No | 15 | 7 | ≤37 | 25 | 25 | 14 | 7 | 1.5 |
| `delayTime` | 24 | 12 | 25 | No | 15 | 7 | ≤37 | 25 | 25 | 14 | 7 | 1.5 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DelayNode>

DeprecationReportBody
=====================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `DeprecationReportBody` interface of the [Reporting API](reporting_api) represents the body of a deprecation report.

 A deprecation report is generated when a deprecated feature (for example a deprecated API method) is used on a document being observed by a [`ReportingObserver`](reportingobserver). In addition to the support of this API, receiving useful deprecation warnings relies on browser vendors adding these warnings for deprecated features.


 ReportBody DeprecationReportBody

Constructor
-----------


An instance of `DeprecationReportBody` is returned as the value of [`Report.body`](report/body) when [`Report.Type`](report/type) is `deprecation`. The interface has no constructor.


Instance properties
-------------------



This interface also inherits properties from [`ReportBody`](reportbody).

  
[`DeprecationReportBody.id`](deprecationreportbody/id)  Experimental 
  A string representing the feature or API that is deprecated, for example `NavigatorGetUserMedia`. This can be used to group reports by deprecated feature.

  
[`DeprecationReportBody.anticipatedRemoval`](deprecationreportbody/anticipatedremoval)  Experimental 
  A [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) object (rendered as a string) representing the date when the feature is expected to be removed from the current browser. If the date is not known, this property will return `null`.

  
[`DeprecationReportBody.message`](deprecationreportbody/message)  Experimental 
  A string containing a human-readable description of the deprecation, including information such as what newer feature has superseded it, if any. This typically matches the message a browser will display in its DevTools console when a deprecated feature is used, if one is available.

  
[`DeprecationReportBody.sourceFile`](deprecationreportbody/sourcefile)  Experimental 
  A string containing the path to the source file where the deprecated feature was used, if known, or `null` otherwise.

  
[`DeprecationReportBody.lineNumber`](deprecationreportbody/linenumber)  Experimental 
  A number representing the line in the source file in which the deprecated feature was used, if known, or `null` otherwise.

  
[`DeprecationReportBody.columnNumber`](deprecationreportbody/columnnumber)  Experimental 
  A number representing the column in the source file in which the deprecated feature was used, if known, or `null` otherwise.

  

Instance methods
----------------



This interface also inherits methods from [`ReportBody`](reportbody).

  
[`DeprecationReportBody.toJSON()`](deprecationreportbody/tojson)  Experimental 
  A *serializer* which returns a JSON representation of the `InterventionReportBody` object.

  

Examples
--------



In our [deprecation\_report.html](https://mdn.github.io/dom-examples/reporting-api/deprecation_report.html) example, we create a simple reporting observer to observe usage of deprecated features on our web page:

 
```
const options = {
  types: ["deprecation"],
  buffered: true,
};

const observer = new ReportingObserver((reports, observer) => {
  reportBtn.onclick = () => displayReports(reports);
}, options);

```
 We then tell it to start observing reports using [`ReportingObserver.observe()`](reportingobserver/observe); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor:

 
```
observer.observe();

```
 Because of the event handler we set up inside the `ReportingObserver()` constructor, we can now click the button to display the report details.

  ![image of a jolly bearded man with various stats displayed below it about a deprecated feature] 

 The report details are displayed via the `displayReports()` function, which takes the observer callback's `reports` parameter as its parameter:

 
```
function displayReports(reports) {
  const outputElem = document.querySelector(".output");
  const list = document.createElement("ul");
  outputElem.appendChild(list);

  reports.forEach((report, i) => {
    const listItem = document.createElement("li");
    const textNode = document.createTextNode(
      `Report ${i + 1}, type: ${report.type}`
    );
    listItem.appendChild(textNode);
    const innerList = document.createElement("ul");
    listItem.appendChild(innerList);
    list.appendChild(listItem);

    for (const [key, value] of Object.entries(report.body)) {
      const innerListItem = document.createElement("li");
      innerListItem.textContent = `${key}: ${value}`;
      innerList.appendChild(innerListItem);
    }
  });
}

```
 The `reports` parameter contains an array of all the reports in the observer's report queue. We loop over each report using a basic [`for`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) loop, then iterate over each entry of in the report's body (a `DeprecationReportBody` instance) using a [`for...in`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) structure, displaying each key/value pair inside a list item.



Specifications
--------------




| Specification |
| --- |
| [Deprecation Reporting # deprecationreportbody](https://wicg.github.io/deprecation-reporting/#deprecationreportbody) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DeprecationReportBody` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `anticipatedRemoval` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `columnNumber` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `id` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `lineNumber` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `message` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `sourceFile` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `toJSON` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |


See also
--------


* [Reporting API](reporting_api)
* [The Reporting API](https://web.dev/reporting-api/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DeprecationReportBody>

DeviceMotionEventRotationRate
=============================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 A `DeviceMotionEventRotationRate` object provides information about the rate at which the device is rotating around all three axes.



Instance properties
-------------------


 
[`DeviceMotionEventRotationRate.alpha`](devicemotioneventrotationrate/alpha) Read only 
  The amount of rotation around the Z axis, in degrees per second.

  
[`DeviceMotionEventRotationRate.beta`](devicemotioneventrotationrate/beta) Read only 
  The amount of rotation around the X axis, in degrees per second.

  
[`DeviceMotionEventRotationRate.gamma`](devicemotioneventrotationrate/gamma) Read only 
  The amount of rotation around the Y axis, in degrees per second.

  
Specifications
--------------




| Specification |
| --- |
| [DeviceOrientation Event Specification # devicemotioneventrotationrate](https://w3c.github.io/deviceorientation/#devicemotioneventrotationrate) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DeviceMotionEventRotationRate` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |
| `alpha` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |
| `beta` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |
| `gamma` | 31 | 12 | 6 | 11 | 18 | No | 4.4.3 | 31 | 6 | 18 | 4.2 | 2.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEventRotationRate>

DeviceOrientationEvent
======================



The `DeviceOrientationEvent` object provides web developers with information from the physical orientation of the device running the web page.


 Event DeviceOrientationEvent

Constructor
-----------


 [`DeviceOrientationEvent.DeviceOrientationEvent()`](deviceorientationevent/deviceorientationevent)  Creates a new `DeviceOrientationEvent`.

  
Instance properties
-------------------


 
[`DeviceOrientationEvent.absolute`](deviceorientationevent/absolute) Read only 
  A boolean that indicates whether or not the device is providing orientation data absolutely.

  
[`DeviceOrientationEvent.alpha`](deviceorientationevent/alpha) Read only 
  A number representing the motion of the device around the z axis, express in degrees with values ranging from 0 (inclusive) to 360 (exclusive).

  
[`DeviceOrientationEvent.beta`](deviceorientationevent/beta) Read only 
  A number representing the motion of the device around the x axis, express in degrees with values ranging from -180 (inclusive) to 180 (exclusive). This represents a front to back motion of the device.

  
[`DeviceOrientationEvent.gamma`](deviceorientationevent/gamma) Read only 
  A number representing the motion of the device around the y axis, express in degrees with values ranging from -90 (inclusive) to 90 (exclusive). This represents a left to right motion of the device.

  
`DeviceOrientationEvent.webkitCompassHeading`  Non-standard  Read only 
  A number represents the difference between the motion of the device around the z axis of the world system and the direction of the north, express in degrees with values ranging from 0 to 360.

  
`DeviceOrientationEvent.webkitCompassAccuracy`  Non-standard  Read only 
  The accuracy of the compass means that the deviation is positive or negative. It's usually 10.

  
Example
-------



```
window.addEventListener("deviceorientation", (event) => {
  console.log(`${event.alpha} : ${event.beta} : ${event.gamma}`);
});

```

Specifications
--------------




| Specification |
| --- |
| [DeviceOrientation Event Specification # deviceorientation](https://w3c.github.io/deviceorientation/#deviceorientation) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DeviceOrientationEvent` | 59 | 14 | 17 | No | 46 | No | 59 | 59 | 17 | 43 | No | 7.0 |
| `DeviceOrientationEvent` | 7Before version 50, Chrome provided absolute values instead of relative values for this event. Developers still needing absolute values may use the `deviceorientationabsolute` event. | 12 | 6Firefox 3.6, 4, and 5 supported `mozOrientation` instead of the standard DeviceOrientationEvent interface. | 11 | 15 | No | 3Before version 50, Chrome provided absolute values instead of relative values for this event. Developers still needing absolute values may use the `deviceorientationabsolute` event. | 18Before version 50, Chrome provided absolute values instead of relative values for this event. Developers still needing absolute values may use the `deviceorientationabsolute` event. | 6Firefox 3.6, 4, and 5 supported `mozOrientation` instead of the standard DeviceOrientationEvent interface. | 14 | 4.2 | 1.0Before Samsung Internet 5.0, Samsung Internet provided absolute values instead of relative values for this event. Developers still needing absolute values may use the `deviceorientationabsolute` event. |
| `absolute` | 7 | 12 | 6 | 11 | 15 | No | 4.4 | 18 | 6 | 14 | No | 1.0 |
| `alpha` | 7 | 12 | 6 | 11 | 15 | No | 3 | 18 | 6 | 14 | 4.2 | 1.0 |
| `beta` | 7 | 12 | 6 | 11 | 15 | No | 3 | 18 | 6 | 14 | 4.2 | 1.0 |
| `gamma` | 7 | 12 | 6 | 11 | 15 | No | 3 | 18 | 6 | 14 | 4.2 | 1.0 |
| `requestPermission` | No | No | No | No | No | No | No | No | No | No | 14.5 | No |


See also
--------


* [`deviceorientation`](window/deviceorientation_event)
* [`DeviceMotionEvent`](devicemotionevent)
* [`devicemotion`](window/devicemotion_event)
* [Detecting device orientation](device_orientation_events/detecting_device_orientation)
* [Orientation and motion data explained](device_orientation_events/orientation_and_motion_data_explained)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent>

DeviceProximityEvent
====================



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.


**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

  **Warning:** `DeviceProximityEvent` is not supported by any current major browser, and should not be used.

  The `DeviceProximityEvent` interface provides information about the distance of a nearby physical object using the proximity sensor of a device.



Instance properties
-------------------


 
`DeviceProximityEvent.max` Read only   Deprecated   Non-standard 
  The maximum sensing distance the sensor is able to report, in centimeters.

  
`DeviceProximityEvent.min` Read only   Deprecated   Non-standard 
  The minimum sensing distance the sensor is able to report, in centimeters. Usually zero.

  
`DeviceProximityEvent.value` Read only   Deprecated   Non-standard 
  The current device proximity, in centimeters.

  
Examples
--------



```
window.addEventListener("deviceproximity", (event) => {
  console.log(
    `value: ${event.value}`,
    `max: ${event.max}`,
    `min: ${event.min}`
  );
});

```

Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DeviceProximityEvent` | No | No | 62–8915–61 | No | No | No | No | No | 15–61 | No | No | No |
| `max` | No | No | 62–8915–61 | No | No | No | No | No | 15–61 | No | No | No |
| `min` | No | No | 62–8915–61 | No | No | No | No | No | 15–61 | No | No | No |
| `value` | No | No | 62–8915–61 | No | No | No | No | No | 15–61 | No | No | No |


See also
--------


* [`UserProximityEvent`](userproximityevent)
* [Proximity API](proximity_events)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DeviceProximityEvent>

DocumentFragment
================



The `DocumentFragment` interface represents a minimal document object that has no parent.

 It is used as a lightweight version of [`Document`](document) that stores a segment of a document structure comprised of nodes just like a standard document. The key difference is due to the fact that the document fragment isn't part of the active document tree structure. Changes made to the fragment don't affect the document.


 EventTarget Node DocumentFragment

Constructor
-----------


 [`DocumentFragment()`](documentfragment/documentfragment)  Creates and returns a new `DocumentFragment` object.

  
Instance properties
-------------------



*This interface has no specific properties, but inherits those of its parent, [`Node`](node).*

  
[`DocumentFragment.childElementCount`](documentfragment/childelementcount) Read only 
  Returns the amount of child [`elements`](element) the `DocumentFragment` has.

  
[`DocumentFragment.children`](documentfragment/children) Read only 
  Returns a live [`HTMLCollection`](htmlcollection) containing all objects of type [`Element`](element) that are children of the `DocumentFragment` object.

  
[`DocumentFragment.firstElementChild`](documentfragment/firstelementchild) Read only 
  Returns the [`Element`](element) that is the first child of the `DocumentFragment` object, or `null` if there is none.

  
[`DocumentFragment.lastElementChild`](documentfragment/lastelementchild) Read only 
  Returns the [`Element`](element) that is the last child of the `DocumentFragment` object, or `null` if there is none.

  

Instance methods
----------------



*This interface inherits the methods of its parent, [`Node`](node).*

  [`DocumentFragment.append()`](documentfragment/append)  Inserts a set of [`Node`](node) objects or string objects after the last child of the document fragment.

  [`DocumentFragment.prepend()`](documentfragment/prepend)  Inserts a set of [`Node`](node) objects or string objects before the first child of the document fragment.

  [`DocumentFragment.querySelector()`](documentfragment/queryselector)  Returns the first [`Element`](element) node within the `DocumentFragment`, in document order, that matches the specified selectors.

  [`DocumentFragment.querySelectorAll()`](documentfragment/queryselectorall)  Returns a [`NodeList`](nodelist) of all the [`Element`](element) nodes within the `DocumentFragment` that match the specified selectors.

  [`DocumentFragment.replaceChildren()`](documentfragment/replacechildren)  Replaces the existing children of a `DocumentFragment` with a specified new set of children.

  [`DocumentFragment.getElementById()`](documentfragment/getelementbyid)  Returns the first [`Element`](element) node within the `DocumentFragment`, in document order, that matches the specified ID. Functionally equivalent to [`Document.getElementById()`](document/getelementbyid).

  

Usage notes
-----------



A common use for `DocumentFragment` is to create one, assemble a DOM subtree within it, then append or insert the fragment into the DOM using [`Node`](node) interface methods such as [`appendChild()`](node/appendchild), [`append()`](element/append), or [`insertBefore()`](node/insertbefore). Doing this moves the fragment's nodes into the DOM, leaving behind an empty `DocumentFragment`.

 This interface is also of great use with Web components: [`<template>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template) elements contain a `DocumentFragment` in their [`HTMLTemplateElement.content`](htmltemplateelement/content) property.

 An empty `DocumentFragment` can be created using the [`document.createDocumentFragment()`](document/createdocumentfragment) method or the constructor.



Performance
-----------


The performance benefit of `DocumentFragment` is often overstated. In fact, in some engines, using a `DocumentFragment` is slower than appending to the document in a loop as demonstrated in [this benchmark](https://jsbench.me/02l63eic9j/1). However, the difference between these examples is so marginal that it's better to optimize for readability than performance.


Example
-------


### HTML



```
<ul></ul>

```

### JavaScript



```
const ul = document.querySelector("ul");
const fruits = ["Apple", "Orange", "Banana", "Melon"];

const fragment = new DocumentFragment();

for (const fruit of fruits) {
  const li = document.createElement("li");
  li.textContent = fruit;
  fragment.append(li);
}

ul.append(fragment);

```

### Result



Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-documentfragment](https://dom.spec.whatwg.org/#interface-documentfragment) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DocumentFragment` | 29 | 17 | 24 | No | 16 | 8 | 4.4 | 29 | 24 | 16 | 8 | 2.0 |
| `DocumentFragment` | 1 | 12 | 1 | 6 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `append` | 54 | 17 | 49 | No | 41 | 10 | 54 | 54 | 49 | 41 | 10 | 6.0 |
| `childElementCount` | 29 | 17 | 25 | No | 16 | 9 | 4.4 | 29 | 25 | 16 | 9 | 2.0 |
| `children` | 29 | 16 | 25 | No | 16 | 9 | 4.4 | 29 | 25 | 16 | 9 | 2.0 |
| `firstElementChild` | 29 | 17 | 25 | No | 16 | 9 | 4.4 | 29 | 25 | 16 | 9 | 2.0 |
| `getElementById` | 36 | 17 | 28 | No | 23 | 9 | 37 | 36 | 28 | 24 | 9 | 3.0 |
| `lastElementChild` | 29 | 17 | 25 | No | 16 | 9 | 4.4 | 29 | 25 | 16 | 9 | 2.0 |
| `prepend` | 54 | 17 | 49 | No | 41 | 10 | 54 | 54 | 49 | 41 | 10 | 6.0 |
| `querySelector` | 2 | 12 | 3.5 | 98`querySelectorAll()` is supported, but only for CSS 2.1 selectors. | 10 | 4 | ≤37 | 18 | 4 | 10.1 | 3 | 1.0 |
| `querySelectorAll` | 2 | 12 | 3.5 | 98`querySelectorAll()` is supported, but only for CSS 2.1 selectors. | 10 | 4 | ≤37 | 18 | 4 | 10.1 | 3 | 1.0 |
| `replaceChildren` | 86 | 86 | 78 | No | 72 | 14 | 86 | 86 | 79 | 61 | 14 | 14.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment>

DocumentTimeline
================



The `DocumentTimeline` interface of the [Web Animations API](web_animations_api) represents animation timelines, including the default document timeline (accessed via [`Document.timeline`](document/timeline)).


 AnimationTimeline DocumentTimeline

Constructor
-----------


 [`DocumentTimeline()`](documenttimeline/documenttimeline)  Creates a new `DocumentTimeline` object associated with the active document of the current browsing context.

  
Instance properties
-------------------



*This interface inherits its property from its parent, [`AnimationTimeline`](animationtimeline).*

  [`AnimationTimeline.currentTime`](animationtimeline/currenttime)  Returns the time value in milliseconds for this timeline or `null` if it is inactive.

  

Specifications
--------------




| Specification |
| --- |
| [Web Animations # the-documenttimeline-interface](https://w3c.github.io/csswg-drafts/web-animations-1/#the-documenttimeline-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DocumentTimeline` | 84 | 84 | 75 | No | 70 | 13.1 | 84 | 84 | 79 | 60 | 13.4 | 14.0 |
| `DocumentTimeline` | 84 | 84 | 75 | No | 70 | 13.1 | 84 | 84 | 79 | 60 | 13.4 | 14.0 |


See also
--------


* [Web Animations API](web_animations_api)
* [`AnimationTimeline`](animationtimeline)
* [`AnimationTimeline.currentTime`](animationtimeline/currenttime)
* [`Document.timeline`](document/timeline)
* [`DocumentTimeline()`](documenttimeline/documenttimeline)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DocumentTimeline>

DocumentType
============



The `DocumentType` interface represents a [`Node`](node) containing a doctype.


 EventTarget Node DocumentType

Instance properties
-------------------



*Inherits properties from its parent, [`Node`](node).*

  
[`DocumentType.name`](documenttype/name) Read only 
  The type of the document. It is always `"html"` for HTML documents, but will vary for XML documents.

  
[`DocumentType.publicId`](documenttype/publicid) Read only 
  A string with an identifier of the type of document. Always empty (`""`) for HTML, it will be, for example, `"-//W3C//DTD SVG 1.1//EN"` for SVG documents.

  
[`DocumentType.systemId`](documenttype/systemid) Read only 
  A string containing the URL to the associated DTD. Always empty (`""`) for HTML, it will be, for example, `"http://www.w3.org/2000/svg"` for SVG documents.

  

Instance methods
----------------



*Inherits methods from its parent, [`Node`](node).*

  [`DocumentType.after()`](documenttype/after)   Inserts a set of [`Node`](node) or string objects in the children list of the object's parent, just before this node. 

  [`DocumentType.before()`](documenttype/before)   Inserts a set of [`Node`](node) or string objects in the children list of the object's parent, just before this node. 

  [`DocumentType.remove()`](documenttype/remove)  Removes this object from its parent children list.

  [`DocumentType.replaceWith()`](documenttype/replacewith)  Replaces the document type with a set of given nodes.

  

Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-documenttype](https://dom.spec.whatwg.org/#interface-documenttype) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DocumentType` | 1 | 12 | 1 | 9 | ≤12.1 | 3 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `after` | 54 | 17 | 49 | No | 39 | 10 | 54 | 54 | 49 | 41 | 10 | 6.0 |
| `before` | 54 | 17 | 49 | No | 39 | 10 | 54 | 54 | 49 | 41 | 10 | 6.0 |
| `name` | 1 | 12 | 1 | 9 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `publicId` | 1 | 12 | 1 | 9 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `remove` | 24 | 12 | 23 | No | 15 | 7 | 4.4 | 25 | 23 | 14 | 7 | 1.5 |
| `replaceWith` | 54 | 17 | 49 | No | 39 | 10 | 54 | 54 | 49 | 41 | 10 | 6.0 |
| `systemId` | 1 | 12 | 1 | 9 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* [The DOM interfaces index.](document_object_model)
* [`DOMImplementation.createDocumentType()`](domimplementation/createdocumenttype) to create a new `DocumentType` node.


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DocumentType>

DOMError
========



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The `DOMError` interface describes an error object that contains an error name.



Instance properties
-------------------


 
`DOMError.name` Read only   Deprecated 
  Returns a string representing one of the error type names (see below).

  
`DOMError.message` Read only   Deprecated 
  Returns a string representing a message or description associated with the given error type name.

  
Error types
-----------




| Type | Description |
| --- | --- |
| `IndexSizeError` | The index is not in the allowed range (e.g. thrown in a [`range`](range) object). |
| `HierarchyRequestError` | The node tree hierarchy is not correct. |
| `WrongDocumentError` | The object is in the wrong [`document`](document). |
| `InvalidCharacterError` | The string contains invalid characters. |
| `NoModificationAllowedError` | The object can not be modified. |
| `NotFoundError` | The object can not be found here. |
| `NotSupportedError` | The operation is not supported |
| `InvalidStateError` | The object is in an invalid state. |
| `SyntaxError` | The string did not match the expected pattern. |
| `InvalidModificationError` | The object can not be modified in this way. |
| `NamespaceError` | The operation is not allowed by Namespaces in XML |
| `InvalidAccessError` | The object does not support the operation or argument. |
| `TypeMismatchError` | The type of the object does not match the expected type. |
| `SecurityError` | The operation is insecure. |
| `NetworkError` | A network error occurred. |
| `AbortError` | The operation was aborted. |
| `URLMismatchError` | The given URL does not match another URL. |
| `QuotaExceededError` | The quota has been exceeded. |
| `TimeoutError` | The operation timed out. |
| `InvalidNodeTypeError` | The node is incorrect or has an incorrect ancestor for this operation. |
| `DataCloneError` | The object can not be cloned. |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DOMError` | 36 | 12 | 12–69 | 10 | 23≤12.1–15 | No | 37 | 36 | 14–79 | 24≤12.1–14 | No | 3.0 |
| `message` | 36 | 12 | 12–69 | 10 | 23 | No | 37 | 36 | 14–79 | 24 | No | 3.0 |
| `name` | 36 | 12 | 12–69 | 10 | 23 | No | 37 | 36 | 14–79 | 24 | No | 3.0 |


See also
--------


* [`DOMException`](domexception)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DOMError>

DOMException
============



The `DOMException` interface represents an abnormal event (called an **exception**) that occurs as a result of calling a method or accessing a property of a web API. This is how error conditions are described in web APIs.

 Each exception has a **name**, which is a short "PascalCase"-style string identifying the error or abnormal condition.

 `DOMException` is a [Serializable object](https://developer.mozilla.org/en-US/docs/Glossary/Serializable_object), so it can be cloned with [`structuredClone()`](structuredclone) or copied between [Workers](worker) using [`postMessage()`](worker/postmessage).



Constructor
-----------


 [`DOMException()`](domexception/domexception)  Returns a `DOMException` object with a specified message and name.

  
Instance properties
-------------------


 
[`DOMException.code`](domexception/code)  Deprecated  Read only 
  Returns one of the legacy error code constants, or `0` if none match.

  
[`DOMException.message`](domexception/message) Read only 
  Returns a string representing a message or description associated with the given [error name](#error_names).

  
[`DOMException.name`](domexception/name) Read only 
  Returns a string that contains one of the strings associated with an [error name](#error_names).

  
Error names
-----------



Common error names are listed here. Some APIs define their own sets of names, so this is not necessarily a complete list.

 Note that the following deprecated historical errors don't have an error name but instead have only a legacy constant code value and a legacy constant name:

 * Legacy code value: `2`, legacy constant name: `DOMSTRING_SIZE_ERR`
* Legacy code value: `6`, legacy constant name: `NO_DATA_ALLOWED_ERR`
* Legacy code value: `16`, legacy constant name: `VALIDATION_ERR`

  **Note:** Because historically the errors were identified by a numeric value that corresponded with a named variable defined to have that value, some of the entries below indicate the legacy code value and constant name that were used in the past.

   `IndexSizeError`  The index is not in the allowed range. For example, this can be thrown by the [`Range`](range) object. (Legacy code value: `1` and legacy constant name: `INDEX_SIZE_ERR`)

  `HierarchyRequestError`  The node tree hierarchy is not correct. (Legacy code value: `3` and legacy constant name: `HIERARCHY_REQUEST_ERR`)

  `WrongDocumentError`  The object is in the wrong [`Document`](document). (Legacy code value: `4` and legacy constant name: `WRONG_DOCUMENT_ERR`)

  `InvalidCharacterError`  The string contains invalid characters. (Legacy code value: `5` and legacy constant name: `INVALID_CHARACTER_ERR`)

  `NoModificationAllowedError`  The object cannot be modified. (Legacy code value: `7` and legacy constant name: `NO_MODIFICATION_ALLOWED_ERR`)

  `NotFoundError`  The object cannot be found here. (Legacy code value: `8` and legacy constant name: `NOT_FOUND_ERR`)

  `NotSupportedError`  The operation is not supported. (Legacy code value: `9` and legacy constant name: `NOT_SUPPORTED_ERR`)

  `InvalidStateError`  The object is in an invalid state. (Legacy code value: `11` and legacy constant name: `INVALID_STATE_ERR`)

  `InUseAttributeError`  The attribute is in use. (Legacy code value: `10` and legacy constant name: `INUSE_ATTRIBUTE_ERR`)

  `SyntaxError`  The string did not match the expected pattern. (Legacy code value: `12` and legacy constant name: `SYNTAX_ERR`)

  `InvalidModificationError`  The object cannot be modified in this way. (Legacy code value: `13` and legacy constant name: `INVALID_MODIFICATION_ERR`)

  `NamespaceError`  The operation is not allowed by Namespaces in XML. (Legacy code value: `14` and legacy constant name: `NAMESPACE_ERR`)

  `InvalidAccessError`  The object does not support the operation or argument. (Legacy code value: `15` and legacy constant name: `INVALID_ACCESS_ERR`)

  
`TypeMismatchError`  Deprecated 
  The type of the object does not match the expected type. (Legacy code value: `17` and legacy constant name: `TYPE_MISMATCH_ERR`) This value is deprecated; the JavaScript [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) exception is now raised instead of a `DOMException` with this value.

  `SecurityError`  The operation is insecure. (Legacy code value: `18` and legacy constant name: `SECURITY_ERR`)

  
`NetworkError`  Experimental 
  A network error occurred. (Legacy code value: `19` and legacy constant name: `NETWORK_ERR`)

  
`AbortError`  Experimental 
  The operation was aborted. (Legacy code value: `20` and legacy constant name: `ABORT_ERR`)

  
`URLMismatchError`  Experimental 
  The given URL does not match another URL. (Legacy code value: `21` and legacy constant name: `URL_MISMATCH_ERR`)

  
`QuotaExceededError`  Experimental 
  The quota has been exceeded. (Legacy code value: `22` and legacy constant name: `QUOTA_EXCEEDED_ERR`)

  `TimeoutError`  The operation timed out. (Legacy code value: `23` and legacy constant name: `TIMEOUT_ERR`)

  
`InvalidNodeTypeError`  Experimental 
  The node is incorrect or has an incorrect ancestor for this operation. (Legacy code value: `24` and legacy constant name: `INVALID_NODE_TYPE_ERR`)

  
`DataCloneError`  Experimental 
  The object can not be cloned. (Legacy code value: `25` and legacy constant name: `DATA_CLONE_ERR`)

  
`EncodingError`  Experimental 
  The encoding or decoding operation failed (No legacy code value and constant name).

  
`NotReadableError`  Experimental 
  The input/output read operation failed (No legacy code value and constant name).

  
`UnknownError`  Experimental 
  The operation failed for an unknown transient reason (e.g. out of memory) (No legacy code value and constant name).

  
`ConstraintError`  Experimental 
  A mutation operation in a transaction failed because a constraint was not satisfied (No legacy code value and constant name).

  
`DataError`  Experimental 
  Provided data is inadequate (No legacy code value and constant name).

  
`TransactionInactiveError`  Experimental 
  A request was placed against a transaction that is currently not active or is finished (No legacy code value and constant name).

  
`ReadOnlyError`  Experimental 
  The mutating operation was attempted in a "readonly" transaction (No legacy code value and constant name).

  
`VersionError`  Experimental 
  An attempt was made to open a database using a lower version than the existing version (No legacy code value and constant name).

  
`OperationError`  Experimental 
  The operation failed for an operation-specific reason (No legacy code value and constant name).

  `NotAllowedError`  The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission (No legacy code value and constant name).

  

Specifications
--------------




| Specification |
| --- |
| [Web IDL Standard # idl-DOMException](https://webidl.spec.whatwg.org/#idl-DOMException) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DOMException` | 46 | 79 | 37 | No | 33 | 10.1 | 46 | 46 | 37 | 33 | 10.3 | 5.0 |
| `DOMException` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `code` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `message` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `name` | 1 | 12 | 1 | 10 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `serializable_object` | 77 | 79 | 101 | No | 64 | No | 77 | 77 | 101 | 55 | No | 12.0 |


See also
--------


* [A polyfill of `DOMException`](https://github.com/zloirock/core-js#domexception) is available in [`core-js`](https://github.com/zloirock/core-js)
* [`DOMError`](domerror)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DOMException>

DOMHighResTimeStamp
===================



The `DOMHighResTimeStamp` type is a `double` and is used to store a time value in milliseconds.

 This type can be used to describe a discrete point in time or a time interval (the difference in time between two discrete points in time). The starting time can be either a specific time determined by the script for a site or app, or the [time origin](performance/timeorigin).

 The time, given in milliseconds, should be accurate to 5 µs (microseconds), with the fractional part of the number indicating fractions of a millisecond. However, if the browser is unable to provide a time value accurate to 5 µs (due, for example, to hardware or software constraints), the browser can represent the value as a time in milliseconds accurate to a millisecond. Also note the section below on reduced time precision controlled by browser preferences to avoid timing attacks and [fingerprinting](https://developer.mozilla.org/en-US/docs/Glossary/Fingerprinting).

 Further, if the device or operating system the user agent is running on doesn't have a clock accurate to the microsecond level, they may only be accurate to the millisecond.



Security requirements
---------------------



To offer protection against timing attacks and [fingerprinting](https://developer.mozilla.org/en-US/docs/Glossary/Fingerprinting), `DOMHighResTimeStamp` types are coarsened based on site isolation status.

 * Resolution in isolated contexts: 5 microseconds
* Resolution in non-isolated contexts: 100 microseconds

  Cross-origin isolate your site using the [`Cross-Origin-Opener-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy) and [`Cross-Origin-Embedder-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy) headers: 

 
```
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp

```
  These headers ensure a top-level document does not share a browsing context group with cross-origin documents. COOP process-isolates your document and potential attackers can't access to your global object if they were opening it in a popup, preventing a set of cross-origin attacks dubbed [XS-Leaks](https://github.com/xsleaks/xsleaks). 



See also
--------


* [`performance.now()`](performance/now)
* [`performance.timeOrigin`](performance/timeorigin)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp>

DOMImplementation
=================


The `DOMImplementation` interface represents an object providing methods which are not dependent on any particular document. Such an object is returned by the [`Document.implementation`](document/implementation) property.


Property
--------


*This interface has no specific property and doesn't inherit any.*


Instance methods
----------------



*No inherited method.*

  [`DOMImplementation.createDocument()`](domimplementation/createdocument)  Creates and returns an [`XMLDocument`](xmldocument).

  [`DOMImplementation.createDocumentType()`](domimplementation/createdocumenttype)  Creates and returns a [`DocumentType`](documenttype).

  [`DOMImplementation.createHTMLDocument()`](domimplementation/createhtmldocument)  Creates and returns an HTML [`Document`](document).

  
[`DOMImplementation.hasFeature()`](domimplementation/hasfeature)  Deprecated 
  Returns a boolean value indicating if a given feature is supported or not. This function is unreliable and kept for compatibility purpose alone: except for SVG-related queries, it always returns `true`. Old browsers are very inconsistent in their behavior.

  

Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-domimplementation](https://dom.spec.whatwg.org/#interface-domimplementation) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DOMImplementation` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `createDocument` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `createDocumentType` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `createHTMLDocument` | 1 | 12 | 4 | 9The `title` parameter is required, but can be empty string. | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `hasFeature` | 1 | 12 | 1Since Firefox 19, `hasFeature()` mostly returns `true`. | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* [The DOM interfaces index.](document_object_model)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation>

DOMMatrix (WebKitCSSMatrix)
===========================



The `DOMMatrix` interface represents 4×4 matrices, suitable for 2D and 3D operations including rotation and translation. It is a mutable version of the [`DOMMatrixReadOnly`](dommatrixreadonly) interface.

 `WebKitCSSMatrix` and `SVGMatrix` are aliases to `DOMMatrix`.

 This interface should be available inside [web workers](web_workers_api), though some implementations don't allow it yet.


 DOMMatrixReadOnly DOMMatrix

Constructor
-----------


 [`DOMMatrix()`](dommatrix/dommatrix)  Creates and returns a new `DOMMatrix` object.

  
Instance properties
-------------------



*This interface inherits properties from [`DOMMatrixReadOnly`](dommatrixreadonly), though some of these properties are altered to be mutable.*

  
`is2D` Read only 
  A Boolean flag whose value is `true` if the matrix was initialized as a 2D matrix. If `false`, the matrix is 3D.

  
`isIdentity` Read only 
  A Boolean whose value is `true` if the matrix is the [identity matrix](https://en.wikipedia.org/wiki/Identity_matrix). The identity matrix is one in which every value is `0` *except* those on the main diagonal from top-left to bottom-right corner (in other words, where the offsets in each direction are equal).

  
`m11`, `m12`, `m13`, `m14`, `m21`, `m22`, `m23`, `m24`, `m31`, `m32`, `m33`, `m34`, `m41`, `m42`, `m43`, `m44`
  Double-precision floating-point values representing each component of a 4×4 matrix, where `m11` through `m14` are the first column, `m21` through `m24` are the second column, and so forth.

  
`a`, `b`, `c`, `d`, `e`, `f`
  Double-precision floating-point values representing the components of a 4×4 matrix which are required in order to perform 2D rotations and translations. These are aliases for specific components of a 4×4 matrix, as shown below.

 

| `2D` | `3D equivalent` |
| --- | --- |
| `a` | `m11` |
| `b` | `m12` |
| `c` | `m21` |
| `d` | `m22` |
| `e` | `m41` |
| `f` | `m42` |

  

Instance methods
----------------



*This interface includes the following methods, as well as the methods it inherits from [`DOMMatrixReadOnly`](dommatrixreadonly).*

  `DOMMatrix.invertSelf()`  Modifies the matrix by inverting it. If the matrix can't be inverted, its components are all set to `NaN`, and `is2D` returns `false`.

  `DOMMatrix.multiplySelf()`  Modifies the matrix by post-multiplying it with the specified `DOMMatrix`. This is equivalent to the dot product `A⋅B`, where matrix `A` is the source matrix and `B` is the matrix given as an input to the method. Returns itself.

  `DOMMatrix.preMultiplySelf()`  Modifies the matrix by pre-multiplying it with the specified `DOMMatrix`. This is equivalent to the dot product `B⋅A`, where matrix `A` is the source matrix and `B` is the matrix given as an input to the method. Returns itself.

  `DOMMatrix.translateSelf()`  Modifies the matrix by applying the specified vector. The default vector is `[0, 0, 0]`. Returns itself.

  
`DOMMatrix.scaleNonUniformSelf()`  Deprecated 
  Modifies the matrix by applying the specified scaling on the X, Y, and Z axes, centered at the given origin. By default, the Y and Z axes' scaling factors are both `1`, but the scaling factor for X must be specified. The default origin is `(0, 0, 0)`. Returns itself.

  `DOMMatrix.scaleSelf()`  Modifies the matrix by applying the specified scaling factors, with the center located at the specified origin. Also returns itself. By default, the scaling factor is `1` for all three axes, and the origin is `(0, 0, 0)`. Returns itself.

  `DOMMatrix.scale3dSelf()`  Modifies the matrix by applying the specified scaling factor to all three axes, centered on the given origin. Returns itself.

  `DOMMatrix.rotateSelf()`  Modifies the matrix by rotating itself around each axis by the specified number of degrees. Returns itself.

  `DOMMatrix.rotateAxisAngleSelf()`  Modifies the matrix by rotating it by the specified angle around the given vector. Returns itself.

  `DOMMatrix.rotateFromVectorSelf()`  Modifies the matrix by rotating it by the angle between the specified vector and `(1, 0)`. Returns itself.

  `DOMMatrix.setMatrixValue()`  Replaces the contents of the matrix with the matrix described by the specified transform or transforms. Returns itself.

  `DOMMatrix.skewXSelf()`  Modifies the matrix by applying the specified skew transformation along the X-axis. Returns itself.

  `DOMMatrix.skewYSelf()`  Modifies the matrix by applying the specified skew transformation along the Y-axis. Returns itself.

  

Static methods
--------------



*This interface inherits methods from [`DOMMatrixReadOnly`](dommatrixreadonly).*

  `fromFloat32Array()`  Creates a new mutable `DOMMatrix` object given an array of single-precision (32-bit) floating-point values. If the array has six values, the result is a 2D matrix; if the array has 16 values, the result is a 3D matrix. Otherwise, a [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) exception is thrown.

  `fromFloat64Array()`  Creates a new mutable `DOMMatrix` object given an array of double-precision (64-bit) floating-point values. If the array has six values, the result is a 2D matrix; if the array has 16 values, the result is a 3D matrix. Otherwise, a [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) exception is thrown.

  `fromMatrix()`  Creates a new mutable `DOMMatrix` object given an existing matrix or a `DOMMatrixInit` dictionary which provides the values for its properties.

  

Usage notes
-----------



The matrix defined by the `DOMMatrix` interface is comprised of four rows of four columns each. While it's beyond the scope of this article to explain the mathematics involved, this 4×4 size is enough to describe any transformation you might apply to either 2D or 3D geometries.

 Here are the positions of the 16 elements (m\_11 through m\_44) which comprise the 4×4 abstract matrix:

     [     m 11     m 21     m 31     m 41       m 12     m 22     m 32     m 42       m 13     m 23     m 33     m 43       m 14     m 24     m 34     m 44     ]  \left [ \begin{matrix} m\_{11} & m\_{21} & m\_{31} & m\_{41} \ m\_{12} & m\_{22} & m\_{32} & m\_{42} \ m\_{13} & m\_{23} & m\_{33} & m\_{43} \ m\_{14} & m\_{24} & m\_{34} & m\_{44} \end{matrix} \right ]   

 The `DOMMatrix` interface is designed with the intent that it will be used for all matrices within markup.



Specifications
--------------




| Specification |
| --- |
| [Geometry Interfaces Module Level 1 # DOMMatrix](https://drafts.fxtf.org/geometry/#DOMMatrix) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DOMMatrix` | 6152 | 79121212–79 | 49331.5 | 11109 | 4815≤12.1 | 1154 | 614.44.4 | 611818 | 49334 | 4814≤12.1 | 1143 | 8.01.01.0 |
| `DOMMatrix` | 6152 | 79121212–79 | 49331.5 | 11109 | 4815≤12.1 | 1154 | 614.44.4 | 611818 | 49334 | 4814≤12.1 | 1143 | 8.01.01.0 |
| `a` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `b` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `c` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `d` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `e` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `f` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `fromFloat32Array` | 61 | 79 | 69 | No | 48 | 11 | 61 | 61 | 79 | 45 | 11 | 8.0 |
| `fromFloat64Array` | 61 | 79 | 69 | No | 48 | 11 | 61 | 61 | 79 | 45 | 11 | 8.0 |
| `fromMatrix` | 61 | 79 | 69 | No | 48 | 11 | 61 | 61 | 79 | 45 | 11 | 8.0 |
| `invertSelf` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m11` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m12` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m13` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m14` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m21` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m22` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m23` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m24` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m31` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m32` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m33` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m34` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m41` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m42` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m43` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m44` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `multiplySelf` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `preMultiplySelf` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `rotateAxisAngleSelf` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `rotateFromVectorSelf` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `rotateSelf` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `scale3dSelf` | 61 | 79 | 33Starting in Firefox 69, the first parameter (`scale`) is now optional with a default value of 1, per the specification. Previously it was required. | No | 48 | 11 | 61 | 61 | 33Firefox for Android requires the first parameter (`scale`). | 45 | 11 | 8.0 |
| `scaleSelf` | 61 | 79 | 33Firefox 69 introduced support for the modern six-parameter syntax for `scaleSelf()`. Previously, it only supported the older three-parameter syntax: `scale(*scaleX*[, *originX*][, *originY*]]])`. | No | 48 | 11 | 61 | 61 | 33Firefox for Android only supports the older three-parameter syntax for `scaleSelf()`: `scale(*scaleX*[, *originX*][, *originY*]]])`, and not the six-parameter syntax. | 45 | 11 | 8.0 |
| `setMatrixValue` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `skewXSelf` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `skewYSelf` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `translateSelf` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `worker_support` | 61 | 79 | 69 | No | 48 | 11 | 61 | 61 | No | 45 | 11 | 8.0 |


### api.DOMMatrix


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.WebKitCSSMatrix


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


See also
--------


* Its non-modifiable counterpart, [`DOMMatrixReadOnly`](dommatrixreadonly)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DOMMatrix>

DOMMatrixReadOnly
=================



The `DOMMatrixReadOnly` interface represents a read-only 4×4 matrix, suitable for 2D and 3D operations. The [`DOMMatrix`](dommatrix) interface — which is based upon `DOMMatrixReadOnly`—adds [mutability](https://en.wikipedia.org/wiki/Immutable_object), allowing you to alter the matrix after creating it.

 This interface should be available inside [web workers](web_workers_api), though some implementations doesn't allow it yet.



Constructor
-----------


 [`DOMMatrixReadOnly()`](dommatrixreadonly/dommatrixreadonly)  Creates a new `DOMMatrixReadOnly` object.

  
Instance properties
-------------------



*This interface doesn't inherit any properties.*

  
`is2D` Read only 
  A Boolean flag whose value is `true` if the matrix was initialized as a 2D matrix. If `false`, the matrix is 3D.

  
`isIdentity` Read only 
  A Boolean whose value is `true` if the matrix is the [identity matrix](https://en.wikipedia.org/wiki/Identity_matrix). The identity matrix is one in which every value is `0` *except* those on the main diagonal from top-left to bottom-right corner (in other words, where the offsets in each direction are equal).

  
`m11`, `m12`, `m13`, `m14`, `m21`, `m22`, `m23`, `m24`, `m31`, `m32`, `m33`, `m34`, `m41`, `m42`, `m43`, `m44`
  Double-precision floating-point values representing each component of a 4×4 matrix, where `m11` through `m14` are the first column, `m21` through `m24` are the second column, and so forth.

  
`a`, `b`, `c`, `d`, `e`, `f`
  Double-precision floating-point values representing the components of a 4×4 matrix which are required in order to perform 2D rotations and translations. These are aliases for specific components of a 4×4 matrix, as shown below.

 

| 2D | 3D equivalent |
| --- | --- |
| `a` | `m11` |
| `b` | `m12` |
| `c` | `m21` |
| `d` | `m22` |
| `e` | `m41` |
| `f` | `m42` |

  

Instance methods
----------------



*This interface doesn't inherit any methods. None of the following methods alter the original matrix.*

  [`DOMMatrixReadOnly.flipX()`](dommatrixreadonly/flipx)  Returns a new [`DOMMatrix`](dommatrix) created by flipping the source matrix around its X-axis. This is equivalent to multiplying the matrix by `DOMMatrix(-1, 0, 0, 1, 0, 0)`. The original matrix is not modified.

  `DOMMatrixReadOnly.flipY()`  Returns a new [`DOMMatrix`](dommatrix) created by flipping the source matrix around its Y-axis. This is equivalent to multiplying the matrix by `DOMMatrix(1, 0, 0, -1, 0, 0)`. The original matrix is not modified.

  `DOMMatrixReadOnly.inverse()`  Returns a new [`DOMMatrix`](dommatrix) created by inverting the source matrix. If the matrix cannot be inverted, the new matrix's components are all set to `NaN` and its `is2D` property is set to `false`. The original matrix is not altered.

  `DOMMatrixReadOnly.multiply()`  Returns a new [`DOMMatrix`](dommatrix) created by computing the dot product of the source matrix and the specified matrix: `A⋅B`. If no matrix is specified as the multiplier, the matrix is multiplied by a matrix in which every element is `0` *except* the bottom-right corner and the element immediately above and to its left: `m33` and `m34`. These have the default value of `1`. The original matrix is not modified.

  `DOMMatrixReadOnly.rotateAxisAngle()`  Returns a new [`DOMMatrix`](dommatrix) created by rotating the source matrix by the given angle around the specified vector. The original matrix is not modified.

  `DOMMatrixReadOnly.rotate()`  Returns a new [`DOMMatrix`](dommatrix) created by rotating the source matrix around each of its axes by the specified number of degrees. The original matrix is not altered.

  `DOMMatrixReadOnly.rotateFromVector()`  Returns a new [`DOMMatrix`](dommatrix) created by rotating the source matrix by the angle between the specified vector and `(1, 0)`. The original matrix is not modified.

  [`DOMMatrixReadOnly.scale()`](dommatrixreadonly/scale)  Returns a new [`DOMMatrix`](dommatrix) created by scaling the source matrix by the amount specified for each axis, centered on the given origin. By default, the X and Z axes are scaled by `1` and the Y axis has no default scaling value. The default origin is `(0, 0, 0)`. The original matrix is not modified.

  `DOMMatrixReadOnly.scale3d()`  Returns a new [`DOMMatrix`](dommatrix) created by scaling the source 3D matrix by the given factor along all its axes, centered on the specified origin point. The default origin is `(0, 0, 0)`. The original matrix is not modified.

  
`DOMMatrixReadOnly.scaleNonUniform()`  Deprecated 
  Returns a new [`DOMMatrix`](dommatrix) created by applying the specified scaling on the X, Y, and Z axes, centered at the given origin. By default, the Y and Z axes' scaling factors are both `1`, but the scaling factor for X must be specified. The default origin is `(0, 0, 0)`. The original matrix is not changed.

  `DOMMatrixReadOnly.skewX()`  Returns a new [`DOMMatrix`](dommatrix) created by applying the specified skew transformation to the source matrix along its X-axis. The original matrix is not modified.

  `DOMMatrixReadOnly.skewY()`  Returns a new [`DOMMatrix`](dommatrix) created by applying the specified skew transformation to the source matrix along its Y-axis. The original matrix is not modified.

  `DOMMatrixReadOnly.toFloat32Array()`  Returns a new [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) containing all 16 elements (`m11`, `m12`, `m13`, `m14`, `m21`, `m22`, `m23`, `m24`, `m31`, `m32`, `m33`, `m34`, `m41`, `m42`, `m43`, `m44`) which comprise the matrix. The elements are stored into the array as single-precision floating-point numbers in column-major (colexographical access, or "colex") order. (In other words, down the first column from top to bottom, then the second column, and so forth.)

  `DOMMatrixReadOnly.toFloat64Array()`  Returns a new [`Float64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) containing all 16 elements (`m11`, `m12`, `m13`, `m14`, `m21`, `m22`, `m23`, `m24`, `m31`, `m32`, `m33`, `m34`, `m41`, `m42`, `m43`, `m44`) which comprise the matrix. The elements are stored into the array as double-precision floating-point numbers in column-major (colexographical access, or "colex") order. (In other words, down the first column from top to bottom, then the second column, and so forth.)

  `DOMMatrixReadOnly.toJSON()`  Returns a JSON representation of the `DOMMatrixReadOnly` object.

  `DOMMatrixReadOnly.toString()`  Creates and returns a string object which contains a string representation of the matrix in CSS matrix syntax, using the appropriate CSS matrix notation. See the `matrix()` CSS function for details on this syntax.

 For a 2D matrix, the elements `a` through `f` are listed, for a total of six values and the form `matrix(a, b, c, d, e, f)`.

 For a 3D matrix, the returned string contains all 16 elements and takes the form `matrix3d(m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44)`. See the CSS `matrix3d()` function for details on the 3D notation's syntax.

 Throws an `InvalidStateError` exception if any of the elements in the matrix are non-finite (even if, in the case of a 2D matrix, the non-finite values are in elements not used by the 2D matrix representation).

  `DOMMatrixReadOnly.transformPoint()`  Transforms the specified point using the matrix, returning a new [`DOMPoint`](dompoint) object containing the transformed point. Neither the matrix nor the original point are altered.

  [`DOMMatrixReadOnly.translate()`](dommatrixreadonly/translate)  Returns a new [`DOMMatrix`](dommatrix) containing a matrix calculated by translating the source matrix using the specified vector. By default, the vector is `(0, 0, 0)`. The original matrix is not changed.

  

Static methods
--------------



*This interface inherits methods from [`DOMMatrixReadOnly`](dommatrixreadonly).*

  `fromFloat32Array()`  Creates a new mutable `DOMMatrix` object given an array of single-precision (32-bit) floating-point values. If the array has six values, the result is a 2D matrix; if the array has 16 values, the result is a 3D matrix. Otherwise, a [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) exception is thrown.

  `fromFloat64Array()`  Creates a new mutable `DOMMatrix` object given an array of double-precision (64-bit) floating-point values. If the array has six values, the result is a 2D matrix; if the array has 16 values, the result is a 3D matrix. Otherwise, a [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) exception is thrown.

  `fromMatrix()`  Creates a new mutable `DOMMatrix` object given an existing matrix or a `DOMMatrixInit` dictionary which provides the values for its properties. If no matrix is specified, the matrix is initialized with every element set to `0` *except* the bottom-right corner and the element immediately above and to its left: `m33` and `m34`. These have the default value of `1`.

  

Specifications
--------------




| Specification |
| --- |
| [Geometry Interfaces Module Level 1 # DOMMatrix](https://drafts.fxtf.org/geometry/#DOMMatrix) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DOMMatrixReadOnly` | 61 | 79 | 62 | No | 48 | 11 | 61 | 61 | 62 | 45 | 11 | 8.0 |
| `DOMMatrixReadOnly` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `a` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `b` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `c` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `d` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `e` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `f` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `flipX` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `flipY` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `fromFloat32Array` | 61 | 79 | 69 | No | 48 | 11 | 61 | 61 | 79 | 45 | 11 | 8.0 |
| `fromFloat64Array` | 61 | 79 | 69 | No | 48 | 11 | 61 | 61 | 79 | 45 | 11 | 8.0 |
| `fromMatrix` | 61 | 79 | 69 | No | 48 | 11 | 61 | 61 | 79 | 45 | 11 | 8.0 |
| `inverse` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `is2D` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `isIdentity` | 61 | 79 | 59 | No | 48 | 11 | 61 | 61 | 59 | 45 | 11 | 8.0 |
| `m11` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m12` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m13` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m14` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m21` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m22` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m23` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m24` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m31` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m32` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m33` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m34` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m41` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m42` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m43` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `m44` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `multiply` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `rotate` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `rotateAxisAngle` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `rotateFromVector` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `scale` | 61 | 79 | 33Firefox 69 introduced support for the modern six-parameter syntax for `scale()`. Previously, it only supported the older three-parameter syntax: `scale(*scaleX*[, *originX*][, *originY*]]])`. | No | 48 | 11 | 61 | 61 | 33Firefox for Android 79 introduced support for the modern six-parameter syntax for `scale()`. Previously, it only supported the older three-parameter syntax: `scale(*scaleX*[, *originX*][, *originY*]]])`. | 45 | 11 | 8.0 |
| `scale3d` | 61 | 79 | 33Starting in Firefox 69, the first parameter (`scale`) is now optional with a default value of 1, per the specification. Previously it was required. | No | 48 | 11 | 61 | 61 | 33Starting in Firefox for Android 79, the first parameter (`scale`) is now optional with a default value of 1, per the specification. Previously it was required. | 45 | 11 | 8.0 |
| `scaleNonUniform` | 73 | 79 | 33 | No | 60 | No | 73 | 73 | 33 | 52 | No | 11.0 |
| `skewX` | 61 | 79 | 33Before Firefox 69, the `sx` parameter was required; you may now call `skewX()` with no inputs. A value of 0 is correctly assumed. | No | 48 | 11 | 61 | 61 | 33Before Firefox for Android 79, the `sx` parameter was required; you may now call `skewX()` with no inputs. A value of 0 is correctly assumed. | 45 | 11 | 8.0 |
| `skewY` | 61 | 79 | 33Before Firefox 69, the `sy` parameter was required; you may now call `skewY()` with no inputs. A value of 0 is correctly assumed. | No | 48 | 11 | 61 | 61 | 33Before Firefox for Android 79, the `sy` parameter was required; you may now call `skewY()` with no inputs. A value of 0 is correctly assumed. | 45 | 11 | 8.0 |
| `toFloat32Array` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `toFloat64Array` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `toJSON` | 61 | 79 | 62 | No | 48 | 11 | 61 | 61 | 62 | 45 | 11 | 8.0 |
| `toString` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `transformPoint` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `translate` | 61 | 79 | 33 | No | 48 | 11 | 61 | 61 | 33 | 45 | 11 | 8.0 |
| `worker_support` | 61 | 79 | 69 | No | 48 | 11 | 61 | 61 | 79 | 45 | 11 | 8.0 |


See also
--------


* The mutable matrix type, [`DOMMatrix`](dommatrix), which is based on this one.
* The CSS [`matrix()`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function#matrix()) and [`matrix3d()`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function#matrix3d()) functional notation that can be generated from this interface to be used in a CSS [`transform`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DOMMatrixReadOnly>

DOMParser
=========



 The `DOMParser` interface provides the ability to parse [XML](https://developer.mozilla.org/en-US/docs/Glossary/XML) or [HTML](https://developer.mozilla.org/en-US/docs/Glossary/HTML) source code from a string into a DOM [`Document`](document). 

  You can perform the opposite operation—converting a DOM tree into XML or HTML source—using the [`XMLSerializer`](xmlserializer) interface. 

  In the case of an HTML document, you can also replace portions of the DOM with new DOM trees built from HTML by setting the value of the [`Element.innerHTML`](element/innerhtml) and [`outerHTML`](element/outerhtml) properties. These properties can also be read to fetch HTML fragments corresponding to the corresponding DOM subtree. 

  Note that [`XMLHttpRequest`](xmlhttprequest) can parse XML and HTML directly from a URL-addressable resource, returning a `Document` in its [`response`](xmlhttprequest/response) property. 

   **Note:** Be aware that [block-level elements](https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements) like `<p>` will be automatically closed if another block-level element is nested inside and therefore parsed before the closing `</p>` tag. 

 

Constructor
-----------


 [`DOMParser()`](domparser/domparser)  Creates a new `DOMParser` object.

  
Instance methods
----------------


 [`DOMParser.parseFromString()`](domparser/parsefromstring)  Parses a string using either the HTML parser or the XML parser, returning an [`HTMLDocument`](htmldocument) or [`XMLDocument`](xmldocument).

  
Examples
--------


The documentation for [`DOMParser.parseFromString()`](domparser/parsefromstring), this interface's only method, contains examples for parsing XML, SVG, and HTML strings.


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # dom-parsing-and-serialization](https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-parsing-and-serialization) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DOMParser` | 1 | 12 | 1 | 9 | 8 | 1.3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `DOMParser` | 1 | 12 | 1 | 9 | 8 | 1.3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `parseFromString` | 1 | 12 | 1 | 9 | 8 | 1.3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |


See also
--------


* [Parsing and serializing XML](https://developer.mozilla.org/en-US/docs/Web/Guide/Parsing_and_serializing_XML)
* [`XMLHttpRequest`](xmlhttprequest)
* [`XMLSerializer`](xmlserializer)
* [`JSON.parse()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) - counterpart for [`JSON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON) documents.


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DOMParser>

DOMPoint
========



A `DOMPoint` object represents a 2D or 3D point in a coordinate system; it includes values for the coordinates in up to three dimensions, as well as an optional perspective value. `DOMPoint` is based on [`DOMPointReadOnly`](dompointreadonly) but allows its properties' values to be changed.

 In general, a positive `x` component represents a position to the right of the origin, a positive `y` component is downward from the origin, and a positive `z` component extends outward from the screen (in other words, toward the user).


 DOMPointReadOnly DOMPoint

Constructor
-----------


 [`DOMPoint()`](dompoint/dompoint)  Creates and returns a new `DOMPoint` object given the values of zero or more of its coordinate components and optionally the `w` perspective value. You can also use an existing `DOMPoint` or `DOMPointReadOnly` or an object to create a new point by calling the [`DOMPoint.fromPoint()`](dompoint/frompoint) static method.

  
Instance properties
-------------------



*`DOMPoint` may also inherit properties from its parent, [`DOMPointReadOnly`](dompointreadonly).*

  [`DOMPoint.x`](dompoint/x)  The `x` coordinate of the `DOMPoint`.

  [`DOMPoint.y`](dompoint/y)  The `y` coordinate of the `DOMPoint`.

  [`DOMPoint.z`](dompoint/z)  The `z` coordinate of the `DOMPoint`.

  [`DOMPoint.w`](dompoint/w)  The perspective value of the `DOMPoint`.

  

Instance methods
----------------


*`DOMPoint` inherits instance methods from its parent, [`DOMPointReadOnly`](dompointreadonly).*


Static methods
--------------



*`DOMPoint` may also inherit static methods from its parent, [`DOMPointReadOnly`](dompointreadonly).*

  [`DOMPoint.fromPoint()`](dompoint/frompoint)  Creates a new mutable `DOMPoint` object given an existing point (or an object containing matching properties) which provides the values for its properties.

  

Examples
--------



In the [WebXR Device API](webxr_device_api), `DOMPointReadOnly` values are used to represent positions and orientations. In the following snippet, the pose of the XR device (such as a VR headset or phone with AR capabilities) can be retrieved by calling using [`XRFrame.getViewerPose()`](xrframe/getviewerpose) during an [`XRSession`](xrsession) animation frame, then accessing the resulting [`XRPose`](xrpose)'s [`transform`](xrpose/transform) property, which contains two `DOMPointReadOnly` attributes: [`position`](xrrigidtransform/position) as a vector and `orientation` as a quaternion.

 
```
function onXRFrame(time, xrFrame) {
  let viewerPose = xrFrame.getViewerPose(xrReferenceSpace);

  if (viewerPose) {
    let position = viewerPose.transform.position;
    let orientation = viewerPose.transform.orientation;

    console.log(
      `XR Viewer Position: {x: ${roundToTwo(position.x)}, y: ${roundToTwo(
 position.y
 )}, z: ${roundToTwo(position.z)}`
    );

    console.log(
      `XR Viewer Orientation: {x: ${roundToTwo(orientation.x)}, y: ${roundToTwo(
 orientation.y
 )}, z: ${roundToTwo(orientation.z)}, w: ${roundToTwo(orientation.w)}`
    );
  }
}

```


Specifications
--------------




| Specification |
| --- |
| [Geometry Interfaces Module Level 1 # DOMPoint](https://drafts.fxtf.org/geometry/#DOMPoint) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DOMPoint` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |
| `DOMPoint` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |
| `fromPoint` | 61 | 79 | 62 | No | 48 | 10.1 | 61 | 61 | 62 | 45 | 10.3 | 8.0 |
| `w` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |
| `worker_support` | 61 | 79 | 69 | No | 48 | 10.1 | 61 | 61 | No | 45 | 10.3 | 8.0 |
| `x` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |
| `y` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |
| `z` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |


See also
--------


* [`DOMRect`](domrect)
* [`DOMMatrix`](dommatrix)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DOMPoint>

Document
========



The `Document` interface represents any web page loaded in the browser and serves as an entry point into the web page's content, which is the [DOM tree](document_object_model/using_the_document_object_model#what_is_a_dom_tree).

 The DOM tree includes elements such as [`<body>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/body) and [`<table>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table), among [many others](https://developer.mozilla.org/en-US/docs/Web/HTML/Element). It provides functionality globally to the document, like how to obtain the page's URL and create new elements in the document.


 EventTarget Node Document The `Document` interface describes the common properties and methods for any kind of document. Depending on the document's type (e.g. [HTML](https://developer.mozilla.org/en-US/docs/Web/HTML), [XML](https://developer.mozilla.org/en-US/docs/Web/XML), SVG, …), a larger API is available: HTML documents, served with the `"text/html"` content type, also implement the [`HTMLDocument`](htmldocument) interface, whereas XML and SVG documents implement the [`XMLDocument`](xmldocument) interface.



Constructor
-----------


 [`Document()`](document/document)  Creates a new `Document` object.

  
Instance properties
-------------------



*This interface also inherits from the [`Node`](node) and [`EventTarget`](eventtarget) interfaces.*

  
[`Document.activeElement`](document/activeelement) Read only 
  Returns the [`Element`](element) that currently has focus.

  [`Document.adoptedStyleSheets`](document/adoptedstylesheets)   Add an array of constructed stylesheets to be used by the document. These stylesheets may also be shared with shadow DOM subtrees of the same document. 

  [`Document.body`](document/body)  Returns the [`<body>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/body) or [`<frameset>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/frameset) node of the current document.

  
[`Document.characterSet`](document/characterset) Read only 
  Returns the character set being used by the document.

  
[`Document.childElementCount`](document/childelementcount) Read only 
  Returns the number of child elements of the current document.

  
[`Document.children`](document/children) Read only 
  Returns the child elements of the current document.

  
[`Document.compatMode`](document/compatmode) Read only 
  Indicates whether the document is rendered in *quirks* or *strict* mode.

  
[`Document.contentType`](document/contenttype) Read only 
  Returns the Content-Type from the MIME Header of the current document.

  
[`Document.currentScript`](document/currentscript) Read only 
  Returns the [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) element whose script is currently being processed and [isn't a JavaScript module](https://github.com/whatwg/html/issues/997).

  
[`Document.doctype`](document/doctype) Read only 
  Returns the Document Type Definition (DTD) of the current document.

  
[`Document.documentElement`](document/documentelement) Read only 
  Returns the [`Element`](element) that is a direct child of the document. For HTML documents, this is normally the [`HTMLHtmlElement`](htmlhtmlelement) object representing the document's [`<html>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/html) element.

  
[`Document.documentURI`](document/documenturi) Read only 
  Returns the document location as a string.

  
[`Document.embeds`](document/embeds) Read only 
  Returns an [`HTMLCollection`](htmlcollection) of the embedded [`<embed>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/embed) elements in the document.

  
[`Document.firstElementChild`](document/firstelementchild) Read only 
  Returns the first child element of the current document.

  [`Document.fonts`](document/fonts)  Returns the [`FontFaceSet`](fontfaceset) interface of the current document.

  
[`Document.forms`](document/forms) Read only 
  Returns an [`HTMLCollection`](htmlcollection) of the [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) elements in the document.

  
[`Document.fragmentDirective`](document/fragmentdirective) Read only   Experimental 
  Returns the [`FragmentDirective`](fragmentdirective) for the current document.

  
[`Document.fullscreenElement`](document/fullscreenelement) Read only 
  The element that's currently in full screen mode for this document.

  
[`Document.head`](document/head) Read only 
  Returns the [`<head>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head) element of the current document.

  
[`Document.hidden`](document/hidden) Read only 
  Returns a Boolean value indicating if the page is considered hidden or not.

  
[`Document.images`](document/images) Read only 
  Returns an [`HTMLCollection`](htmlcollection) of the images in the document.

  
[`Document.implementation`](document/implementation) Read only 
  Returns the DOM implementation associated with the current document.

  
[`Document.lastElementChild`](document/lastelementchild) Read only 
  Returns the last child element of the current document.

  
[`Document.links`](document/links) Read only 
  Returns an [`HTMLCollection`](htmlcollection) of the hyperlinks in the document.

  
[`Document.pictureInPictureElement`](document/pictureinpictureelement) Read only 
  Returns the [`Element`](element) currently being presented in picture-in-picture mode in this document.

  
[`Document.pictureInPictureEnabled`](document/pictureinpictureenabled) Read only 
  Returns true if the picture-in-picture feature is enabled.

  
[`Document.plugins`](document/plugins) Read only 
  Returns an [`HTMLCollection`](htmlcollection) of the available plugins.

  
[`Document.pointerLockElement`](document/pointerlockelement) Read only 
  Returns the element set as the target for mouse events while the pointer is locked. `null` if lock is pending, pointer is unlocked, or if the target is in another document.

  
[`Document.featurePolicy`](document/featurepolicy)  Experimental  Read only 
  Returns the [`FeaturePolicy`](featurepolicy) interface which provides a simple API for introspecting the feature policies applied to a specific document.

  
[`Document.scripts`](document/scripts) Read only 
  Returns an [`HTMLCollection`](htmlcollection) of the [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) elements in the document.

  
[`Document.scrollingElement`](document/scrollingelement) Read only 
  Returns a reference to the [`Element`](element) that scrolls the document.

  
[`Document.styleSheets`](document/stylesheets) Read only 
  Returns a [`StyleSheetList`](stylesheetlist) of [`CSSStyleSheet`](cssstylesheet) objects for stylesheets explicitly linked into, or embedded in a document.

  
[`Document.timeline`](document/timeline) Read only 
  Returns timeline as a special instance of [`DocumentTimeline`](documenttimeline) that is automatically created on page load.

  
[`Document.visibilityState`](document/visibilitystate) Read only 
  Returns a `string` denoting the visibility state of the document. Possible values are `visible`, `hidden`, `prerender`, and `unloaded`.

  

### Extensions for HTMLDocument



*The `Document` interface for HTML documents inherits from the [`HTMLDocument`](htmldocument) interface or is extended for such documents.*

  [`Document.cookie`](document/cookie)  Returns a semicolon-separated list of the cookies for that document or sets a single cookie.

  
[`Document.defaultView`](document/defaultview) Read only 
  Returns a reference to the window object.

  [`Document.designMode`](document/designmode)  Gets/sets the ability to edit the whole document.

  [`Document.dir`](document/dir)  Gets/sets directionality (rtl/ltr) of the document.

  
[`Document.domain`](document/domain)  Deprecated 
  Gets/sets the domain of the current document.

  
[`Document.fullscreenEnabled`](document/fullscreenenabled) Read only 
  Indicates whether fullscreen mode is available.

  
[`Document.lastModified`](document/lastmodified) Read only 
  Returns the date on which the document was last modified.

  
[`Document.location`](document/location) Read only 
  Returns the URI of the current document.

  
[`Document.readyState`](document/readystate) Read only 
  Returns loading status of the document.

  
[`Document.referrer`](document/referrer) Read only 
  Returns the URI of the page that linked to this page.

  [`Document.title`](document/title)  Sets or gets the title of the current document.

  
[`Document.URL`](document/url) Read only 
  Returns the document location as a string.

  

### Deprecated properties


 
[`Document.alinkColor`](document/alinkcolor)  Deprecated 
  Returns or sets the color of active links in the document body.

  
[`Document.all`](document/all)  Deprecated 
  Provides access to all elements in the document — it returns an `HTMLAllCollection` rooted at the document node. This is a legacy, non-standard property and should not be used.

  
[`Document.anchors`](document/anchors)  Deprecated  Read only 
  Returns a list of all of the anchors in the document.

  
[`Document.applets`](document/applets)  Deprecated  Read only 
  Returns an ordered list of the applets within a document.

  
[`Document.bgColor`](document/bgcolor)  Deprecated 
  Gets/sets the background color of the current document.

  
[`Document.charset`](document/characterset)  Deprecated  Read only 
  Alias of [`Document.characterSet`](document/characterset). Use this property instead.

  
[`Document.fgColor`](document/fgcolor)  Deprecated 
  Gets/sets the foreground color, or text color, of the current document.

  
[`Document.fullscreen`](document/fullscreen)  Deprecated 
  `true` when the document is in [fullscreen mode](fullscreen_api).

  
[`Document.height`](element/clientheight)  Non-standard   Deprecated 
  Gets/sets the height of the current document.

  
[`Document.inputEncoding`](document/characterset)  Deprecated  Read only 
  Alias of [`Document.characterSet`](document/characterset). Use this property instead.

  
[`Document.lastStyleSheetSet`](document/laststylesheetset)  Deprecated  Read only   Non-standard 
  Returns the name of the style sheet set that was last enabled. Has the value `null` until the style sheet is changed by setting the value of [`selectedStyleSheetSet`](document/selectedstylesheetset).

  
[`Document.linkColor`](document/linkcolor)  Deprecated 
  Gets/sets the color of hyperlinks in the document.

  
[`Document.preferredStyleSheetSet`](document/preferredstylesheetset)  Deprecated  Read only   Non-standard 
  Returns the preferred style sheet set as specified by the page author.

  
[`Document.rootElement`](document/rootelement)  Deprecated 
  Like [`Document.documentElement`](document/documentelement), but only for [`<svg>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg) root elements. Use this property instead.

  
[`Document.selectedStyleSheetSet`](document/selectedstylesheetset)  Deprecated   Non-standard 
  Returns which style sheet set is currently in use.

  
[`Document.styleSheetSets`](document/stylesheetsets)  Deprecated  Read only   Non-standard 
  Returns a list of the style sheet sets available on the document.

  
[`Document.vlinkColor`](document/vlinkcolor)  Deprecated 
  Gets/sets the color of visited hyperlinks.

  
[`Document.width`](element/clientwidth)  Non-standard   Deprecated 
  Returns the width of the current document.

  
[`Document.xmlEncoding`](document/xmlencoding)  Deprecated 
  Returns the encoding as determined by the XML declaration.

  
`Document.xmlStandalone`  Deprecated 
  Returns `true` if the XML declaration specifies the document to be standalone (*e.g.,* An external part of the DTD affects the document's content), else `false`.

  
[`Document.xmlVersion`](document/xmlversion)  Deprecated 
  Returns the version number as specified in the XML declaration or `"1.0"` if the declaration is absent.

  
Instance methods
----------------



*This interface also inherits from the [`Node`](node) and [`EventTarget`](eventtarget) interfaces.*

  [`Document.adoptNode()`](document/adoptnode)  Adopt node from an external document.

  [`Document.append()`](document/append)  Inserts a set of [`Node`](node) objects or string objects after the last child of the document.

  
`Document.captureEvents()`  Deprecated 
  See [`Window.captureEvents`](window/captureevents).

  [`Document.caretPositionFromPoint()`](document/caretpositionfrompoint)  Returns a [`CaretPosition`](caretposition) object containing the DOM node containing the caret, and caret's character offset within that node.

  
[`Document.caretRangeFromPoint()`](document/caretrangefrompoint)  Non-standard 
  Gets a [`Range`](range) object for the document fragment under the specified coordinates.

  [`Document.createAttribute()`](document/createattribute)  Creates a new [`Attr`](attr) object and returns it.

  [`Document.createAttributeNS()`](document/createattributens)  Creates a new attribute node in a given namespace and returns it.

  [`Document.createCDATASection()`](document/createcdatasection)  Creates a new CDATA node and returns it.

  [`Document.createComment()`](document/createcomment)  Creates a new comment node and returns it.

  [`Document.createDocumentFragment()`](document/createdocumentfragment)  Creates a new document fragment.

  [`Document.createElement()`](document/createelement)  Creates a new element with the given tag name.

  [`Document.createElementNS()`](document/createelementns)  Creates a new element with the given tag name and namespace URI.

  
[`Document.createEntityReference()`](document)  Deprecated 
  Creates a new entity reference object and returns it.

  [`Document.createEvent()`](document/createevent)  Creates an event object.

  [`Document.createNodeIterator()`](document/createnodeiterator)  Creates a [`NodeIterator`](nodeiterator) object.

  [`Document.createProcessingInstruction()`](document/createprocessinginstruction)  Creates a new [`ProcessingInstruction`](processinginstruction) object.

  [`Document.createRange()`](document/createrange)  Creates a [`Range`](range) object.

  [`Document.createTextNode()`](document/createtextnode)  Creates a text node.

  
[`Document.createTouch()`](document/createtouch)  Deprecated   Non-standard 
  Creates a [`Touch`](touch) object.

  
[`Document.createTouchList()`](document/createtouchlist)  Deprecated   Non-standard 
  Creates a [`TouchList`](touchlist) object.

  [`Document.createTreeWalker()`](document/createtreewalker)  Creates a [`TreeWalker`](treewalker) object.

  [`Document.elementFromPoint()`](document/elementfrompoint)  Returns the topmost element at the specified coordinates.

  [`Document.elementsFromPoint()`](document/elementsfrompoint)  Returns an array of all elements at the specified coordinates.

  
[`Document.enableStyleSheetsForSet()`](document/enablestylesheetsforset)  Deprecated   Non-standard 
  Enables the style sheets for the specified style sheet set.

  [`Document.exitFullscreen()`](document/exitfullscreen)  Stops document's fullscreen element from being displayed fullscreen.

  [`Document.exitPictureInPicture()`](document/exitpictureinpicture)  Remove the video from the floating picture-in-picture window back to its original container.

  [`Document.exitPointerLock()`](document/exitpointerlock)  Release the pointer lock.

  [`Document.getAnimations()`](document/getanimations)  Returns an array of all [`Animation`](animation) objects currently in effect, whose target elements are descendants of the `document`.

  
`Document.getBoxQuads()`  Experimental 
  Returns a list of [`DOMQuad`](domquad) objects representing the CSS fragments of the node.

  [`Document.getElementById()`](document/getelementbyid)  Returns an object reference to the identified element.

  [`Document.getElementsByClassName()`](document/getelementsbyclassname)  Returns a list of elements with the given class name.

  [`Document.getElementsByTagName()`](document/getelementsbytagname)  Returns a list of elements with the given tag name.

  [`Document.getElementsByTagNameNS()`](document/getelementsbytagnamens)  Returns a list of elements with the given tag name and namespace.

  [`Document.getSelection()`](document/getselection)  Returns a [`Selection`](selection) object representing the range of text selected by the user, or the current position of the caret.

  [`Document.hasStorageAccess()`](document/hasstorageaccess)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with a boolean value indicating whether the document has access to its first-party storage.

  [`Document.importNode()`](document/importnode)  Returns a clone of a node from an external document.

  [`Document.prepend()`](document/prepend)  Inserts a set of [`Node`](node) objects or string objects before the first child of the document.

  [`Document.querySelector()`](document/queryselector)  Returns the first Element node within the document, in document order, that matches the specified selectors.

  [`Document.querySelectorAll()`](document/queryselectorall)  Returns a list of all the Element nodes within the document that match the specified selectors.

  
[`Document.releaseCapture()`](document/releasecapture)  Non-standard 
  Releases the current mouse capture if it's on an element in this document.

  
`Document.releaseEvents()`  Deprecated 
  See [`Window.releaseEvents()`](window/releaseevents).

  [`Document.replaceChildren()`](document/replacechildren)  Replaces the existing children of a document with a specified new set of children.

  [`Document.requestStorageAccess()`](document/requeststorageaccess)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves if the access to first-party storage was granted, and rejects if access was denied.

  
[`Document.startViewTransition()`](document/startviewtransition)  Experimental 
  Starts a new [view transition](view_transitions_api) and returns a [`ViewTransition`](viewtransition) object to represent it.

  
[`Document.mozSetImageElement()`](document/mozsetimageelement)  Non-standard 
  Allows you to change the element being used as the background image for a specified element ID.

   The `Document` interface is extended with the [`XPathEvaluator`](xpathevaluator) interface:

  [`Document.createExpression()`](document/createexpression)  Compiles an [`XPathExpression`](xpathexpression) which can then be used for (repeated) evaluations.

  [`Document.createNSResolver()`](document/creatensresolver)  Creates an [`XPathNSResolver`](xpathnsresolver) object.

  [`Document.evaluate()`](document/evaluate)  Evaluates an XPath expression.

  

### Extension for HTML documents



The `Document` interface for HTML documents inherit from the [`HTMLDocument`](htmldocument) interface or is extended for such documents:

  
[`Document.clear()`](document/clear)  Deprecated 
  This method does nothing.

  [`Document.close()`](document/close)  Closes a document stream for writing.

  
[`Document.execCommand()`](document/execcommand)  Deprecated 
  On an editable document, executes a formatting command.

  [`Document.getElementsByName()`](document/getelementsbyname)  Returns a list of elements with the given name.

  [`Document.hasFocus()`](document/hasfocus)  Returns `true` if the focus is currently located anywhere inside the specified document.

  [`Document.open()`](document/open)  Opens a document stream for writing.

  
[`Document.queryCommandEnabled()`](document/querycommandenabled)  Deprecated   Non-standard 
  Returns true if the formatting command can be executed on the current range.

  
`Document.queryCommandIndeterm()`  Deprecated 
  Returns true if the formatting command is in an indeterminate state on the current range.

  
[`Document.queryCommandState()`](document/querycommandstate)  Deprecated   Non-standard 
  Returns true if the formatting command has been executed on the current range.

  
[`Document.queryCommandSupported()`](document/querycommandsupported)  Deprecated   Non-standard 
  Returns true if the formatting command is supported on the current range.

  
`Document.queryCommandValue()`  Deprecated 
  Returns the current value of the current range for a formatting command.

  [`Document.write()`](document/write)  Writes text in a document.

  [`Document.writeln()`](document/writeln)  Writes a line of text in a document.

  

Events
------



Listen to these events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface.

  
[`afterscriptexecute`](document/afterscriptexecute_event)  Non-standard 
  Fired when a static [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) element finishes executing its script

  
[`beforescriptexecute`](document/beforescriptexecute_event)  Non-standard 
  Fired when a static [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) is about to start executing.

  `securitypolicyviolation`  Fired when a content security policy is violated.

  [`scroll`](document/scroll_event)  Fired when the document view or an element has been scrolled.

  [`visibilitychange`](document/visibilitychange_event)  Fired when the content of a tab has become visible or has been hidden.

  [`wheel`](element/wheel_event)  Fired when the user rotates a wheel button on a pointing device (typically a mouse).

  

### Animation events


 [`animationcancel`](element/animationcancel_event)  Fired when an animation unexpectedly aborts.

  [`animationend`](element/animationend_event)  Fired when an animation has completed normally.

  [`animationiteration`](element/animationiteration_event)  Fired when an animation iteration has completed.

  [`animationstart`](element/animationstart_event)  Fired when an animation starts.

  
### Clipboard events


 [`copy`](document/copy_event)  Fired when the user initiates a copy action through the browser's user interface.

  [`cut`](document/cut_event)  Fired when the user initiates a cut action through the browser's user interface.

  [`paste`](document/paste_event)  Fired when the user initiates a paste action through the browser's user interface.

  
### Drag & drop events


 [`drag`](htmlelement/drag_event)  Fired every few hundred milliseconds as an element or text selection is being dragged by the user.

  [`dragend`](htmlelement/dragend_event)  Fired when a drag operation is being ended (by releasing a mouse button or hitting the escape key).

  [`dragenter`](htmlelement/dragenter_event)  Fired when a dragged element or text selection enters a valid drop target.

  [`dragleave`](htmlelement/dragleave_event)  Fired when a dragged element or text selection leaves a valid drop target.

  [`dragover`](htmlelement/dragover_event)  Fired when an element or text selection is being dragged over a valid drop target (every few hundred milliseconds).

  [`dragstart`](htmlelement/dragstart_event)  Fired when the user starts dragging an element or text selection.

  [`drop`](htmlelement/drop_event)  Fired when an element or text selection is dropped on a valid drop target.

  
### Fullscreen events


 [`fullscreenchange`](document/fullscreenchange_event)  Fired when the `Document` transitions into or out of [fullscreen](fullscreen_api/guide) mode.

  [`fullscreenerror`](document/fullscreenerror_event)  Fired if an error occurs while attempting to switch into or out of [fullscreen](fullscreen_api/guide) mode.

  
### Keyboard events


 [`keydown`](element/keydown_event)  Fired when a key is pressed.

  
[`keypress`](element/keypress_event)  Deprecated 
  Fired when a key that produces a character value is pressed down.

  [`keyup`](element/keyup_event)  Fired when a key is released.

  
### Load & unload events


 [`DOMContentLoaded`](document/domcontentloaded_event)  Fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

  [`readystatechange`](document/readystatechange_event)  Fired when the [`readyState`](document/readystate) attribute of a document has changed.

  
### Pointer events


 [`gotpointercapture`](element/gotpointercapture_event)  Fired when an element captures a pointer using [`setPointerCapture()`](element/setpointercapture).

  [`lostpointercapture`](document/lostpointercapture_event)  Fired when a [captured pointer](pointer_events#pointer_capture) is released.

  [`pointercancel`](element/pointercancel_event)  Fired when a pointer event is canceled.

  [`pointerdown`](element/pointerdown_event)  Fired when a pointer becomes active.

  [`pointerenter`](element/pointerenter_event)  Fired when a pointer is moved into the hit test boundaries of an element or one of its descendants.

  [`pointerleave`](element/pointerleave_event)  Fired when a pointer is moved out of the hit test boundaries of an element.

  [`pointerlockchange`](document/pointerlockchange_event)  Fired when the pointer is locked/unlocked.

  [`pointerlockerror`](document/pointerlockerror_event)  Fired when locking the pointer failed.

  [`pointermove`](element/pointermove_event)  Fired when a pointer changes coordinates.

  [`pointerout`](element/pointerout_event)  Fired when a pointer is moved out of the *hit test* boundaries of an element (among other reasons).

  [`pointerover`](element/pointerover_event)  Fired when a pointer is moved into an element's hit test boundaries.

  [`pointerup`](element/pointerup_event)  Fired when a pointer is no longer active.

  
### Selection events


 [`selectionchange`](document/selectionchange_event)  Fired when the current text selection on a document is changed.

  
### Touch events


 [`touchcancel`](element/touchcancel_event)  Fired when one or more touch points have been disrupted in an implementation-specific manner (for example, too many touch points are created).

  [`touchend`](element/touchend_event)  Fired when one or more touch points are removed from the touch surface.

  [`touchmove`](element/touchmove_event)  Fired when one or more touch points are moved along the touch surface.

  [`touchstart`](element/touchstart_event)  Fired when one or more touch points are placed on the touch surface.

  
### Transition events


 [`transitioncancel`](element/transitioncancel_event)  Fired when a [CSS transition](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions) is canceled.

  [`transitionend`](element/transitionend_event)  Fired when a [CSS transition](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions) has completed.

  [`transitionrun`](element/transitionrun_event)  Fired when a [CSS transition](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions) is first created.

  [`transitionstart`](element/transitionstart_event)  Fired when a [CSS transition](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions) has actually started.

  
Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-document](https://dom.spec.whatwg.org/#interface-document) |
| [HTML Standard # the-document-object](https://html.spec.whatwg.org/multipage/dom.html#the-document-object) |
| [CSSOM View Module # extensions-to-the-document-interface](https://w3c.github.io/csswg-drafts/cssom-view/#extensions-to-the-document-interface) |
| [Pointer Lock 2.0 # extensions-to-the-document-interface](https://w3c.github.io/pointerlock/#extensions-to-the-document-interface) |
| [Selection API # extensions-to-document-interface](https://w3c.github.io/selection-api/#extensions-to-document-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DOMContentLoaded_event` | 1 | 12 | 1 | 9 | 9 | 3.1 | 4.4 | 18 | 4 | 10.1 | 2 | 1.0 |
| `Document` | 60 | 17 | 20 | No | 47 | 8 | 60 | 60 | 20 | 44 | 8 | 8.0 |
| `URL` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `Document` | 1 | 12 | 1 | 4 | 3 | 1 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 |
| `activeElement` | 2 | 12 | 3 | 6 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `adoptNode` | 1 | 12 | 1 | 9 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `adoptedStyleSheets` | 73 | 79 | 101 | No | 60 | 16.4 | 73 | 73 | 101 | 50 | 16.4 | 11.0 |
| `afterscriptexecute_event` | No | No | 9 | No | No | No | No | No | 9 | No | No | No |
| `alinkColor` | 641–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 12 | 1 | 4 | 51≤12.1–51Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 111.2–11Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 644.4–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 6418–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 4 | 47≤12.1–47Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 111–11Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 9.01.0–9.0Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. |
| `all` | 641–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 12 | 24 | 4 | 51≤12.1–51Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 113–11Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 64≤37–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 6418–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 24 | 47≤12.1–47Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 111–11Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 9.01.0–9.0Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. |
| `anchors` | 1 | 12 | 1 | 4 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `append` | 54 | 17 | 49 | No | 41 | 10 | 54 | 54 | 49 | 41 | 10 | 6.0 |
| `applets` | 1 | 12 | 1 | 4 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `beforescriptexecute_event` | No | No | 9 | No | No | No | No | No | 9 | No | No | No |
| `bgColor` | 641–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 12 | 1 | 4 | 51≤12.1–51Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 111–11Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 644.4–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 6418–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 4 | 47≤12.1–47Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 111–11Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 9.01.0–9.0Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. |
| `body` | 1 | 12 | 601–60Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 4 | 9.6 | 1 | 4.4 | 18 | 604–60Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 10.1 | 1 | 1.0 |
| `captureEvents` | 641–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 12 | 1 | 11 | 51≤12.1–51Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 111–11Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 644.4–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 6418–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 4 | 47≤12.1–47Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 111–11Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 9.01.0–9.0Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. |
| `caretPositionFromPoint` | No | No | 20 | No | No | No | No | No | 20 | No | No | No |
| `caretRangeFromPoint` | 4 | 12 | No | No | 15 | 5 | ≤37 | 18 | No | 14 | 4 | 1.0 |
| `characterSet` | 11`charset` alias was made read-only in Chrome 45.1 | 121212 | 441.51 | 994 | 15`charset` alias was made read-only in Opera 45.15≤12.1 | 333 | 11`charset` alias was made read-only in WebView 45.1 | 1818`charset` alias was made read-only in Chrome 45.18 | 4444 | 14`charset` alias was made read-only in Opera 45.14≤12.1 | 111 | 1.01.0`charset` alias was made read-only in Samsung Internet 5.0.1.0 |
| `childElementCount` | 29 | 17 | 25 | No | 16 | 9 | 4.4 | 29 | 25 | 16 | 9 | 2.0 |
| `children` | 29 | 16 | 25 | No | 16 | 9 | 4.4 | 29 | 25 | 16 | 9 | 2.0 |
| `clear` | 641–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 12 | 1 | 4 | 51≤12.1–51Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 1 | 644.4–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 6418–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 4 | 47≤12.1–47Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 1 | 9.01.0–9.0Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. |
| `close` | 641–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 12 | 1 | 4 | 51≤12.1–51Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 111–11Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 644.4–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 6418–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 4 | 47≤12.1–47Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 111–11Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 9.01.0–9.0Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. |
| `compatMode` | 1 | 12 | 1 | 6 | ≤12.1 | 3.1 | 4.4 | 18 | 4 | ≤12.1 | 2 | 1.0 |
| `contentType` | 36 | 17 | 1 | No | 23≤12.1–15 | 9 | 37 | 36 | 4 | 24≤12.1–14 | 9 | 3.0 |
| `cookie` | 1 | 12 | 1Before Firefox 68, `cookie` was available only on HTML documents; it is now available on all documents, such as XML and SVG. | 4 | 3 | 1 | 4.4 | 18 | 4Before Firefox 68, `cookie` was available only on HTML documents; it is now available on all documents, such as XML and SVG. | 10.1 | 1 | 1.0 |
| `createAttribute` | 1 | 12 | 441–44The parameter was not converted to its lowercase variant. | 6 | ≤12.1 | 1 | 4.4 | 18 | 444–44The parameter was not converted to its lowercase variant. | ≤12.1 | 1 | 1.0 |
| `createAttributeNS` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `createCDATASection` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `createComment` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `createDocumentFragment` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `createElement` | 1 | 12 | 1Doesn't conform to the DOM spec for XUL and XHTML documents: `localName` and `namespaceURI` are not set to null on the created element. | 5 | 6 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `createElementNS` | 1 | 12 | 1Doesn't conform to the DOM spec for XUL and XHTML documents: `localName` and `namespaceURI` are not set to null on the created element. | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `createEvent` | 1 | 12 | 1From version 67, creating touch events using this method is no longer supported. | 9 | 7 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `createExpression` | 1 | 12 | 1 | No | ≤12.1 | 3 | 3 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `createNSResolver` | 1 | 12 | 1 | No | ≤12.1 | 3 | 3 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `createNodeIterator` | 1 | 12 | 1 | 9 | 9 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `createProcessingInstruction` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `createRange` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `createTextNode` | 1 | 12 | 1 | 5 | 7 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `createTouch` | No | No | 18–67 | No | No | No | 4.4–68Since Chrome 55, all parameters are optional. | 25–68Since Chrome 55, all parameters are optional. | 6 | 14–48Since Opera Android 42, all parameters are optional. | ≤3 | 1.5–10.0Since Samsung Internet 6.0, all parameters are optional. |
| `createTouchList` | 22–69 | No | 18–67 | No | 15–56 | No | 4.4–69 | 25–69 | 6 | 14–48 | ≤3 | 1.5–10.0 |
| `createTreeWalker` | 1 | 12 | 1 | 9 | 9 | 3 | 4.4 | 18 | 4 | 10.1 | 3 | 1.0 |
| `currentScript` | 29 | 12 | 4 | No | 16 | 8 | 4.4 | 29 | 4 | 16 | 8 | 2.0 |
| `defaultView` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `designMode` | 1 | 12 | 1 | 4 | 9 | 1.2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `dir` | 641–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 12 | 1Incorrect behavior before Firefox 23. | 5 | 51≤12.1–51Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 10.11–10.1Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 644.4–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 6418–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 4Incorrect behavior before Firefox 23. | 47≤12.1–47Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 10.31–10.3Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 9.01.0–9.0Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. |
| `doctype` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `documentElement` | 1 | 12 | 1 | 5 | 7 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `documentURI` | 1 | 17 | 1 | No | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `domain` | 1From Chrome 110, `domain` is available by opt-in via `Origin-keyed agent clusters` . See this [chromestatus entry](https://chromestatus.com/feature/5428079583297536). | 12 | 1From Firefox 62, if the domain cannot be identified, `domain` returns an empty string instead of `null`. See [bug 819475](https://bugzil.la/819475). | 4 | ≤12.1 | 1 | 4.4From Chrome 110, `domain` is available by opt-in via `Origin-keyed agent clusters` . See this [chromestatus entry](https://chromestatus.com/feature/5428079583297536). | 18From Chrome 110, `domain` is available by opt-in via `Origin-keyed agent clusters` . See this [chromestatus entry](https://chromestatus.com/feature/5428079583297536). | 4From Firefox 62, if the domain cannot be identified, `domain` returns an empty string instead of `null`. See [bug 819475](https://bugzil.la/819475). | ≤12.1 | 1 | 1.0From Samsung Internet false, `domain` is available by opt-in via `Origin-keyed agent clusters` . See this [chromestatus entry](https://chromestatus.com/feature/5428079583297536). |
| `elementFromPoint` | 1Before Chrome 66, this method returned `null` when the element was a child of a host node. See [issue 759947](https://crbug.com/759947). | 12 | 3 | 4 | ≤12.1Before Opera 53, this method returned `null` when the element was a child of a host node. See [issue 759947](https://crbug.com/759947). | 4 | ≤37Before WebView 66, this method returned `null` when the element was a child of a host node. See [issue 759947](https://crbug.com/759947). | 18Before Chrome 66, this method returned `null` when the element was a child of a host node. See [issue 759947](https://crbug.com/759947). | 4 | ≤12.1Before Opera Android 47, this method returned `null` when the element was a child of a host node. See [issue 759947](https://crbug.com/759947). | 3.2 | 1.0Before Samsung Internet 9.0, this method returned `null` when the element was a child of a host node. See [issue 759947](https://crbug.com/759947). |
| `elementsFromPoint` | 43Before Chrome 66, this method returned `null` when the element was a child of a host node. See [issue 759947](https://crbug.com/759947). | 7912–79Returns a `NodeList` instead of an array. See [the MSDN documentation](https://msdn.microsoft.com/en-us/library/hh772121(v=vs.85).aspx). Returns `null` when the point provided has no elements beneath it (e.g., when given a point outside the document). | 46 | 10Returns a `NodeList` instead of an array. See [the MSDN documentation](https://msdn.microsoft.com/en-us/library/hh772121(v=vs.85).aspx). Returns `null` when the point provided has no elements beneath it (e.g., when given a point outside the document). | 30 | 11.1 | 43Before Chrome 66, this method returned `null` when the element was a child of a host node. See [issue 759947](https://crbug.com/759947). | 43Before Chrome 66, this method returned `null` when the element was a child of a host node. See [issue 759947](https://crbug.com/759947). | 46 | 30 | 11.3 | 4.0Before Samsung Internet 9.0, this method returned `null` when the element was a child of a host node. See [issue 759947](https://crbug.com/759947). |
| `embeds` | 641–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 12 | 1 | 4 | 51≤12.1–51Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 10.12–10.1Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 644.4–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 6418–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 4 | 47≤12.1–47Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 10.31–10.3Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 9.01.0–9.0Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. |
| `enableStyleSheetsForSet` | No | No | 3 | No | No | No | No | No | 4 | No | No | No |
| `evaluate` | 1 | 12 | 1 | No | 9 | 3 | 3 | 18 | 4 | 10.1 | 1 | 1.0 |
| `execCommand` | 1 | 12 | 1["From Firefox 82, nested calls are not supported (return `false`). See [bug 1634262](https://bugzil.la/1634262).", "Before Firefox 89, manipulating the content of `<input>` and `<textarea>` elements using `Document.execCommand()` commands requires workarounds (see [bug 1220696](https://bugzil.la/1220696))."] | 4 | 9 | 1.3 | 4.4 | 18 | 4["From Firefox 82, nested calls are not supported (return `false`). See [bug 1634262](https://bugzil.la/1634262).", "Before Firefox 89, manipulating the content of `<input>` and `<textarea>` elements using `Document.execCommand()` commands requires workarounds (see [bug 1220696](https://bugzil.la/1220696))."] | 10.1 | 1 | 1.0 |
| `exitFullscreen` | 7115 | 791212–14 | 649 | 11 | 581512.1–15 | 16.45.1 | 71≤37 | 7118 | 649 | 501412.1–14 | 12Only available on iPad, not on iPhone. | 10.01.0 |
| `exitPictureInPicture` | 69 | 79 | No | No | 56 | 13.1 | No | 105 | No | 72 | 13.4 | 20.0 |
| `exitPointerLock` | 3722 | 13 | 5014–50 | No | 2415 | 10.1 | 374.4 | 3725 | 5014–50 | 2414 | No | 3.01.5 |
| `featurePolicy` | 74 | 79 | 69 | No | 62 | No | 74 | 74 | No | 53 | No | 11.0 |
| `fgColor` | 641–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 12 | 1 | 4 | 51≤12.1–51Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 111–11Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 644.4–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 6418–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 4 | 47≤12.1–47Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 111–11Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 9.01.0–9.0Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. |
| `firstElementChild` | 29 | 17 | 25 | No | 16 | 9 | 4.4 | 29 | 25 | 16 | 9 | 2.0 |
| `fonts` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 3.0 |
| `forms` | 1 | 12 | 1 | 4 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `fragmentDirective` | 86 | 86 | No | No | 72 | No | 86 | 86 | No | 61 | No | 14.0 |
| `freeze_event` | 68 | 79 | No | No | 55 | No | 68 | 68 | No | 48 | No | 10.0 |
| `fullscreen` | 7115 | 7912 | 649 | No | 5815 | 16.46 | 71≤37 | 7118 | 649 | 5014 | 12Only available on iPad, not on iPhone. | 10.01.0 |
| `fullscreenElement` | 7120 | 791212–14 | 649 | 11 | 581512.1–15 | 16.46 | 714.4 | 7125 | 649 | 501412.1–14 | 16.4Only available on iPad, not on iPhone.12Only available on iPad, not on iPhone. | 10.01.5 |
| `fullscreenEnabled` | 7120 | 12 | 6410 | 11 | 581512.1–15 | 16.46 | 714.4 | 7125 | 6410 | 501412.1–14 | 12Only available on iPad, not on iPhone. | 10.01.5 |
| `fullscreenchange_event` | 7115 | 791212–14 | 6410 | 11 | 581512.1–15 | 16.45.1 | 71≤37 | 7118 | 6410 | 501412.1–14 | 12Only available on iPad, not on iPhone. | 10.01.0 |
| `fullscreenerror_event` | 7118 | 791212–14 | 6410 | 11 | 581512.1–15 | 16.46 | 71≤37 | 7118 | 6410 | 501412.1–14 | 12Only available on iPad, not on iPhone. | 10.01.0 |
| `getAnimations` | 84 | 84 | 75 | No | 70 | 1413.1Implements an older version of the specification, see Webkit bug [179536](https://webkit.org/b/179536). | 84 | 84 | 79 | 60 | 1413.4Implements an older version of the specification, see Webkit bug [179536](https://webkit.org/b/179536). | 14.0 |
| `getBoxQuads` | No | No | 31 | No | No | No | No | No | No | No | No | No |
| `getElementById` | 1 | 12 | 1 | 5.5 | 7 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `getElementsByClassName` | 1 | 12 | 3 | 9 | 9.5 | 3.1 | 4.4 | 18 | 4 | 10.1 | 2 | 1.0 |
| `getElementsByName` | 1 | 12Before Edge 79, this method returns an `HTMLCollection`, not a `NodeList`. | 1 | 5Returns an `HTMLCollection`, not a `NodeList` | 5 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `getElementsByTagName` | 1 | 12 | 1 | 5 | 5.1 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `getElementsByTagNameNS` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `getSelection` | 2 | 12 | 1 | 9 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `hasFocus` | 2 | 12 | 3 | 5.5 | 15 | 4 | ≤37 | 18 | 4 | 14 | 3.2 | 1.0 |
| `hasStorageAccess` | 78See [bug 989663](https://crbug.com/989663). | 85 | 65 | No | 65 | 11.1 | No | 78See [bug 989663](https://crbug.com/989663). | 65 | No | 11.3 | No |
| `head` | 4 | 12 | 4 | 9 | 11 | 5 | ≤37 | 18 | 4 | 11 | 4 | 1.0 |
| `hidden` | 3313 | 12 | 18Since Firefox 56 it also returns `true` on macOS when the window is completely hidden by another non-translucent application.10–52 | 10 | 12.1 | 7 | ≤374.4.3 | 3318 | 18Since Firefox 56 it also returns `true` on macOS when the window is completely hidden by another non-translucent application.10–52 | 12.1 | 7 | 2.01.0 |
| `images` | 1 | 12 | 1 | 4 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `implementation` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `importNode` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `lastElementChild` | 29 | 17 | 25 | No | 16 | 9 | 4.4 | 29 | 25 | 16 | 9 | 2.0 |
| `lastModified` | 1 | 12 | 1 | 4 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `lastStyleSheetSet` | No | No | 3 | No | No | No | No | No | 4 | No | No | No |
| `linkColor` | 641–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 12 | 1 | 4 | 51≤12.1–51Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 111–11Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 644.4–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 6418–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 4 | 47≤12.1–47Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 111–11Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 9.01.0–9.0Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. |
| `links` | 1 | 12 | 1 | 4 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `location` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `lostpointercapture_event` | 57 | 17 | 59 | No | 44 | 13 | 57 | 57 | 79 | 43 | 13 | 7.0 |
| `mozSetImageElement` | No | No | 4 | No | No | No | No | No | 4 | No | No | No |
| `open` | 641–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 12 | 1 | 4 | 51≤12.1–51Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 111–11Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 644.4–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 6418–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 4 | 47≤12.1–47Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 111–11Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 9.01.0–9.0Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. |
| `pictureInPictureElement` | 69 | 79 | No | No | 56 | 13.1 | No | 105 | No | 72 | 13.4 | 20.0 |
| `pictureInPictureEnabled` | 69 | 79 | No | No | 56 | 13.1 | No | 105 | No | 72 | 13.4 | 20.0 |
| `plugins` | 641–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 12 | 1 | 4 | 51≤12.1–51Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 10.13–10.1Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 644.4–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 6418–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 4 | 47≤12.1–47Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 10.31–10.3Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 9.01.0–9.0Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. |
| `pointerLockElement` | 37 | 13 | 5014–50 | No | 24 | 10.1 | 37 | 37 | 5014–50 | 24 | No | 3.0 |
| `pointerlockchange_event` | 3622–38 | 13 | 5014–50 | No | 2315–25 | 10.1 | 374.4–38 | 3625–38 | 5014–50 | 2414–25 | No | 3.01.5–3.0 |
| `pointerlockerror_event` | 3622–38 | 13 | 5014–50 | No | 2315–25 | 10.1 | 374.4–38 | 3625–38 | 5014–50 | 2414–25 | No | 3.01.5–3.0 |
| `preferredStyleSheetSet` | No | No | 3 | No | No | No | No | No | 4 | No | No | No |
| `prepend` | 54 | 17 | 49 | No | 41 | 10 | 54 | 54 | 49 | 41 | 10 | 6.0 |
| `prerendering` | 108 | 108 | No | No | 94 | No | 108 | 108 | No | 73 | No | No |
| `prerenderingchange_event` | 108 | 108 | No | No | 94 | No | 108 | 108 | No | 73 | No | No |
| `queryCommandEnabled` | 1 | 12 | 411–41`queryCommandEnabled` with arguments `cut`, `copy` or `paste` would throw errors unless the script had special privileges. | 4 | ≤12.1 | 2 | 4.4 | 18 | 414–41`queryCommandEnabled` with arguments `cut`, `copy` or `paste` would throw errors unless the script had special privileges. | ≤12.1 | 1 | 1.0 |
| `queryCommandIndeterm` | 1 | 12 | 1 | 4 | 15 | 2 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `queryCommandState` | 1 | 12 | 1 | 4 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `queryCommandSupported` | 1 | 12 | 411–41The `"paste"` command is reported as supported when the paste feature is available even if the calling script has insufficient privileges to actually perform the action. | 4 | ≤12.1 | 2 | 4.4 | 18 | 414–41The `"paste"` command is reported as supported when the paste feature is available even if the calling script has insufficient privileges to actually perform the action. | ≤12.1 | 1 | 1.0 |
| `queryCommandValue` | 1 | 12 | 1 | 4 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `querySelector` | 1 | 12 | 3.5 | 98`querySelectorAll()` is supported, but only for CSS 2.1 selectors. | 10 | 3.1 | 4.4 | 18 | 4 | 10.1 | 2 | 1.0 |
| `querySelectorAll` | 1 | 12 | 3.5 | 98`querySelectorAll()` is supported, but only for CSS 2.1 selectors. | 10 | 3.1 | 4.4 | 18 | 4 | 10.1 | 2 | 1.0 |
| `readyState` | 1 | 12 | 3.6 | 119–11Internet Explorer 9 and 10 have bugs where the 'interactive' state can be fired too early before the document has finished parsing.4–9Only supports 'complete'. | 11Opera Presto fires 'complete' late after the 'load' event (in an incorrect order as per HTML5 standard specification). | 1 | 4.4 | 18 | 4 | 11Opera Presto fires 'complete' late after the 'load' event (in an incorrect order as per HTML5 standard specification). | 1 | 1.0 |
| `readystatechange_event` | 9 | 12 | 4 | 4 | ≤12.1 | 5.1 | ≤37 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `referrer` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `releaseCapture` | No | No | 4 | 5 | No | No | No | No | 4 | No | No | No |
| `releaseEvents` | 641–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 12 | 1 | 11 | 51≤12.1–51Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 111–11Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 644.4–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 6418–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 4 | 47≤12.1–47Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 111–11Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 9.01.0–9.0Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. |
| `replaceChildren` | 86 | 86 | 78 | No | 72 | 14 | 86 | 86 | 79 | 61 | 14 | 14.0 |
| `requestStorageAccess` | 78See [bug 989663](https://crbug.com/989663). | 85 | 65 | No | 65 | 11.1 | No | 78See [bug 989663](https://crbug.com/989663). | 65 | No | 11.3 | No |
| `resume_event` | 68 | 79 | No | No | 55 | No | 68 | 68 | No | 48 | No | 10.0 |
| `rootElement` | 34 | 12 | 52 | 9 | 21 | 10.1 | 37 | 34 | 52 | 21 | 10.3 | 2.0 |
| `scripts` | 1 | 12 | 9 | 4 | ≤12.1 | 3 | 4.4 | 18 | 9 | ≤12.1 | 1 | 1.0 |
| `scroll_event` | 1 | 12 | 6 | 9 | 11.6 | 2 | 4.4 | 18 | 6 | 12 | 1 | 1.0 |
| `scrollend_event` | preview | No | 109 | No | No | No | No | No | 109 | No | No | No |
| `scrollingElement` | 44 | 12 | 48 | No | 31 | 9 | 44 | 44 | 48 | 32 | 9 | 4.0 |
| `securitypolicyviolation_event` | 76 | 79 | 93 | No | 63 | 15.4 | 76 | 76 | 93 | 54 | 15.4 | 12.0 |
| `selectedStyleSheetSet` | No | No | 3 | No | No | No | No | No | 4 | No | No | No |
| `selectionchange_event` | 11 | 12 | 52 | 5.5 | 15 | 5.1 | ≤37 | 18 | 52 | 14 | 5 | 1.0 |
| `startViewTransition` | 111 | 111 | No | No | 97 | No | 111 | 111 | No | No | No | No |
| `styleSheetSets` | No | No | 3 | No | No | No | No | No | 4 | No | No | No |
| `styleSheets` | 1 | 12 | 1 | 4 | ≤12.1 | 4 | 4.4 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `timeline` | 84 | 84 | 75 | No | 70 | 13.1 | 84 | 84 | 79 | 60 | 13.4 | 14.0 |
| `title` | 1 | 12 | 1 | 4 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `visibilityState` | 3313 | 12 | 1810–52 | 10 | 201512.1–15 | 7 | ≤374.4.3 | 3318 | 1810–52 | 201412.1–14 | 7 | 2.01.0 |
| `visibilitychange_event` | 6233The `onvisibilitychange` event handler property is not supported.13The `onvisibilitychange` event handler property is not supported. | 1812The `onvisibilitychange` event handler property is not supported. | 56 | 10The `onvisibilitychange` event handler property is not supported. | 4920The `onvisibilitychange` event handler property is not supported.15The `onvisibilitychange` event handler property is not supported.12.1–15The `onvisibilitychange` event handler property is not supported. | 14.114Doesn't fire the `visibilitychange` event when navigating away from a document, so also include code to check for the `pagehide` event (which does fire for that case in all current browsers). See WebKit bugs [116769](https://webkit.org/b/116769), [151234](https://webkit.org/b/151234), [151610](https://webkit.org/b/151610), and [194897](https://webkit.org/b/194897).10.1["Doesn't fire the `visibilitychange` event when navigating away from a document, so also include code to check for the `pagehide` event (which does fire for that case in all current browsers). See WebKit bugs [116769](https://webkit.org/b/116769), [151234](https://webkit.org/b/151234), [151610](https://webkit.org/b/151610), and [194897](https://webkit.org/b/194897).", "Before Safari 14, the event does not bubble, so `document.addEventListener('visibilitychange', ...)` works, but `window.addEventListener('visibilitychange', ...)` does not."]7["Doesn't fire the `visibilitychange` event when navigating away from a document, so also include code to check for the `pagehide` event (which does fire for that case in all current browsers). See WebKit bugs [116769](https://webkit.org/b/116769), [151234](https://webkit.org/b/151234), [151610](https://webkit.org/b/151610), and [194897](https://webkit.org/b/194897).", "Before Safari 14, the event does not bubble, so `document.addEventListener('visibilitychange', ...)` works, but `window.addEventListener('visibilitychange', ...)` does not.", "The `onvisibilitychange` event handler property is not supported."] | 62≤37The `onvisibilitychange` event handler property is not supported.4.4.3The `onvisibilitychange` event handler property is not supported. | 6233The `onvisibilitychange` event handler property is not supported.18The `onvisibilitychange` event handler property is not supported. | 56 | 4620The `onvisibilitychange` event handler property is not supported.14The `onvisibilitychange` event handler property is not supported.12.1–14The `onvisibilitychange` event handler property is not supported. | 14.514Doesn't fire the `visibilitychange` event when navigating away from a document, so also include code to check for the `pagehide` event (which does fire for that case in all current browsers). See WebKit bugs [116769](https://webkit.org/b/116769), [151234](https://webkit.org/b/151234), [151610](https://webkit.org/b/151610), and [194897](https://webkit.org/b/194897).10.3["Doesn't fire the `visibilitychange` event when navigating away from a document, so also include code to check for the `pagehide` event (which does fire for that case in all current browsers). See WebKit bugs [116769](https://webkit.org/b/116769), [151234](https://webkit.org/b/151234), [151610](https://webkit.org/b/151610), and [194897](https://webkit.org/b/194897).", "Before Safari 14, the event does not bubble, so `document.addEventListener('visibilitychange', ...)` works, but `window.addEventListener('visibilitychange', ...)` does not."]7["Doesn't fire the `visibilitychange` event when navigating away from a document, so also include code to check for the `pagehide` event (which does fire for that case in all current browsers). See WebKit bugs [116769](https://webkit.org/b/116769), [151234](https://webkit.org/b/151234), [151610](https://webkit.org/b/151610), and [194897](https://webkit.org/b/194897).", "Before Safari 14, the event does not bubble, so `document.addEventListener('visibilitychange', ...)` works, but `window.addEventListener('visibilitychange', ...)` does not.", "The `onvisibilitychange` event handler property is not supported."] | 8.02.0The `onvisibilitychange` event handler property is not supported.1.0The `onvisibilitychange` event handler property is not supported. |
| `vlinkColor` | 641–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 12 | 1 | 4 | 51≤12.1–51Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 111–11Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 644.4–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 6418–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 4 | 47≤12.1–47Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 111–11Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 9.01.0–9.0Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. |
| `wasDiscarded` | 68 | 79 | No | No | 55 | No | 68 | 68 | No | 48 | No | 10.0 |
| `write` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `writeln` | 641–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 12 | 1 | 4 | 51≤12.1–51Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 111–11Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 644.4–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 6418–64Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 4 | 47≤12.1–47Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 111–11Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. | 9.01.0–9.0Only supported for [`HTMLDocument`](https://developer.mozilla.org/docs/Web/API/HTMLDocument), not all `Document` objects. |
| `xmlEncoding` | 1 | 12 | 1–10 | 9 | 15 | 3 | 4.4 | 18 | 4–10 | 14 | 1 | 1.0 |
| `xmlStandalone` | 1 | 12 | 1–10 | 9 | 15 | 3 | 4.4 | 18 | 4–10 | 14 | 1 | 1.0 |
| `xmlVersion` | 1 | 12 | 1–10 | 9 | 15 | 3 | 4.4 | 18 | 4–10 | 14 | 1 | 1.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Document>

DOMPointReadOnly
================



The `DOMPointReadOnly` interface specifies the coordinate and perspective fields used by [`DOMPoint`](dompoint) to define a 2D or 3D point in a coordinate system.


 **Note:** This feature is available in [Web Workers](web_workers_api)

  There are two ways to create a new `DOMPointReadOnly` instance. First, you can use its constructor, passing in the values of the parameters for each dimension and, optionally, the perspective:

 
```
/\* 2D \*/
const point2D = new DOMPointReadOnly(50, 50);

/\* 3D \*/
const point3D = new DOMPointReadOnly(50, 50, 25);

/\* 3D with perspective \*/
const point3DPerspective = new DOMPointReadOnly(100, 100, 100, 1.0);

```
 The other option is to use the static [`DOMPointReadOnly.fromPoint()`](dompointreadonly/frompoint) method:

 
```
const point = DOMPointReadOnly.fromPoint({ x: 100, y: 100, z: 50, w: 1.0 });

```


Constructor
-----------


 [`DOMPointReadOnly()`](dompointreadonly/dompointreadonly)  Creates a new `DOMPointReadOnly` object given the values of its coordinates and perspective. To create a point using an object, you can instead use [`DOMPointReadOnly.fromPoint()`](dompointreadonly/frompoint).

  
Instance properties
-------------------


 
[`DOMPointReadOnly.x`](dompointreadonly/x) Read only 
  The point's horizontal coordinate, `x`.

  
[`DOMPointReadOnly.y`](dompointreadonly/y) Read only 
  The point's vertical coordinate, `y`.

  
[`DOMPointReadOnly.z`](dompointreadonly/z) Read only 
  The point's depth coordinate, `z`.

  
[`DOMPointReadOnly.w`](dompointreadonly/w) Read only 
  The point's perspective value, `w`.

  
Static methods
--------------


 [`DOMPointReadOnly.fromPoint()`](dompointreadonly/frompoint)  A static method that creates a new `DOMPointReadOnly` object given the coordinates provided in the specified object.

  
Instance methods
----------------


 `matrixTransform()`  Applies a matrix transform specified as an object to the `DOMPointReadOnly` object.

  [`toJSON()`](dompointreadonly/tojson)  Returns a JSON representation of the `DOMPointReadOnly` object.

  
Specifications
--------------




| Specification |
| --- |
| [Geometry Interfaces Module Level 1 # DOMPoint](https://drafts.fxtf.org/geometry/#DOMPoint) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DOMPointReadOnly` | 61 | 79 | 62 | No | 48 | 10.1 | 61 | 61 | 62 | 45 | 10.3 | 8.0 |
| `DOMPointReadOnly` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |
| `fromPoint` | 61 | 79 | 62 | No | 48 | 10.1 | 61 | 61 | 62 | 45 | 10.3 | 8.0 |
| `matrixTransform` | 61 | 79 | 69 | No | 48 | 11 | 61 | 61 | 79 | 45 | 11 | 8.0 |
| `toJSON` | 61 | 79 | 62 | No | 48 | 10.1 | 61 | 61 | 62 | 45 | 10.3 | 8.0 |
| `w` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |
| `worker_support` | 61 | 79 | 69 | No | 48 | 10.1 | 61 | 61 | 79 | 45 | 10.3 | 8.0 |
| `x` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |
| `y` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |
| `z` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |


See also
--------


* [`DOMPoint`](dompoint)
* [`DOMRect`](domrect)
* [`DOMMatrix`](dommatrix)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DOMPointReadOnly>

DOMQuad
=======


A `DOMQuad` is a collection of four `DOMPoint`s defining the corners of an arbitrary quadrilateral. Returning `DOMQuad`s lets `getBoxQuads()` return accurate information even when arbitrary 2D or 3D transforms are present. It has a handy `bounds` attribute returning a `DOMRectReadOnly` for those cases where you just want an axis-aligned bounding rectangle.


Constructor
-----------


 `DOMQuad()`  Creates a new `DOMQuad` object.

  
Instance properties
-------------------


 p1,p2,p3,p4 Read only 
  are [`DOMPoint`](dompoint) objects for each of the `DOMQuad` object's four corners.

  
Instance methods
----------------


 `DOMQuad.fromRect()`  Returns a new `DOMQuad` object based on the passed set of coordinates.

  `DOMQuad.fromQuad()`  Returns a new `DOMQuad` object based on the passed set of coordinates.

  `DOMQuad.getBounds()`  Returns a [`DOMRect`](domrect) object with the coordinates and dimensions of the `DOMQuad` object.

  `DOMQuad.toJSON()`  Returns a JSON representation of the `DOMQuad` object.

  
Specifications
--------------




| Specification |
| --- |
| [Geometry Interfaces Module Level 1 # DOMQuad](https://drafts.fxtf.org/geometry/#DOMQuad) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DOMQuad` | 61 | 79 | 31 | No | 48 | 11 | 61 | 61 | 31 | 45 | 11 | 8.0 |
| `DOMQuad` | 61 | 79 | 31 | No | 48 | 11 | 61 | 61 | 31 | 45 | 11 | 8.0 |
| `fromQuad` | 61 | 79 | 69 | No | 48 | 11 | 61 | 61 | 79 | 45 | 11 | 8.0 |
| `fromRect` | 61 | 79 | 69 | No | 48 | 11 | 61 | 61 | 79 | 45 | 11 | 8.0 |
| `getBounds` | 61 | 79 | 62 | No | 48 | 11 | 61 | 61 | 62 | 45 | 11 | 8.0 |
| `p1` | 61 | 79 | 31Before Firefox 69, the default value of `p1` through `p4` was undefined; now `DOMQuadInit` defines these as `false`. | No | 48 | 11 | 61 | 61 | 31Before Firefox for Android 79, the default value of `p1` through `p4` was undefined; now `DOMQuadInit` defines these as `false`. | 45 | 11 | 8.0 |
| `p2` | 61 | 79 | 31Before Firefox 69, the default value of `p1` through `p4` was undefined; now `DOMQuadInit` defines these as `false`. | No | 48 | 11 | 61 | 61 | 31Before Firefox for Android 79, the default value of `p1` through `p4` was undefined; now `DOMQuadInit` defines these as `false`. | 45 | 11 | 8.0 |
| `p3` | 61 | 79 | 31Before Firefox 69, the default value of `p1` through `p4` was undefined; now `DOMQuadInit` defines these as `false`. | No | 48 | 11 | 61 | 61 | 31Before Firefox for Android 79, the default value of `p1` through `p4` was undefined; now `DOMQuadInit` defines these as `false`. | 45 | 11 | 8.0 |
| `p4` | 61 | 79 | 31Before Firefox 69, the default value of `p1` through `p4` was undefined; now `DOMQuadInit` defines these as `false`. | No | 48 | 11 | 61 | 61 | 31Before Firefox for Android 79, the default value of `p1` through `p4` was undefined; now `DOMQuadInit` defines these as `false`. | 45 | 11 | 8.0 |
| `toJSON` | 61 | 79 | 62 | No | 48 | 11 | 61 | 61 | 62 | 45 | 11 | 8.0 |
| `worker_support` | 61 | 79 | 69 | No | 48 | 11 | 61 | 61 | 79 | 45 | 11 | 8.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DOMQuad>

DOMRect
=======



A `DOMRect` describes the size and position of a rectangle.

 The type of box represented by the `DOMRect` is specified by the method or property that returned it. For example, [`Range.getBoundingClientRect()`](range/getboundingclientrect) specifies the rectangle that bounds the content of the range using such objects.

 It inherits from its parent, [`DOMRectReadOnly`](domrectreadonly).


 DOMRectReadOnly DOMRect

Constructor
-----------


 [`DOMRect()`](domrect/domrect)  Creates a new `DOMRect` object.

  
Instance properties
-------------------



*`DOMRect` inherits properties from its parent, [`DOMRectReadOnly`](domrectreadonly). The difference is that they are not read-only anymore.*

  [`DOMRectReadOnly.x`](domrectreadonly/x)  The x coordinate of the `DOMRect`'s origin (typically the top-left corner of the rectangle).

  [`DOMRectReadOnly.y`](domrectreadonly/y)  The y coordinate of the `DOMRect`'s origin (typically the top-left corner of the rectangle).

  [`DOMRectReadOnly.width`](domrectreadonly/width)  The width of the `DOMRect`.

  [`DOMRectReadOnly.height`](domrectreadonly/height)  The height of the `DOMRect`.

  [`DOMRectReadOnly.top`](domrectreadonly/top)  Returns the top coordinate value of the `DOMRect` (has the same value as `y`, or `y + height` if `height` is negative).

  [`DOMRectReadOnly.right`](domrectreadonly/right)  Returns the right coordinate value of the `DOMRect` (has the same value as `x + width`, or `x` if `width` is negative).

  [`DOMRectReadOnly.bottom`](domrectreadonly/bottom)  Returns the bottom coordinate value of the `DOMRect` (has the same value as `y + height`, or `y` if `height` is negative).

  [`DOMRectReadOnly.left`](domrectreadonly/left)  Returns the left coordinate value of the `DOMRect` (has the same value as `x`, or `x + width` if `width` is negative).

  

Static methods
--------------



*`DOMRect` may also inherit static methods from its parent, [`DOMRectReadOnly`](domrectreadonly).*

  [`DOMRect.fromRect()`](domrect/fromrect)  Creates a new `DOMRect` object with a given location and dimensions.

  

Instance methods
----------------


*`DOMRect` may inherit methods from its parent, [`DOMRectReadOnly`](domrectreadonly).*


Specifications
--------------




| Specification |
| --- |
| [Geometry Interfaces Module Level 1 # DOMRect](https://drafts.fxtf.org/geometry/#DOMRect) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DOMRect` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |
| `DOMRect` | 612–61 | 7912–79 | 273–27 | 4 | 489.5–48 | 10.14–11 | 612–61 | 6118–61 | 274–27 | 4510.1–45 | 10.33.2–11 | 8.01.0–8.0 |
| `fromRect` | 61 | 79 | 69 | No | 48 | 10.1 | 61 | 61 | 79 | 45 | 10.3 | 8.0 |
| `height` | 2 | 12 | 3 | 4 | 9.5 | 4 | 2 | 18 | 4 | 10.1 | 3.2 | 1.0 |
| `width` | 2 | 12 | 3 | 4 | 9.5 | 4 | 2 | 18 | 4 | 10.1 | 3.2 | 1.0 |
| `worker_support` | 61 | 79 | 69 | No | 48 | 10.1 | 61 | 61 | No | 45 | 10.3 | 8.0 |
| `x` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |
| `y` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |


See also
--------


* [`DOMPoint`](dompoint)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DOMRect>

DOMRectReadOnly
===============


The `DOMRectReadOnly` interface specifies the standard properties used by [`DOMRect`](domrect) to define a rectangle whose properties are immutable.


Constructor
-----------


 [`DOMRectReadOnly()`](domrectreadonly/domrectreadonly)  Defined to create a new `DOMRectReadOnly` object. Note that this constructor cannot be called by 3rd party JavaScript; doing so returns an `"Illegal constructor"` [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError).

  
Instance properties
-------------------


 
[`DOMRectReadOnly.x`](domrectreadonly/x) Read only 
  The x coordinate of the `DOMRect`'s origin.

  
[`DOMRectReadOnly.y`](domrectreadonly/y) Read only 
  The y coordinate of the `DOMRect`'s origin.

  
[`DOMRectReadOnly.width`](domrectreadonly/width) Read only 
  The width of the `DOMRect`.

  
[`DOMRectReadOnly.height`](domrectreadonly/height) Read only 
  The height of the `DOMRect`.

  
[`DOMRectReadOnly.top`](domrectreadonly/top) Read only 
  Returns the top coordinate value of the `DOMRect` (usually the same as `y`).

  
[`DOMRectReadOnly.right`](domrectreadonly/right) Read only 
  Returns the right coordinate value of the `DOMRect` (usually the same as `x + width`).

  
[`DOMRectReadOnly.bottom`](domrectreadonly/bottom) Read only 
  Returns the bottom coordinate value of the `DOMRect` (usually the same as `y + height`).

  
[`DOMRectReadOnly.left`](domrectreadonly/left) Read only 
  Returns the left coordinate value of the `DOMRect` (usually the same as `x`).

  
Static methods
--------------


 [`DOMRectReadOnly.fromRect()`](domrectreadonly/fromrect)  Creates a new `DOMRect` object with a given location and dimensions.

  
Specifications
--------------




| Specification |
| --- |
| [Geometry Interfaces Module Level 1 # DOMRect](https://drafts.fxtf.org/geometry/#DOMRect) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DOMRectReadOnly` | 61 | 79 | 62 | No | 48 | 10.1 | 61 | 61 | 62 | 45 | 10.3 | 8.0 |
| `DOMRectReadOnly` | 612–61 | 7912–79 | 3127–313–27 | 4 | 489.5–48 | 10.14–11 | 612–61 | 6118–61 | 3127–314–27 | 4510.1–45 | 10.33.2–11 | 8.01.0–8.0 |
| `bottom` | 2 | 12 | 3 | 4 | 9.5 | 4 | 2 | 18 | 4 | 10.1 | 3.2 | 1.0 |
| `fromRect` | 61 | 79 | 69 | No | 48 | 10.1 | 61 | 61 | 79 | 45 | 10.3 | 8.0 |
| `height` | 2 | 12 | 3 | 4 | 9.5 | 4 | 2 | 18 | 4 | 10.1 | 3.2 | 1.0 |
| `left` | 2 | 12 | 3 | 4 | 9.5 | 4 | 2 | 18 | 4 | 10.1 | 3.2 | 1.0 |
| `right` | 2 | 12 | 3 | 4 | 9.5 | 4 | 2 | 18 | 4 | 10.1 | 3.2 | 1.0 |
| `toJSON` | 61 | 79 | 62 | No | 48 | 10.1 | 61 | 61 | 62 | 45 | 10.3 | 8.0 |
| `top` | 2 | 12 | 3 | 4 | 9.5 | 4 | 2 | 18 | 4 | 10.1 | 3.2 | 1.0 |
| `width` | 2 | 12 | 3 | 4 | 9.5 | 4 | 2 | 18 | 4 | 10.1 | 3.2 | 1.0 |
| `worker_support` | 61 | 79 | 69 | No | 48 | 10.1 | 61 | 61 | No | 45 | 10.3 | 8.0 |
| `x` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |
| `y` | 61 | 79 | 31 | No | 48 | 10.1 | 61 | 61 | 31 | 45 | 10.3 | 8.0 |


See also
--------


* [`DOMPoint`](dompoint)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DOMRectReadOnly>

DOMStringList
=============



The `DOMString` interface is a legacy type returned by some APIs and represents a non-modifiable list of strings (`DOMString`). Modern APIs use [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) objects (in WebIDL: `sequence<DOMString>`) instead.

 This interface is used in [IndexedDB](indexeddb_api) and in the [`Location`](location) API:

 * [`IDBDatabase.objectStoreNames`](idbdatabase/objectstorenames)
* [`IDBObjectStore.indexNames`](idbobjectstore/indexnames)
* [`Location.ancestorOrigins`](location/ancestororigins)



Instance properties
-------------------


 
[`DOMStringList.length`](domstringlist/length) Read only 
  Returns the size of the list.

  
Instance methods
----------------


 [`DOMStringList.item()`](domstringlist/item)  Returns a string from the list with the given index.

  [`DOMStringList.contains()`](domstringlist/contains)  Returns a boolean indicating whether the given string is in the list.

  
Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-domstringlist-interface](https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#the-domstringlist-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DOMStringList` | 1 | 12 | 1 | 10 | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `contains` | 1 | 12 | 1.5 | 10 | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `item` | 1 | 12 | 1 | 10 | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `length` | 1 | 12 | 1 | 10 | ≤12.1 | 5.1 | ≤37 | 18 | 4 | ≤12.1 | 5 | 1.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DOMStringList>

DragEvent
=========



The `DragEvent` interface is a [`DOM event`](event) that represents a drag and drop interaction. The user initiates a drag by placing a pointer device (such as a mouse) on the touch surface and then dragging the pointer to a new location (such as another DOM element). Applications are free to interpret a drag and drop interaction in an application-specific way.

 This interface inherits properties from [`MouseEvent`](mouseevent) and [`Event`](event).


 Event UIEvent MouseEvent DragEvent

Instance properties
-------------------


 
[`DragEvent.dataTransfer`](dragevent/datatransfer) Read only 
  The data that is transferred during a drag and drop interaction.

  
Constructors
------------



Although this interface has a constructor, it is not possible to create a useful DataTransfer object from script, since [`DataTransfer`](datatransfer) objects have a processing and security model that is coordinated by the browser during drag-and-drops.

  [`DragEvent()`](dragevent/dragevent)  Creates a synthetic and untrusted DragEvent.

  

Event types
-----------


 [`drag`](htmlelement/drag_event)  This event is fired when an element or text selection is being dragged.

  [`dragend`](htmlelement/dragend_event)  This event is fired when a drag operation is being ended (by releasing a mouse button or hitting the escape key).

  [`dragenter`](htmlelement/dragenter_event)  This event is fired when a dragged element or text selection enters a valid drop target.

  [`dragleave`](htmlelement/dragleave_event)  This event is fired when a dragged element or text selection leaves a valid drop target.

  [`dragover`](htmlelement/dragover_event)  This event is fired continuously when an element or text selection is being dragged and the mouse pointer is over a valid drop target (every 50 ms WHEN mouse is not moving ELSE much faster between 5 ms (slow movement) and 1ms (fast movement) approximately. This firing pattern is different than [`mouseover`](element/mouseover_event) ).

  [`dragstart`](htmlelement/dragstart_event)  This event is fired when the user starts dragging an element or text selection.

  [`drop`](htmlelement/drop_event)  This event is fired when an element or text selection is dropped on a valid drop target.

  
Example
-------


An Example of each property, constructor, event type and global event handlers is included in their respective reference page.


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-dragevent-interface](https://html.spec.whatwg.org/multipage/dnd.html#the-dragevent-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DragEvent` | 46 | 12 | 3.5 | No | 12 | 3.1 | No | No | 4 | No | No | No |
| `DragEvent` | 3 | 12 | 3.5 | 9Before Internet Explorer 10, `DragEvent` is exposed in standards mode but not quirks mode. | 12 | 3.1 | No | No | 4 | No | No | No |
| `dataTransfer` | 46 | 12 | 3.5 | 10The value is always `null`. | 33 | 3.1 | No | No | 4 | No | No | No |


See also
--------


* [Drag and drop](html_drag_and_drop_api)
* [Drag Operations](html_drag_and_drop_api/drag_operations)
* [Recommended Drag Types](html_drag_and_drop_api/recommended_drag_types)
* [DataTransfer test - Paste or Drag](https://codepen.io/tech_query/pen/MqGgap)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DragEvent>

DynamicsCompressorNode
======================



The `DynamicsCompressorNode` interface provides a compression effect, which lowers the volume of the loudest parts of the signal in order to help prevent clipping and distortion that can occur when multiple sounds are played and multiplexed together at once. This is often used in musical production and game audio. `DynamicsCompressorNode` is an [`AudioNode`](audionode) that has exactly one input and one output.


 EventTarget AudioNode DynamicsCompressorNode 

|  |  |
| --- | --- |
| Number of inputs | `1` |
| Number of outputs | `1` |
| Channel count mode | `"clamped-max"` |
| Channel count | `2` |
| Channel interpretation | `"speakers"` |



Constructor
-----------


 [`DynamicsCompressorNode()`](dynamicscompressornode/dynamicscompressornode)  Creates a new instance of an `DynamicsCompressorNode` object.

  
Instance properties
-------------------



*Inherits properties from its parent, [`AudioNode`](audionode)*.

  
[`DynamicsCompressorNode.threshold`](dynamicscompressornode/threshold) Read only 
  A [k-rate](audioparam#k-rate) [`AudioParam`](audioparam) representing the decibel value above which the compression will start taking effect.

  
[`DynamicsCompressorNode.knee`](dynamicscompressornode/knee) Read only 
  A [k-rate](audioparam#k-rate) [`AudioParam`](audioparam) containing a decibel value representing the range above the threshold where the curve smoothly transitions to the compressed portion.

  
[`DynamicsCompressorNode.ratio`](dynamicscompressornode/ratio) Read only 
  A [k-rate](audioparam#k-rate) [`AudioParam`](audioparam) representing the amount of change, in dB, needed in the input for a 1 dB change in the output.

  
[`DynamicsCompressorNode.reduction`](dynamicscompressornode/reduction) Read only 
  A `float` representing the amount of gain reduction currently applied by the compressor to the signal.

  
[`DynamicsCompressorNode.attack`](dynamicscompressornode/attack) Read only 
  A [k-rate](audioparam#k-rate) [`AudioParam`](audioparam) representing the amount of time, in seconds, required to reduce the gain by 10 dB.

  
[`DynamicsCompressorNode.release`](dynamicscompressornode/release) Read only 
  A [k-rate](audioparam#k-rate) [`AudioParam`](audioparam) representing the amount of time, in seconds, required to increase the gain by 10 dB.

  

Instance methods
----------------


*No specific methods; inherits methods from its parent, [`AudioNode`](audionode)*.


Example
-------


See [`BaseAudioContext.createDynamicsCompressor()`](baseaudiocontext/createdynamicscompressor#examples) example code.


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # DynamicsCompressorNode](https://webaudio.github.io/web-audio-api/#DynamicsCompressorNode) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DynamicsCompressorNode` | 55 | 79 | 53 | No | 42 | 14.1 | 55 | 55 | 53 | 42 | 14.5 | 6.0 |
| `DynamicsCompressorNode` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `attack` | 19 | 12 | 25 | No | 15 | 6 | ≤37 | 25 | 25 | 14 | 6 | 1.5 |
| `knee` | 19 | 12 | 25 | No | 15 | 6 | ≤37 | 25 | 25 | 14 | 6 | 1.5 |
| `ratio` | 19 | 12 | 25 | No | 15 | 6 | ≤37 | 25 | 25 | 14 | 6 | 1.5 |
| `reduction` | 19Before version 52, this was an `AudioParam.`. | 12 | 25 | No | 15 | 6 | ≤37Before version 52, this was an `AudioParam.`. | 25Before version 52, this was an `AudioParam.`. | 25 | 14 | 6 | 1.0Before Samsung Internet 6.0, this was an `AudioParam.`. |
| `release` | 20 | 12 | 25 | No | 15 | 6 | ≤37 | 25 | 25 | 14 | 6 | 1.5 |
| `threshold` | 19 | 12 | 25 | No | 15 | 6 | ≤37 | 25 | 25 | 14 | 6 | 1.5 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DynamicsCompressorNode>

EcdhKeyDeriveParams
===================



The `EcdhKeyDeriveParams` dictionary of the [Web Crypto API](web_crypto_api) represents the object that should be passed as the `algorithm` parameter into [`SubtleCrypto.deriveKey()`](subtlecrypto/derivekey), when using the [ECDH](subtlecrypto/derivekey#ecdh) algorithm.

 ECDH enables two people who each have a key pair consisting of a public and a private key to derive a shared secret. They exchange public keys and use the combination of their private key and the other entity's public key to derive a secret key that they — and no one else — share.

 The parameters for ECDH `deriveKey()` therefore include the other entity's public key, which is combined with this entity's private key to derive the shared secret.



Instance properties
-------------------


 `name`  A string. This should be set to `ECDH`.

  `public`  A [`CryptoKey`](cryptokey) object representing the public key of the other entity.

  
Examples
--------


See the examples for [`SubtleCrypto.deriveKey()`](subtlecrypto/derivekey).


Specifications
--------------




| Specification |
| --- |
| [Web Cryptography API # dfn-EcdhKeyDeriveParams](https://w3c.github.io/webcrypto/#dfn-EcdhKeyDeriveParams) |


Browser compatibility
---------------------


See also
--------


* [`SubtleCrypto.deriveKey()`](subtlecrypto/derivekey).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/EcdhKeyDeriveParams>

DOMStringMap
============


The `DOMStringMap` interface is used for the [`HTMLElement.dataset`](htmlelement/dataset)/[`SVGElement.dataset`](htmlelement/dataset) attribute, to represent data for custom attributes added to elements.


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # embedding-custom-non-visible-data-with-the-data-\*-attributes:domstringmap-3](https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes:domstringmap-3) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DOMStringMap` | 7 | 12 | 6 | 11 | ≤12.1 | 5.1 | 3 | 18 | 6 | ≤12.1 | 5 | 1.0 |


See also
--------


* [`HTMLElement.dataset`](htmlelement/dataset) / [`SVGElement.dataset`](htmlelement/dataset)
* [Global attributes - `data-*`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-*)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DOMStringMap>

DOMTokenList
============



The `DOMTokenList` interface represents a set of space-separated tokens. Such a set is returned by [`Element.classList`](element/classlist) or [`HTMLLinkElement.relList`](htmllinkelement/rellist), and many others.

 A `DOMTokenList` is indexed beginning with `0` as with JavaScript [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) objects. `DOMTokenList` is always case-sensitive.



Instance properties
-------------------


 
[`DOMTokenList.length`](domtokenlist/length) Read only 
  An `integer` representing the number of objects stored in the object.

  [`DOMTokenList.value`](domtokenlist/value)  A [stringifier](https://developer.mozilla.org/en-US/docs/Glossary/Stringifier) property that returns the value of the list as a string.

  
Instance methods
----------------


 [`DOMTokenList.item()`](domtokenlist/item)  Returns the item in the list by its index, or `null` if the index is greater than or equal to the list's `length`.

  [`DOMTokenList.contains()`](domtokenlist/contains)  Returns `true` if the list contains the given token, otherwise `false`.

  [`DOMTokenList.add()`](domtokenlist/add)  Adds the specified tokens to the list.

  [`DOMTokenList.remove()`](domtokenlist/remove)  Removes the specified tokens from the list.

  [`DOMTokenList.replace()`](domtokenlist/replace)  Replaces the token with another one.

  [`DOMTokenList.supports()`](domtokenlist/supports)  Returns `true` if the given token is in the associated attribute's supported tokens.

  [`DOMTokenList.toggle()`](domtokenlist/toggle)  Removes the token from the list if it exists, or adds it to the list if it doesn't. Returns a boolean indicating whether the token is in the list after the operation.

  [`DOMTokenList.entries()`](domtokenlist/entries)  Returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols), allowing you to go through all key/value pairs contained in this object.

  [`DOMTokenList.forEach()`](domtokenlist/foreach)  Executes a provided callback function once for each `DOMTokenList` element.

  [`DOMTokenList.keys()`](domtokenlist/keys)  Returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols), allowing you to go through all keys of the key/value pairs contained in this object.

  [`DOMTokenList.values()`](domtokenlist/values)  Returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols), allowing you to go through all values of the key/value pairs contained in this object.

  
Examples
--------



In the following simple example, we retrieve the list of classes set on a [`<p>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p) element as a `DOMTokenList` using [`Element.classList`](element/classlist), add a class using [`DOMTokenList.add()`](domtokenlist/add), and then update the [`Node.textContent`](node/textcontent) of the `<p>` to equal the `DOMTokenList`.

 First, the HTML:

 
```
<p class="a b c"></p>

```
 Now the JavaScript:

 
```
let para = document.querySelector("p");
let classes = para.classList;
para.classList.add("d");
para.textContent = `paragraph classList is "${classes}"`;

```
 The output looks like this:




Trimming of whitespace and removal of duplicates
------------------------------------------------



Methods that modify the `DOMTokenList` (such as [`DOMTokenList.add()`](domtokenlist/add)) automatically trim any excess [Whitespace](https://developer.mozilla.org/en-US/docs/Glossary/Whitespace) and remove duplicate values from the list. For example:

 
```
<span class=" d d e f"></span>

```
 
```
let span = document.querySelector("span");
let classes = span.classList;
span.classList.add("x");
span.textContent = `span classList is "${classes}"`;

```
 The output looks like this:




Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-domtokenlist](https://dom.spec.whatwg.org/#interface-domtokenlist) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@iterator` | 42 | 16 | 36 | No | 29 | 10.1 | 42 | 42 | 36 | 29 | 10.3 | 4.0 |
| `DOMTokenList` | 8 | 12 | 3.6 | 10 | 11.5 | 5.1 | 3 | 18 | 4 | 11.5 | 5 | 1.0 |
| `add` | 8 | 12 | 3.6 | 10 | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `contains` | 8 | 12 | 3.6 | 10 | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `entries` | 42 | 16 | 50 | No | 29 | 10.1 | 42 | 42 | 50 | 29 | 10.3 | 4.0 |
| `forEach` | 42 | 16 | 50 | No | 29 | 10.1 | 42 | 42 | 50 | 29 | 10.3 | 4.0 |
| `item` | 8 | 12 | 3.6 | 10 | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `keys` | 42 | 16 | 50 | No | 29 | 10.1 | 42 | 42 | 50 | 29 | 10.3 | 4.0 |
| `length` | 8 | 12 | 3.6 | 10 | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `remove` | 8 | 12 | 3.6 | 10 | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `remove_duplicates` | 60 | 17 | 55 | No | 47 | 10 | 60 | 60 | 55 | 44 | 10 | 8.0 |
| `replace` | 61 | 17 | 49 | No | 48 | 10.1 | 61 | 61 | 49 | 45 | 10.3 | 8.0 |
| `supports` | 49 | 17 | 49 | No | 36 | 10.1 | 49 | 49 | 49 | 36 | 10.3 | 5.0 |
| `toString` | 8 | 12 | 3.6 | No | ≤12.1 | 5.1 | 4.4 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `toggle` | 8 | 12 | 3.6 | 10 | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `trim_whitespace` | 48 | 12 | 51 | 10 | 35 | 10 | 48 | 48 | 51 | 35 | 10 | 5.0 |
| `value` | 50Before Chrome 50, this property was part of the deprecated child `DOMSettableTokenList` interface. | 17 | 47 | No | 37Before Opera 37, this property was part of the deprecated child `DOMSettableTokenList` interface. | 10 | 50Before Chrome 50, this property was part of the deprecated child `DOMSettableTokenList` interface. | 50Before Chrome 50, this property was part of the deprecated child `DOMSettableTokenList` interface. | 47 | 37Before Opera 37, this property was part of the deprecated child `DOMSettableTokenList` interface. | 10 | 5.0Before Samsung Internet 5.0, this property was part of the deprecated child `DOMSettableTokenList` interface. |
| `values` | 42 | 16 | 50 | No | 29 | 10.1 | 42 | 42 | 50 | 29 | 10.3 | 4.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList>

EcdsaParams
===========


The `EcdsaParams` dictionary of the [Web Crypto API](web_crypto_api) represents the object that should be passed as the `algorithm` parameter into [`SubtleCrypto.sign()`](subtlecrypto/sign) or [`SubtleCrypto.verify()`](subtlecrypto/verify) when using the [ECDSA](subtlecrypto/sign#ecdsa) algorithm.


Instance properties
-------------------


 `name`  A string. This should be set to `ECDSA`.

  `hash`  A string. An identifier for the [digest algorithm](subtlecrypto/digest) to use. This should be one of the following:

 * `SHA-256`: selects the [SHA-256](subtlecrypto/digest#supported_algorithms) algorithm.
* `SHA-384`: selects the [SHA-384](subtlecrypto/digest#supported_algorithms) algorithm.
* `SHA-512`: selects the [SHA-512](subtlecrypto/digest#supported_algorithms) algorithm.

  **Warning:** `SHA-1` is also supported here but the [SHA-1](subtlecrypto/digest#supported_algorithms) algorithm is considered vulnerable and should no longer be used.

   
Examples
--------


See the examples for [`SubtleCrypto.sign()`](subtlecrypto/sign) or [`SubtleCrypto.verify()`](subtlecrypto/verify).


Specifications
--------------




| Specification |
| --- |
| [Web Cryptography API # SubtleCrypto-method-sign](https://w3c.github.io/webcrypto/#SubtleCrypto-method-sign) |
| [Web Cryptography API # SubtleCrypto-method-verify](https://w3c.github.io/webcrypto/#SubtleCrypto-method-verify) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `EcdsaParams` | 37 | 7912–79Not supported: RSA-PSS, ECDSA. | 34 | 11Returns `CryptoOperation` instead of `Promise` | 24 | 7 | 37 | 37 | 34 | 24 | 7 | 3.0 |




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `EcdsaParams` | 37 | 7912–79Not supported: RSA-PSS, ECDSA. | 34 | 11Returns `CryptoOperation` instead of `Promise` | 24 | 7 | 37 | 37 | 34 | 24 | 7 | 3.0 |


### api.SubtleCrypto.sign


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


### api.SubtleCrypto.verify


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


See also
--------


* [`SubtleCrypto.sign()`](subtlecrypto/sign) and [`SubtleCrypto.verify()`](subtlecrypto/verify).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/EcdsaParams>

EncodedVideoChunk
=================


The `EncodedVideoChunk` interface of the [WebCodecs API](webcodecs_api) represents a chunk of encoded video data.


Constructor
-----------


 [`EncodedVideoChunk()`](encodedvideochunk/encodedvideochunk)  Creates a new `EncodedVideoChunk` object.

  
Instance properties
-------------------


 
[`EncodedVideoChunk.type`](encodedvideochunk/type) Read only 
  Returns a string indicating whether this chunk of data is a key chunk.

  
[`EncodedVideoChunk.timestamp`](encodedvideochunk/timestamp) Read only 
  Returns an integer representing the timestamp of the video in microseconds.

  
[`EncodedVideoChunk.duration`](encodedvideochunk/duration) Read only 
  Returns an integer representing the duration of the video in microseconds.

  
[`EncodedVideoChunk.byteLength`](encodedvideochunk/bytelength) Read only 
  Returns an integer representing the length of the video in bytes.

  
Instance methods
----------------


 [`EncodedVideoChunk.copyTo()`](encodedvideochunk/copyto)  Copies the encoded video data.

  
Specifications
--------------




| Specification |
| --- |
| [WebCodecs # encodedvideochunk-interface](https://w3c.github.io/webcodecs/#encodedvideochunk-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `EncodedVideoChunk` | 94 | 94 | No | No | 80 | 16.4 | 94 | 94 | No | 66 | 16.4 | 17.0 |
| `EncodedVideoChunk` | 94 | 94 | No | No | 80 | 16.4 | 94 | 94 | No | 66 | 16.4 | 17.0 |
| `byteLength` | 94 | 94 | No | No | 80 | 16.4 | 94 | 94 | No | 66 | 16.4 | 17.0 |
| `copyTo` | 94 | 94 | No | No | 80 | 16.4 | 94 | 94 | No | 66 | 16.4 | 17.0 |
| `duration` | 94 | 94 | No | No | 80 | 16.4 | 94 | 94 | No | 66 | 16.4 | 17.0 |
| `timestamp` | 94 | 94 | No | No | 80 | 16.4 | 94 | 94 | No | 66 | 16.4 | 17.0 |
| `type` | 94 | 94 | No | No | 80 | 16.4 | 94 | 94 | No | 66 | 16.4 | 17.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/EncodedVideoChunk>

EcKeyGenParams
==============


The `EcKeyGenParams` dictionary of the [Web Crypto API](web_crypto_api) represents the object that should be passed as the `algorithm` parameter into [`SubtleCrypto.generateKey()`](subtlecrypto/generatekey), when generating any elliptic-curve-based key pair: that is, when the algorithm is identified as either of [ECDSA](subtlecrypto/sign#ecdsa) or [ECDH](subtlecrypto/derivekey#ecdh).


Instance properties
-------------------


 `name`  A string. This should be set to `ECDSA` or `ECDH`, depending on the algorithm you want to use.

  `namedCurve`  A string representing the name of the elliptic curve to use. This may be any of the following names for [NIST](https://www.nist.gov/)-approved curves:

 * `P-256`
* `P-384`
* `P-521`

  
Examples
--------


See the examples for [`SubtleCrypto.generateKey()`](subtlecrypto/generatekey).


Specifications
--------------




| Specification |
| --- |
| [Web Cryptography API # dfn-EcKeyGenParams](https://w3c.github.io/webcrypto/#dfn-EcKeyGenParams) |


Browser compatibility
---------------------


See also
--------


* [`SubtleCrypto.generateKey()`](subtlecrypto/generatekey).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/EcKeyGenParams>

EcKeyImportParams
=================


The `EcKeyImportParams` dictionary of the [Web Crypto API](web_crypto_api) represents the object that should be passed as the `algorithm` parameter into [`SubtleCrypto.importKey()`](subtlecrypto/importkey) or [`SubtleCrypto.unwrapKey()`](subtlecrypto/unwrapkey), when generating any elliptic-curve-based key pair: that is, when the algorithm is identified as either of [ECDSA](subtlecrypto/sign#ecdsa) or [ECDH](subtlecrypto/derivekey#ecdh).


Instance properties
-------------------


 `name`  A string. This should be set to `ECDSA` or `ECDH`, depending on the algorithm you want to use.

  `namedCurve`  A string representing the name of the elliptic curve to use. This may be any of the following names for [NIST](https://www.nist.gov/)-approved curves:

 * `P-256`
* `P-384`
* `P-521`

  
Examples
--------


See the examples for [`SubtleCrypto.importKey()`](subtlecrypto/importkey).


Specifications
--------------




| Specification |
| --- |
| [Web Cryptography API # dfn-EcKeyImportParams](https://w3c.github.io/webcrypto/#dfn-EcKeyImportParams) |


Browser compatibility
---------------------


See also
--------


* [`SubtleCrypto.importKey()`](subtlecrypto/importkey).
* [`SubtleCrypto.unwrapKey()`](subtlecrypto/unwrapkey).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/EcKeyImportParams>

ElementInternals
================


The `ElementInternals` interface of the [Document Object Model](document_object_model) gives web developers a way to allow custom elements to fully participate in HTML forms. It provides utilities for working with these elements in the same way you would work with any standard HTML form element, and also exposes the [Accessibility Object Model](https://wicg.github.io/aom/explainer.html) to the element.


Constructor
-----------


This interface has no constructor. An `ElementInternals` object is returned when calling [`HTMLElement.attachInternals()`](htmlelement/attachinternals).


Instance properties
-------------------


 
[`ElementInternals.shadowRoot`](elementinternals/shadowroot) Read only 
  Returns the [`ShadowRoot`](shadowroot) object associated with this element.

  
[`ElementInternals.form`](elementinternals/form) Read only 
  Returns the [`HTMLFormElement`](htmlformelement) associated with this element.

  
[`ElementInternals.states`](elementinternals/states) Read only   Experimental 
  Returns the [`CustomStateSet`](customstateset) associated with this element.

  
[`ElementInternals.willValidate`](elementinternals/willvalidate) Read only 
   A boolean value which returns true if the element is a submittable element that is a candidate for [constraint validation](https://developer.mozilla.org/en-US/docs/Web/HTML/Constraint_validation). 

  
[`ElementInternals.validity`](elementinternals/validity) Read only 
  Returns a [`ValidityState`](validitystate) object which represents the different validity states the element can be in, with respect to constraint validation.

  
[`ElementInternals.validationMessage`](elementinternals/validationmessage) Read only 
  A string containing the validation message of this element.

  
[`ElementInternals.labels`](elementinternals/labels) Read only 
  Returns a [`NodeList`](nodelist) of all of the label elements associated with this element.

  
### Instance properties included from ARIA



The `ElementInternals` interface includes the following properties, defined on the `ARIAMixin` mixin.

  **Note:** These are included in order that default accessibility semantics can be defined on a custom element. These may be overwritten by author-defined attributes, but ensure that default semantics are retained should the author delete those attributes, or fail to add them at all. For more information see the [Accessibility Object Model explainer](https://wicg.github.io/aom/explainer.html#default-semantics-for-custom-elements-via-the-elementinternals-object).

   [`ElementInternals.ariaAtomic`](elementinternals/ariaatomic)  A string reflecting the [`aria-atomic`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-atomic) attribute, which indicates whether assistive technologies will present all, or only parts of, the changed region based on the change notifications defined by the [`aria-relevant`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-relevant) attribute.

  [`ElementInternals.ariaAutoComplete`](elementinternals/ariaautocomplete)  A string reflecting the [`aria-autocomplete`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-autocomplete) attribute, which indicates whether inputting text could trigger display of one or more predictions of the user's intended value for a combobox, searchbox, or textbox and specifies how predictions would be presented if they were made.

  [`ElementInternals.ariaBusy`](elementinternals/ariabusy)  A string reflecting the [`aria-busy`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-busy) attribute, which indicates whether an element is being modified, as assistive technologies may want to wait until the modifications are complete before exposing them to the user.

  [`ElementInternals.ariaChecked`](elementinternals/ariachecked)  A string reflecting the [`aria-checked`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-checked) attribute, which indicates the current "checked" state of checkboxes, radio buttons, and other widgets that have a checked state.

  [`ElementInternals.ariaColCount`](elementinternals/ariacolcount)  A string reflecting the [`aria-colcount`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-colcount) attribute, which defines the number of columns in a table, grid, or treegrid.

  [`ElementInternals.ariaColIndex`](elementinternals/ariacolindex)  A string reflecting the [`aria-colindex`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-colindex) attribute, which defines an element's column index or position with respect to the total number of columns within a table, grid, or treegrid.

  [`ElementInternals.ariaColSpan`](elementinternals/ariacolspan)  A string reflecting the [`aria-colspan`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-colspan) attribute, which defines the number of columns spanned by a cell or gridcell within a table, grid, or treegrid.

  [`ElementInternals.ariaCurrent`](elementinternals/ariacurrent)  A string reflecting the [`aria-current`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-current) attribute, which indicates the element that represents the current item within a container or set of related elements.

  [`ElementInternals.ariaDescription`](elementinternals/ariadescription)  A string reflecting the [`aria-description`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-description) attribute, which defines a string value that describes or annotates the current ElementInternals.

  [`ElementInternals.ariaDisabled`](elementinternals/ariadisabled)  A string reflecting the [`aria-disabled`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-disabled) attribute, which indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.

  [`ElementInternals.ariaExpanded`](elementinternals/ariaexpanded)  A string reflecting the [`aria-expanded`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-expanded) attribute, which indicates whether a grouping element owned or controlled by this element is expanded or collapsed.

  [`ElementInternals.ariaHasPopup`](elementinternals/ariahaspopup)  A string reflecting the [`aria-haspopup`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-haspopup) attribute, which indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an ElementInternals.

  [`ElementInternals.ariaHidden`](elementinternals/ariahidden)  A string reflecting the [`aria-hidden`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-hidden) attribute, which indicates whether the element is exposed to an accessibility API.

  [`ElementInternals.ariaKeyShortcuts`](elementinternals/ariakeyshortcuts)  A string reflecting the [`aria-keyshortcuts`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-keyshortcuts) attribute, which indicates keyboard shortcuts that an author has implemented to activate or give focus to an ElementInternals.

  [`ElementInternals.ariaLabel`](elementinternals/arialabel)  A string reflecting the [`aria-label`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) attribute, which defines a string value that labels the current ElementInternals.

  [`ElementInternals.ariaLevel`](elementinternals/arialevel)  A string reflecting the [`aria-level`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-level) attribute, which defines the hierarchical level of an element within a structure.

  [`ElementInternals.ariaLive`](elementinternals/arialive)  A string reflecting the [`aria-live`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-live) attribute, which indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region.

  [`ElementInternals.ariaModal`](elementinternals/ariamodal)  A string reflecting the [`aria-modal`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-modal) attribute, which indicates whether an element is modal when displayed.

  [`ElementInternals.ariaMultiline`](elementinternals/ariamultiline)  A string reflecting the [`aria-multiline`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-multiline) attribute, which indicates whether a text box accepts multiple lines of input or only a single line.

  [`ElementInternals.ariaMultiSelectable`](elementinternals/ariamultiselectable)  A string reflecting the [`aria-multiselectable`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-multiselectable) attribute, which indicates that the user may select more than one item from the current selectable descendants.

  [`ElementInternals.ariaOrientation`](elementinternals/ariaorientation)  A string reflecting the [`aria-orientation`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-orientation) attribute, which indicates whether the element's orientation is horizontal, vertical, or unknown/ambiguous.

  [`ElementInternals.ariaPlaceholder`](elementinternals/ariaplaceholder)  A string reflecting the [`aria-placeholder`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-placeholder) attribute, which defines a short hint intended to aid the user with data entry when the control has no value.

  [`ElementInternals.ariaPosInSet`](elementinternals/ariaposinset)  A string reflecting the [`aria-posinset`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-posinset) attribute, which defines an element's number or position in the current set of listitems or treeitems.

  [`ElementInternals.ariaPressed`](elementinternals/ariapressed)  A string reflecting the [`aria-pressed`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-pressed) attribute, which indicates the current "pressed" state of toggle buttons.

  [`ElementInternals.ariaReadOnly`](elementinternals/ariareadonly)  A string reflecting the [`aria-readonly`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-readonly) attribute, which indicates that the element is not editable, but is otherwise operable.

  
[`ElementInternals.ariaRelevant`](elementinternals/ariarelevant)  Non-standard 
  A string reflecting the [`aria-relevant`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-relevant) attribute, which indicates what notifications the user agent will trigger when the accessibility tree within a live region is modified. This is used to describe what changes in an `aria-live` region are relevant and should be announced.

  [`ElementInternals.ariaRequired`](elementinternals/ariarequired)  A string reflecting the [`aria-required`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-required) attribute, which indicates that user input is required on the element before a form may be submitted.

  [`ElementInternals.role`](elementinternals/role)  A string which contains an ARIA role. A full list of ARIA roles can be found on the [ARIA techniques page](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques).

  [`ElementInternals.ariaRoleDescription`](elementinternals/ariaroledescription)  A string reflecting the [`aria-roledescription`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-roledescription) attribute, which defines a human-readable, author-localized description for the role of an Element.

  [`ElementInternals.ariaRowCount`](elementinternals/ariarowcount)  A string reflecting the [`aria-rowcount`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowcount) attribute, which defines the total number of rows in a table, grid, or treegrid.

  [`ElementInternals.ariaRowIndex`](elementinternals/ariarowindex)  A string reflecting the [`aria-rowindex`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowindex) attribute, which defines an element's row index or position with respect to the total number of rows within a table, grid, or treegrid.

  [`ElementInternals.ariaRowSpan`](elementinternals/ariarowspan)  A string reflecting the [`aria-rowspan`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowspan) attribute, which defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid.

  [`ElementInternals.ariaSelected`](elementinternals/ariaselected)  A string reflecting the [`aria-selected`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-selected) attribute, which indicates the current "selected" state of elements that have a selected state.

  [`ElementInternals.ariaSetSize`](elementinternals/ariasetsize)  A string reflecting the [`aria-setsize`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-setsize) attribute, which defines the number of items in the current set of listitems or treeitems.

  [`ElementInternals.ariaSort`](elementinternals/ariasort)  A string reflecting the [`aria-sort`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-sort) attribute, which indicates if items in a table or grid are sorted in ascending or descending order.

  [`ElementInternals.ariaValueMax`](elementinternals/ariavaluemax)  A string reflecting the [`aria-valueMax`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemax) attribute, which defines the maximum allowed value for a range widget.

  [`ElementInternals.ariaValueMin`](elementinternals/ariavaluemin)  A string reflecting the [`aria-valueMin`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemin) attribute, which defines the minimum allowed value for a range widget.

  [`ElementInternals.ariaValueNow`](elementinternals/ariavaluenow)  A string reflecting the [`aria-valueNow`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuenow) attribute, which defines the current value for a range widget.

  [`ElementInternals.ariaValueText`](elementinternals/ariavaluetext)  A string reflecting the [`aria-valuetext`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuetext) attribute, which defines the human-readable text alternative of aria-valuenow for a range widget.

  

Instance methods
----------------


 [`ElementInternals.setFormValue()`](elementinternals/setformvalue)  Sets the element's submission value and state, communicating these to the user agent.

  [`ElementInternals.setValidity()`](elementinternals/setvalidity)  Sets the validity of the element.

  [`ElementInternals.checkValidity()`](elementinternals/checkvalidity)  Checks if an element meets any [constraint validation](https://developer.mozilla.org/en-US/docs/Web/HTML/Constraint_validation) rules applied to it.

  [`ElementInternals.reportValidity()`](elementinternals/reportvalidity)  Checks if an element meets any [constraint validation](https://developer.mozilla.org/en-US/docs/Web/HTML/Constraint_validation) rules applied to it, and also sends a validation message to the user agent.

  
Examples
--------



The following example demonstrates how to create a custom form-associated element with [`HTMLElement.attachInternals`](htmlelement/attachinternals).

 
```
class CustomCheckbox extends HTMLElement {
  static formAssociated = true;

  constructor() {
    super();
    this.internals_ = this.attachInternals();
  }

  // …
}

window.customElements.define("custom-checkbox", CustomCheckbox);

let element = document.createElement("custom-checkbox");
let form = document.createElement("form");

// Append element to form to associate it
form.appendChild(element);

console.log(element.internals_.form);
// expected output: <form><custom-checkbox></custom-checkbox></form>

```


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-elementinternals-interface](https://html.spec.whatwg.org/multipage/custom-elements.html#the-elementinternals-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ElementInternals` | 77 | 79 | 93 | No | 64 | 16.4See [bug 197960](https://webkit.org/b/197960). | 77 | 77 | 93 | 55 | 16.4See [bug 197960](https://webkit.org/b/197960). | 12.0 |
| `ariaAtomic` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaAutoComplete` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaBusy` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaChecked` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaColCount` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaColIndex` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaColSpan` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaCurrent` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaDescription` | 83 | 83 | No | No | 69 | No | 83 | 83 | No | 59 | No | 13.0 |
| `ariaDisabled` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaExpanded` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaHasPopup` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaHidden` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaInvalid` | 102 | 102 | No | No | 88 | 16.4 | 102 | 102 | No | 70 | 16.4 | 19.0 |
| `ariaKeyShortcuts` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaLabel` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaLevel` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaLive` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaModal` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaMultiLine` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaMultiSelectable` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaOrientation` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaPlaceholder` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaPosInSet` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaPressed` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaReadOnly` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaRelevant` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaRequired` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaRoleDescription` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaRowCount` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaRowIndex` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaRowSpan` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaSelected` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaSetSize` | 84 | 84 | No | No | 70 | 16.4 | 84 | 84 | No | 60 | 16.4 | 14.0 |
| `ariaSort` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaValueMax` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaValueMin` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaValueNow` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `ariaValueText` | 81 | 81 | No | No | 68 | 16.4 | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `checkValidity` | 77 | 79 | 98 | No | 64 | 16.4 | 77 | 77 | 98 | 55 | 16.4 | 12.0 |
| `form` | 77 | 79 | 98 | No | 64 | 16.4 | 77 | 77 | 98 | 55 | 16.4 | 12.0 |
| `labels` | 77 | 79 | 98 | No | 64 | 16.4 | 77 | 77 | 98 | 55 | 16.4 | 12.0 |
| `reportValidity` | 77 | 79 | 98 | No | 64 | 16.4 | 77 | 77 | 98 | 55 | 16.4 | 12.0 |
| `role` | 103 | 103 | No | No | 89 | 16.4 | 103 | 103 | No | 71 | 16.4 | 20.0 |
| `setFormValue` | 77 | 79 | 98 | No | 64 | 16.4 | 77 | 77 | 98 | 55 | 16.4 | 12.0 |
| `setValidity` | 77 | 79 | 98 | No | 64 | 16.4 | 77 | 77 | 98 | 55 | 16.4 | 12.0 |
| `shadowRoot` | 88 | 88 | 93 | No | 74 | 16.4 | 88 | 88 | 93 | 63 | 16.4 | 15.0 |
| `states` | 90 | 90 | No | No | 76 | No | 90 | 90 | No | 64 | No | 15.0 |
| `validationMessage` | 77 | 79 | 98 | No | 64 | 16.4 | 77 | 77 | 98 | 55 | 16.4 | 12.0 |
| `validity` | 77 | 79 | 98 | No | 64 | 16.4 | 77 | 77 | 98 | 55 | 16.4 | 12.0 |
| `willValidate` | 77 | 79 | 98 | No | 64 | 16.4 | 77 | 77 | 98 | 55 | 16.4 | 12.0 |


See also
--------


* [More capable form controls](https://web.dev/more-capable-form-controls/)
* [Creating custom form controls with ElementInternals](https://css-tricks.com/creating-custom-form-controls-with-elementinternals/)
* [ElementInternals polyfill](https://www.npmjs.com/package/element-internals-polyfill)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ElementInternals>

EncodedAudioChunk
=================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `EncodedAudioChunk` interface of the [WebCodecs API](webcodecs_api) represents a chunk of encoded audio data.



Constructor
-----------


 
[`EncodedAudioChunk()`](encodedaudiochunk/encodedaudiochunk)  Experimental 
  Creates a new `EncodedAudioChunk` object.

  
Instance properties
-------------------


 
[`EncodedAudioChunk.type`](encodedaudiochunk/type) Read only   Experimental 
  Returns a string indicating whether this chunk of data is a key chunk.

  
[`EncodedAudioChunk.timestamp`](encodedaudiochunk/timestamp) Read only   Experimental 
  Returns an integer representing the timestamp of the audio in microseconds.

  
[`EncodedAudioChunk.duration`](encodedaudiochunk/duration) Read only   Experimental 
  Returns an integer representing the duration of the audio in microseconds.

  
[`EncodedAudioChunk.byteLength`](encodedaudiochunk/bytelength) Read only   Experimental 
  Returns an integer representing the length of the audio in bytes.

  
Instance methods
----------------


 
[`EncodedAudioChunk.copyTo()`](encodedaudiochunk/copyto)  Experimental 
  Copies the encoded audio data.

  
Specifications
--------------




| Specification |
| --- |
| [WebCodecs # encodedaudiochunk-interface](https://w3c.github.io/webcodecs/#encodedaudiochunk-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `EncodedAudioChunk` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `EncodedAudioChunk` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `byteLength` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `copyTo` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `duration` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `timestamp` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `type` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/EncodedAudioChunk>

ErrorEvent
==========



The `ErrorEvent` interface represents events providing information related to errors in scripts or in files.


 Event ErrorEvent

Instance properties
-------------------



*Also inherits properties from its parent [`Event`](event)*.

  
`ErrorEvent.message` Read only 
  A string containing a human-readable error message describing the problem. Lacking a [`crossorigin`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#crossorigin) setting reduces error logging.

  
`ErrorEvent.filename` Read only 
  A string containing the name of the script file in which the error occurred.

  
`ErrorEvent.lineno` Read only 
  An `integer` containing the line number of the script file on which the error occurred.

  
`ErrorEvent.colno` Read only 
  An `integer` containing the column number of the script file on which the error occurred.

  
`ErrorEvent.error` Read only 
  A JavaScript `Object` that is concerned by the event.

  

Constructor
-----------


 `ErrorEvent()`  Creates an `ErrorEvent` event with the given parameters.

  
Instance methods
----------------


*Inherits methods from its parent [`Event`](event)*.


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-errorevent-interface](https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ErrorEvent` | 16 | 14 | 27 | No | 15 | 6 | 4.4 | 18 | 27 | 14 | 6 | 1.0 |
| `ErrorEvent` | 10 | 12 | 27 | 10 | 11 | 6 | 4.4 | 18 | 27 | 11 | 6 | 1.0 |
| `colno` | 30 | 12 | 31 | 10 | 17 | 8 | 4.4 | 30 | 31 | 18 | 8 | 2.0 |
| `error` | 30 | 12 | 31 | 11 | 17 | 10 | 4.4 | 30 | 31 | 18 | 10 | 2.0 |
| `filename` | 10 | 12 | 27 | 10 | 11 | 6 | 4.4 | 18 | 27 | 11 | 6 | 1.0 |
| `lineno` | 10 | 12 | 27 | 10 | 11 | 6 | 4.4 | 18 | 27 | 11 | 6 | 1.0 |
| `message` | 10 | 12 | 27 | 10 | 11 | 6 | 4.4 | 18 | 27 | 11 | 6 | 1.0 |


See also
--------


* [Using web workers](web_workers_api/using_web_workers), most likely objects to raise such an event


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent>

Event
=====



The `Event` interface represents an event which takes place in the DOM.

 An event can be triggered by the user action e.g. clicking the mouse button or tapping keyboard, or generated by APIs to represent the progress of an asynchronous task. It can also be triggered programmatically, such as by calling the [`HTMLElement.click()`](htmlelement/click) method of an element, or by defining the event, then sending it to a specified target using [`EventTarget.dispatchEvent()`](eventtarget/dispatchevent).

 There are many types of events, some of which use other interfaces based on the main `Event` interface. `Event` itself contains the properties and methods which are common to all events.

 Many DOM elements can be set up to accept (or "listen" for) these events, and execute code in response to process (or "handle") them. Event-handlers are usually connected (or "attached") to various [HTML elements](https://developer.mozilla.org/en-US/docs/Web/HTML/Element) (such as `<button>`, `<div>`, `<span>`, etc.) using [`EventTarget.addEventListener()`](eventtarget/addeventlistener), and this generally replaces using the old HTML [event handler attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes). Further, when properly added, such handlers can also be disconnected if needed using [`removeEventListener()`](eventtarget/removeeventlistener).

  **Note:** One element can have several such handlers, even for the exact same event—particularly if separate, independent code modules attach them, each for its own independent purposes. (For example, a webpage with an advertising-module and statistics-module both monitoring video-watching.)

  When there are many nested elements, each with its own handler(s), event processing can become very complicated—especially where a parent element receives the very same event as its child elements because "spatially" they overlap so the event technically occurs in both, and the processing order of such events depends on the [Event bubbling and capture](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_bubbling_and_capture) settings of each handler triggered.



Interfaces based on Event
-------------------------



Below is a list of interfaces which are based on the main `Event` interface, with links to their respective documentation in the MDN API reference.

 Note that all event interfaces have names which end in "Event".

 * [`AnimationEvent`](animationevent)
* [`AudioProcessingEvent`](audioprocessingevent)  Deprecated
* [`BeforeUnloadEvent`](beforeunloadevent)
* [`BlobEvent`](blobevent)
* [`ClipboardEvent`](clipboardevent)
* [`CloseEvent`](closeevent)
* [`CompositionEvent`](compositionevent)
* [`CustomEvent`](customevent)
* [`DeviceMotionEvent`](devicemotionevent)
* [`DeviceOrientationEvent`](deviceorientationevent)
* [`DeviceProximityEvent`](deviceproximityevent)  Deprecated
* [`DragEvent`](dragevent)
* [`ErrorEvent`](errorevent)
* [`FetchEvent`](fetchevent)
* [`FocusEvent`](focusevent)
* [`FontFaceSetLoadEvent`](fontfacesetloadevent)
* [`FormDataEvent`](formdataevent)
* [`GamepadEvent`](gamepadevent)
* [`HashChangeEvent`](hashchangeevent)
* [`HIDInputReportEvent`](hidinputreportevent)
* [`IDBVersionChangeEvent`](idbversionchangeevent)
* [`InputEvent`](inputevent)
* [`KeyboardEvent`](keyboardevent)
* [`MediaStreamEvent`](mediastreamevent)  Deprecated
* [`MessageEvent`](messageevent)
* [`MouseEvent`](mouseevent)
* [`MutationEvent`](mutationevent)  Deprecated
* [`OfflineAudioCompletionEvent`](offlineaudiocompletionevent)
* [`PageTransitionEvent`](pagetransitionevent)
* [`PaymentRequestUpdateEvent`](paymentrequestupdateevent)
* [`PointerEvent`](pointerevent)
* [`PopStateEvent`](popstateevent)
* [`ProgressEvent`](progressevent)
* [`RTCDataChannelEvent`](rtcdatachannelevent)
* [`RTCPeerConnectionIceEvent`](rtcpeerconnectioniceevent)
* [`StorageEvent`](storageevent)
* [`SubmitEvent`](submitevent)
* [`SVGEvent`](svgevent)  Deprecated
* [`TimeEvent`](timeevent)
* [`TouchEvent`](touchevent)
* [`TrackEvent`](trackevent)
* [`TransitionEvent`](transitionevent)
* [`UIEvent`](uievent)
* [`UserProximityEvent`](userproximityevent)  Deprecated
* [`WebGLContextEvent`](webglcontextevent)
* [`WheelEvent`](wheelevent)



Constructor
-----------


 [`Event()`](event/event)  Creates an `Event` object, returning it to the caller.

  
Instance properties
-------------------


 
[`Event.bubbles`](event/bubbles) Read only 
  A boolean value indicating whether or not the event bubbles up through the DOM.

  
[`Event.cancelable`](event/cancelable) Read only 
  A boolean value indicating whether the event is cancelable.

  
[`Event.composed`](event/composed) Read only 
  A boolean indicating whether or not the event can bubble across the boundary between the shadow DOM and the regular DOM.

  
[`Event.currentTarget`](event/currenttarget) Read only 
  A reference to the currently registered target for the event. This is the object to which the event is currently slated to be sent. It's possible this has been changed along the way through *retargeting*.

  
[`Event.defaultPrevented`](event/defaultprevented) Read only 
  Indicates whether or not the call to [`event.preventDefault()`](event/preventdefault) canceled the event.

  
[`Event.eventPhase`](event/eventphase) Read only 
  Indicates which phase of the event flow is being processed. It is one of the following numbers: `NONE`, `CAPTURING_PHASE`, `AT_TARGET`, `BUBBLING_PHASE`.

  
[`Event.isTrusted`](event/istrusted) Read only 
  Indicates whether or not the event was initiated by the browser (after a user click, for instance) or by a script (using an event creation method, for example).

  
[`Event.target`](event/target) Read only 
  A reference to the object to which the event was originally dispatched.

  
[`Event.timeStamp`](event/timestamp) Read only 
  The time at which the event was created (in milliseconds). By specification, this value is time since epoch—but in reality, browsers' definitions vary. In addition, work is underway to change this to be a [`DOMHighResTimeStamp`](domhighrestimestamp) instead.

  
[`Event.type`](event/type) Read only 
  The case-insensitive name identifying the type of the event.

  
### Legacy and non-standard properties


 
[`Event.cancelBubble`](event/cancelbubble)  Deprecated 
  A historical alias to [`Event.stopPropagation()`](event/stoppropagation) that should be used instead. Setting its value to `true` before returning from an event handler prevents propagation of the event.

  
[`Event.explicitOriginalTarget`](event/explicitoriginaltarget)  Non-standard  Read only 
  The explicit original target of the event.

  
[`Event.originalTarget`](event/originaltarget)  Non-standard  Read only 
  The original target of the event, before any retargetings.

  
[`Event.returnValue`](event/returnvalue)  Deprecated 
  A historical property still supported in order to ensure existing sites continue to work. Use [`Event.preventDefault()`](event/preventdefault) and [`Event.defaultPrevented`](event/defaultprevented) instead.

  
[`Event.scoped`](event/composed) Read only   Deprecated 
  A boolean value indicating whether the given event will bubble across through the shadow root into the standard DOM. Use [`composed`](event/composed) instead.

  
Instance methods
----------------


 [`Event.composedPath()`](event/composedpath)  Returns the event's path (an array of objects on which listeners will be invoked). This does not include nodes in shadow trees if the shadow root was created with its [`ShadowRoot.mode`](shadowroot/mode) closed.

  [`Event.preventDefault()`](event/preventdefault)  Cancels the event (if it is cancelable).

  [`Event.stopImmediatePropagation()`](event/stopimmediatepropagation)  For this particular event, prevent all other listeners from being called. This includes listeners attached to the same element as well as those attached to elements that will be traversed later (during the capture phase, for instance).

  [`Event.stopPropagation()`](event/stoppropagation)  Stops the propagation of events further along in the DOM.

  
### Deprecated methods


 
[`Event.initEvent()`](event/initevent)  Deprecated 
  Initializes the value of an Event created. If the event has already been dispatched, this method does nothing. Use the constructor ([`Event()`](event/event) instead).

  
Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-event](https://dom.spec.whatwg.org/#interface-event) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Event` | 15 | 12 | 11 | No | 11.6 | 6 | 4.4 | 18 | 14 | 12 | 6 | 1.0 |
| `Event` | 1 | 12 | 1 | 6 | 4 | 1 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 |
| `bubbles` | 1 | 12 | 1.5 | 9 | ≤12.1 | 1 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `cancelBubble` | 1Starting with Chrome 58 and Opera 45, setting this property to false does nothing, as per [spec discussion](https://github.com/whatwg/dom/issues/211). | 12 | 531–53Only supported for [`UIEvent`](https://developer.mozilla.org/docs/Web/API/UIEvent), not all `Event` objects. | 9 | ≤12.1Starting with Chrome 58 and Opera 45, setting this property to false does nothing, as per [spec discussion](https://github.com/whatwg/dom/issues/211). | 1 | ≤37Starting with Chrome 58 and Opera 45, setting this property to false does nothing, as per [spec discussion](https://github.com/whatwg/dom/issues/211). | 18Starting with Chrome 58 and Opera 45, setting this property to false does nothing, as per [spec discussion](https://github.com/whatwg/dom/issues/211). | 534–53Only supported for [`UIEvent`](https://developer.mozilla.org/docs/Web/API/UIEvent), not all `Event` objects. | ≤12.1Starting with Chrome 58 and Opera 45, setting this property to false does nothing, as per [spec discussion](https://github.com/whatwg/dom/issues/211). | 1 | 1.0Starting with Samsung Internet 7.0 and Opera 45, setting this property to false does nothing, as per [spec discussion](https://github.com/whatwg/dom/issues/211). |
| `cancelable` | 1 | 12 | 1.5 | 9 | ≤12.1 | 1 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `composed` | 53 | 79 | 52 | No | 40 | 10 | 53 | 53 | 52 | 41 | 10 | 6.0 |
| `composedPath` | 5350–53 | 79 | 59 | No | 4037–40 | 10 | 5350–53 | 5350–53 | 59 | 4137–41 | 10 | 6.05.0–6.0 |
| `currentTarget` | 1 | 12 | 1 | 96–9On Internet Explorer 6 through 8, the event model is different. Event listeners are attached with the non-standard [`EventTarget.attachEvent`](https://developer.mozilla.org/docs/Web/API/EventTarget/attachEvent) method. In this model, there is no equivalent to `event.currentTarget` and `this` is the global object. One solution to emulate the `event.currentTarget` feature is to wrap your handler in a function calling the handler using `Function.prototype.call` with the element as a first argument. This way, `this` will be the expected value. | 7 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `defaultPrevented` | 5 | 12 | 6 | 9 | 11 | 5 | 3 | 18 | 6 | 11 | 5 | 1.0 |
| `eventPhase` | 1 | 12 | 1.5 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `explicitOriginalTarget` | No | No | 1.5 | No | No | No | No | No | 4 | No | No | No |
| `initEvent` | 1 | 12 | 171–17Before Firefox 17, a call to this method after the dispatching of the event raised an exception instead of doing nothing. | 9 | ≤12.1 | 1 | ≤37 | 18 | 174–17Before Firefox 17, a call to this method after the dispatching of the event raised an exception instead of doing nothing. | ≤12.1 | 1 | 1.0 |
| `isTrusted` | 46Starting with Chrome 53 and Opera 40, untrusted events do not invoke the default action. | 12 | 1.5 | 9In Internet Explorer, all events are trusted except those that are created with the `createEvent()` method. | 33Starting with Chrome 53 and Opera 40, untrusted events do not invoke the default action. | 10 | 46Starting with version 53, untrusted events do not invoke the default action. | 46Starting with Chrome 53 and Opera 40, untrusted events do not invoke the default action. | 4 | 33Starting with Chrome 53 and Opera 40, untrusted events do not invoke the default action. | 10 | 5.0Starting with Samsung Internet 6.0 and Opera 40, untrusted events do not invoke the default action. |
| `originalTarget` | No | No | 1.5 | No | No | No | No | No | 4 | No | No | No |
| `preventDefault` | 1 | 12 | 1 | 9 | 7 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `returnValue` | 1 | 12 | NoTemporarily added in 63, removed in 64, briefly added in 65, then removed again while related compatibility issues are sorted out (see [bug 1520756](https://bugzil.la/1520756)). | 6 | 15 | 1 | ≤37 | 18 | NoTemporarily added in 63, removed in 64, briefly added in 65, then removed again while related compatibility issues are sorted out (see [bug 1520756](https://bugzil.la/1520756)). | 14 | 1 | 1.0 |
| `srcElement` | 1 | 12 | 62 | 9 | ≤12.1 | 1 | ≤37 | 18 | 62 | ≤12.1 | 1 | 1.0 |
| `stopImmediatePropagation` | 5 | 12 | 10 | 9 | ≤12.1 | 5 | ≤37 | 18 | 10 | ≤12.1 | 5 | 1.0 |
| `stopPropagation` | 1 | 12 | 1 | 9 | 7 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `target` | 1 | 12 | 1 | 9 | 7 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `timeStamp` | 1Starting with Chrome 49, Firefox 54 and Opera 36, this property returns [`DOMHighResTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMHighResTimeStamp) instead of [`DOMTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMTimeStamp). | 12 | 1.5Starting with Chrome 49, Firefox 54 and Opera 36, this property returns [`DOMHighResTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMHighResTimeStamp) instead of [`DOMTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMTimeStamp). | 9Starting with Chrome 49, Firefox 54 and Opera 36, this property returns [`DOMHighResTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMHighResTimeStamp) instead of [`DOMTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMTimeStamp). | ≤12.1Starting with Chrome 49, Firefox 54 and Opera 36, this property returns [`DOMHighResTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMHighResTimeStamp) instead of [`DOMTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMTimeStamp). | 1 | 1Starting with version 49, this property returns [`DOMHighResTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMHighResTimeStamp) instead of [`DOMTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMTimeStamp). | 18Starting with Chrome 49, Firefox 54 and Opera 36, this property returns [`DOMHighResTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMHighResTimeStamp) instead of [`DOMTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMTimeStamp). | 4Starting with Chrome 49, Firefox 54 and Opera 36, this property returns [`DOMHighResTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMHighResTimeStamp) instead of [`DOMTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMTimeStamp). | ≤12.1Starting with Chrome 49, Firefox 54 and Opera 36, this property returns [`DOMHighResTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMHighResTimeStamp) instead of [`DOMTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMTimeStamp). | 1 | 1.0Starting with Samsung Internet 5.0, Firefox 54 and Opera 36, this property returns [`DOMHighResTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMHighResTimeStamp) instead of [`DOMTimeStamp`](https://developer.mozilla.org/docs/Web/API/DOMTimeStamp). |
| `type` | 1 | 12 | 1.5 | 9 | 7 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |


See also
--------


* Types of events available: [Event reference](https://developer.mozilla.org/en-US/docs/Web/Events)
* [Comparison of Event Targets](event/comparison_of_event_targets) (`target` vs. `currentTarget` vs. `relatedTarget` vs. `originalTarget`)
* [Creating and triggering custom events](https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Event>

EventCounts
===========



The `EventCounts` interface is a read-only map where the keys are event types and the values are the number of events that have been dispatched for that event type.

 As a read-only map, `EventCounts` is similar to a [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map), however, it doesn't implement the `clear()`, `delete()`, and `set()` methods.



Constructor
-----------


This interface has no constructor. You typically get an instance of this object using the [`performance.eventCounts`](performance/eventcounts) property.


Instance properties
-------------------


 `size`  See [`Map.prototype.size`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/size) for details.

  
Instance methods
----------------


 `entries()`  See [`Map.prototype.entries()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries) for details.

  `forEach()`  See [`Map.prototype.forEach()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach) for details.

  `get()`  See [`Map.prototype.get()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get) for details.

  `has()`  See [`Map.prototype.has()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has) for details.

  `keys()`  See [`Map.prototype.keys()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/keys) for details.

  `values()`  See [`Map.prototype.values()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/values) for details.

  
Examples
--------


### Working with EventCount maps



Below are a few examples to get information from an `EventCounts` map. Note that the map is read-only and the `clear()`, `delete()`, and `set()` methods aren't available.

 
```
for (entry of performance.eventCounts.entries()) {
  const type = entry[0];
  const count = entry[1];
}

const clickCount = performance.eventCounts.get("click");

const isExposed = performance.eventCounts.has("mousemove");
const exposedEventsCount = performance.eventCounts.size;
const exposedEventsList = [...performance.eventCounts.keys()];

```


Specifications
--------------




| Specification |
| --- |
| [Event Timing API # sec-event-counts](https://w3c.github.io/event-timing/#sec-event-counts) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@iterator` | 85 | 85 | 89 | No | 71 | No | 85 | 85 | 89 | 60 | No | 14.0 |
| `EventCounts` | 85 | 85 | 89 | No | 71 | No | 85 | 85 | 89 | 60 | No | 14.0 |
| `entries` | 85 | 85 | 89 | No | 71 | No | 85 | 85 | 89 | 60 | No | 14.0 |
| `forEach` | 85 | 85 | 89 | No | 71 | No | 85 | 85 | 89 | 60 | No | 14.0 |
| `get` | 85 | 85 | 89 | No | 71 | No | 85 | 85 | 89 | 60 | No | 14.0 |
| `has` | 85 | 85 | 89 | No | 71 | No | 85 | 85 | 89 | 60 | No | 14.0 |
| `keys` | 85 | 85 | 89 | No | 71 | No | 85 | 85 | 89 | 60 | No | 14.0 |
| `size` | 85 | 85 | 89 | No | 71 | No | 85 | 85 | 89 | 60 | No | 14.0 |
| `values` | 85 | 85 | 89 | No | 71 | No | 85 | 85 | 89 | 60 | No | 14.0 |


See also
--------


* [`performance.eventCounts`](performance/eventcounts)
* [`PerformanceEventTiming`](performanceeventtiming)
* [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/EventCounts>

EventSource
===========



The `EventSource` interface is web content's interface to [server-sent events](server-sent_events).

 An `EventSource` instance opens a persistent connection to an [HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP) server, which sends [events](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events) in `text/event-stream` format. The connection remains open until closed by calling [`EventSource.close()`](eventsource/close).


 EventTarget EventSource Once the connection is opened, incoming messages from the server are delivered to your code in the form of events. If there is an event field in the incoming message, the triggered event is the same as the event field value. If no event field is present, then a generic [`message`](eventsource/message_event) event is fired.

 Unlike [WebSockets](websockets_api), server-sent events are unidirectional; that is, data messages are delivered in one direction, from the server to the client (such as a user's web browser). That makes them an excellent choice when there's no need to send data from the client to the server in message form. For example, `EventSource` is a useful approach for handling things like social media status updates, news feeds, or delivering data into a [client-side storage](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage) mechanism like [IndexedDB](indexeddb_api) or [web storage](web_storage_api).

  **Warning:** When **not used over HTTP/2**, SSE suffers from a limitation to the maximum number of open connections, which can be specially painful when opening various tabs as the limit is *per browser* and set to a very low number (6). The issue has been marked as "Won't fix" in [Chrome](https://crbug.com/275955) and [Firefox](https://bugzil.la/906896). This limit is per browser + domain, so that means that you can open 6 SSE connections across all of the tabs to `www.example1.com` and another 6 SSE connections to `www.example2.com.` (from [Stackoverflow](https://stackoverflow.com/questions/5195452/websockets-vs-server-sent-events-eventsource/5326159)). When using HTTP/2, the maximum number of simultaneous *HTTP streams* is negotiated between the server and the client (defaults to 100).

 

Constructor
-----------


 [`EventSource()`](eventsource/eventsource)  Creates a new `EventSource` to handle receiving server-sent events from a specified URL, optionally in credentials mode.

  
Instance properties
-------------------



*This interface also inherits properties from its parent, [`EventTarget`](eventtarget).*

  
[`EventSource.readyState`](eventsource/readystate) Read only 
  A number representing the state of the connection. Possible values are `CONNECTING` (`0`), `OPEN` (`1`), or `CLOSED` (`2`).

  
[`EventSource.url`](eventsource/url) Read only 
  A string representing the URL of the source.

  
[`EventSource.withCredentials`](eventsource/withcredentials) Read only 
  A boolean value indicating whether the `EventSource` object was instantiated with cross-origin ([CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)) credentials set (`true`), or not (`false`, the default).

  

Instance methods
----------------



*This interface also inherits methods from its parent, [`EventTarget`](eventtarget).*

  [`EventSource.close()`](eventsource/close)  Closes the connection, if any, and sets the `readyState` attribute to `CLOSED`. If the connection is already closed, the method does nothing.

  

Events
------



 [`error`](eventsource/error_event)  Fired when a connection to an event source failed to open.

  [`message`](eventsource/message_event)  Fired when data is received from an event source.

  [`open`](eventsource/open_event)  Fired when a connection to an event source has opened.

   Additionally, the event source itself may send messages with an event field, which will create ad hoc events keyed to that value.



Examples
--------



In this basic example, an `EventSource` is created to receive unnamed events from the server; a page with the name `sse.php` is responsible for generating the events.

 
```
const evtSource = new EventSource("sse.php");
const eventList = document.querySelector("ul");

evtSource.onmessage = (e) => {
  const newElement = document.createElement("li");

  newElement.textContent = `message: ${e.data}`;
  eventList.appendChild(newElement);
};

```
 Each received event causes our `EventSource` object's `onmessage` event handler to be run. It, in turn, creates a new [`<li>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li) element and writes the message's data into it, then appends the new element to the list element already in the document.

  **Note:** You can find a full example on GitHub — see [Simple SSE demo using PHP](https://github.com/mdn/dom-examples/tree/main/server-sent-events).

  To listen to named events, you'll require a listener for each type of event sent.

 
```
const sse = new EventSource("/api/v1/sse");

/\*
 \* This will listen only for events
 \* similar to the following:
 \*
 \* event: notice
 \* data: useful data
 \* id: someid
 \*/
sse.addEventListener("notice", (e) => {
  console.log(e.data);
});

/\*
 \* Similarly, this will listen for events
 \* with the field `event: update`
 \*/
sse.addEventListener("update", (e) => {
  console.log(e.data);
});

/\*
 \* The event "message" is a special case, as it
 \* will capture events without an event field
 \* as well as events that have the specific type
 \* `event: message` It will not trigger on any
 \* other event type.
 \*/
sse.addEventListener("message", (e) => {
  console.log(e.data);
});

```


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-eventsource-interface](https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `EventSource` | 6 | 79 | 6 | No | 11 | 5 | 4.4 | 18 | 45 | 12 | 5 | 1.0 |
| `EventSource` | 6 | 79 | 6 | No | 11 | 5 | 4.4 | 18 | 45 | 11 | 5 | 1.0 |
| `close` | 6 | 79 | 6 | No | 12 | 5 | 4.4 | 18 | 45 | 12 | 5 | 1.0 |
| `error_event` | 6 | 79 | 6 | No | 12 | 5 | 4.4 | 18 | 45 | 12 | 5 | 1.0 |
| `message_event` | 6 | 79 | 6 | No | 12 | 5 | 4.4 | 18 | 45 | 12 | 5 | 1.0 |
| `open_event` | 6 | 79 | 6 | No | 12 | 5 | 4.4 | 18 | 45 | 12 | 5 | 1.0 |
| `readyState` | 6 | 79 | 6 | No | 12 | 5 | 4.4 | 18 | 45 | 12 | 5 | 1.0 |
| `url` | 18 | 79 | 6 | No | 12 | 6 | 4.4 | 18 | 45 | 12 | 6 | 1.0 |
| `withCredentials` | 26 | 79 | 6 | No | 12 | 7 | 4.4 | 26 | 45 | 12 | 7 | 1.5 |
| `worker_support` | 6 | 79 | 53 | No | ≤15 | 5 | ≤37 | 18 | 53 | ≤14 | 5 | 1.0 |


See also
--------


* [Server-sent events](server-sent_events)
* [Using server-sent events](server-sent_events/using_server-sent_events)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/EventSource>

EventTarget
===========



 The `EventTarget` interface is implemented by objects that can receive events and may have listeners for them. In other words, any target of events implements the three methods associated with this interface. 

  [`Element`](element), and its children, as well as [`Document`](document) and [`Window`](window), are the most common event targets, but other objects can be event targets, too. For example [`XMLHttpRequest`](xmlhttprequest), [`AudioNode`](audionode), and [`AudioContext`](audiocontext) are also event targets. 

 Many event targets (including elements, documents, and windows) also support setting [event handlers](https://developer.mozilla.org/en-US/docs/Web/Events/Event_handlers) via `onevent` properties and attributes.



Constructor
-----------


 [`EventTarget()`](eventtarget/eventtarget)  Creates a new `EventTarget` object instance.

  
Instance methods
----------------


 [`EventTarget.addEventListener()`](eventtarget/addeventlistener)  Registers an event handler of a specific event type on the `EventTarget`.

  [`EventTarget.removeEventListener()`](eventtarget/removeeventlistener)  Removes an event listener from the `EventTarget`.

  [`EventTarget.dispatchEvent()`](eventtarget/dispatchevent)  Dispatches an event to this `EventTarget`.

  
Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-eventtarget](https://dom.spec.whatwg.org/#interface-eventtarget) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `EventTarget` | 64 | 79 | 59 | No | 51 | 14 | 64 | 64 | 59 | 47 | 14 | 9.0 |
| `EventTarget` | 1 | 12 | 1 | 6 | 7 | 1`window.EventTarget` did not exist on versions of Safari before 10.1. | ≤37 | 18 | 4 | 10.1 | 1`window.EventTarget` did not exist on versions of Safari iOS before 10.3. | 1.0 |
| `addEventListener` | 1Before Chrome 49, the `type` and `listener` parameters were optional. | 12 | 1 | 96–11Older versions of IE supported an equivalent, proprietary `EventTarget.attachEvent()` method. | 7 | 1 | 1Before Chrome 49, the `type` and `listener` parameters were optional. | 18Before Chrome 49, the `type` and `listener` parameters were optional. | 4 | 10.1 | 1 | 1.0Before Samsung Internet 5.0, the `type` and `listener` parameters were optional. |
| `dispatchEvent` | 4 | 12 | 2 | 96–11Older versions of IE supported an equivalent, proprietary `EventTarget.fireEvent()` method. | 9 | 3.1 | 4 | 18 | 4 | 10.1 | 3 | 1.0 |
| `removeEventListener` | 1 | 12 | 1 | 96–11Older versions of IE supported an equivalent, proprietary `EventTarget.detachEvent()` method. | 7 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |


See also
--------


* [Event reference](https://developer.mozilla.org/en-US/docs/Web/Events) – the events available in the platform.
* [Introduction to events](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events)
* [`Event`](event) interface


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/EventTarget>

ExtendableCookieChangeEvent
===========================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `ExtendableCookieChangeEvent` interface of the['Cookie Store API'](cookie_store_api) is the event type passed to `ServiceWorkerRegistration.oncookiechange()` when any cookie changes occur. A cookie change event consists of a cookie and a type (either "changed" or "deleted".)

 Cookie changes that cause the `ExtendableCookieChangeEvent` to be dispatched are:

 * A cookie is newly created and not immediately removed. In this case `type` is "changed".
* A cookie is newly created and immediately removed. In this case `type` is "deleted"
* A cookie is removed. In this case `type` is "deleted".

  **Note:** A cookie that is replaced due to the insertion of another cookie with the same name, domain, and path, is ignored and does not trigger a change event.

 
 Event ExtendableEvent ExtendableCookieChangeEvent

Constructor
-----------


 [`ExtendableCookieChangeEvent()`](extendablecookiechangeevent/extendablecookiechangeevent)  Creates a new `ExtendableCookieChangeEvent`.

  
Instance properties
-------------------



*This interface also inherits properties from [`ExtendableEvent`](extendableevent).*

  
[`ExtendableCookieChangeEvent.changed`](extendablecookiechangeevent/changed) Read only 
  Returns an array containing the changed cookies.

  
[`ExtendableCookieChangeEvent.deleted`](extendablecookiechangeevent/deleted) Read only 
  Returns an array containing the deleted cookies.

  

Examples
--------



In the below example we use [`CookieStoreManager.getSubscriptions()`](cookiestoremanager/getsubscriptions) to get a list of existing subscriptions. (In service workers, a subscription is required in order to listen for events.) We unsubscribe from existing subscriptions using [`CookieStoreManager.unsubscribe()`](cookiestoremanager/unsubscribe), then subscribe to the cookie with a name of 'COOKIE\_NAME' using [`CookieStoreManager.subscribe()`](cookiestoremanager/subscribe). If that cookie is changed, the event listener logs the event to the console. This will be an `ExtendableCookieChangeEvent` object, with the [`changed`](extendablecookiechangeevent/changed) or [`deleted`](extendablecookiechangeevent/deleted) property containing the modified cookie.

 
```
self.addEventListener("activate", (event) => {
  event.waitUntil(async () => {
    const subscriptions = await self.registration.cookies.getSubscriptions();
    await self.registration.cookies.unsubscribe(subscriptions);

    await self.registration.cookies.subscribe([
      {
        name: "COOKIE\_NAME",
      },
    ]);
  });
});

self.addEventListener("cookiechange", (event) => {
  console.log(event);
});

```


Specifications
--------------




| Specification |
| --- |
| [Cookie Store API # ExtendableCookieChangeEvent](https://wicg.github.io/cookie-store/#ExtendableCookieChangeEvent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ExtendableCookieChangeEvent` | 87 | 87 | No | No | 73 | No | 87 | 87 | No | 62 | No | 14.0 |
| `ExtendableCookieChangeEvent` | 87 | 87 | No | No | 73 | No | 87 | 87 | No | 62 | No | 14.0 |
| `changed` | 87 | 87 | No | No | 73 | No | 87 | 87 | No | 62 | No | 14.0 |
| `deleted` | 87 | 87 | No | No | 73 | No | 87 | 87 | No | 62 | No | 14.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ExtendableCookieChangeEvent>

ExtendableEvent
===============



The `ExtendableEvent` interface extends the lifetime of the [`install`](serviceworkerglobalscope/install_event) and [`activate`](serviceworkerglobalscope/activate_event) events dispatched on the global scope as part of the service worker lifecycle. This ensures that any functional events (like [`FetchEvent`](fetchevent)) are not dispatched until it upgrades database schemas and deletes the outdated cache entries.

 If [`waitUntil()`](extendableevent/waituntil) is called outside of the `ExtendableEvent` handler, the browser should throw an `InvalidStateError`; note also that multiple calls will stack up, and the resulting promises will be added to the list of [extend lifetime promises](https://w3c.github.io/ServiceWorker/#extendableevent-extend-lifetime-promises).

  **Note:** The behavior described in the above paragraph was fixed in Firefox 43 (see [Firefox bug 1180274](https://bugzil.la/1180274).)

  This interface inherits from the [`Event`](event) interface.


 Event ExtendableEvent  **Note:** This interface is only available when the global scope is a [`ServiceWorkerGlobalScope`](serviceworkerglobalscope). It is not available when it is a [`Window`](window), or the scope of another kind of worker.

 

Constructor
-----------


 [`ExtendableEvent()`](extendableevent/extendableevent)  Creates a new `ExtendableEvent` object.

  
Instance properties
-------------------


*Doesn't implement any specific properties, but inherits properties from its parent, [`Event`](event).*


Instance methods
----------------



*Inherits methods from its parent, [`Event`](event)*.

  [`ExtendableEvent.waitUntil()`](extendableevent/waituntil)  Extends the lifetime of the event. It is intended to be called in the [`install`](serviceworkerglobalscope/install_event) [event handler](https://developer.mozilla.org/en-US/docs/Web/Events/Event_handlers) for the [`installing`](serviceworkerregistration/installing) worker and on the [`activate`](serviceworkerglobalscope/activate_event) [event handler](https://developer.mozilla.org/en-US/docs/Web/Events/Event_handlers) for the [`active`](serviceworkerregistration/active) worker.

  

Examples
--------



This code snippet is from the [service worker prefetch sample](https://github.com/GoogleChrome/samples/blob/gh-pages/service-worker/prefetch/service-worker.js) (see [prefetch example live](https://googlechrome.github.io/samples/service-worker/prefetch/).) The code calls [`ExtendableEvent.waitUntil()`](extendableevent/waituntil) in [`oninstall`](serviceworkerglobalscope/install_event), delaying treating the [`ServiceWorkerRegistration.installing`](serviceworkerregistration/installing) worker as installed until the passed promise resolves successfully. The promise resolves when all resources have been fetched and cached, or else when any exception occurs.

 The code snippet also shows a best practice for versioning caches used by the service worker. Though there's only one cache in this example, the same approach can be used for multiple caches. It maps a shorthand identifier for a cache to a specific, versioned cache name.

  **Note:** In Chrome, logging statements are visible via the "Inspect" interface for the relevant service worker accessed via chrome://serviceworker-internals.

  
```
const CACHE\_VERSION = 1;
const CURRENT\_CACHES = {
  prefetch: `prefetch-cache-v${CACHE\_VERSION}`,
};

self.addEventListener("install", (event) => {
  const urlsToPrefetch = [
    "./static/pre\_fetched.txt",
    "./static/pre\_fetched.html",
    "https://www.chromium.org/\_/rsrc/1302286216006/config/customLogo.gif",
  ];

  console.log(
    "Handling install event. Resources to pre-fetch:",
    urlsToPrefetch
  );

  event.waitUntil(
    caches
      .open(CURRENT\_CACHES["prefetch"])
      .then((cache) => {
        return cache
          .addAll(
            urlsToPrefetch.map((urlToPrefetch) => {
              return new Request(urlToPrefetch, { mode: "no-cors" });
            })
          )
          .then(() => {
            console.log("All resources have been fetched and cached.");
          });
      })
      .catch((error) => {
        console.error("Pre-fetching failed:", error);
      })
  );
});

```
  **Note:** When fetching resources, it's very important to use `{mode: 'no-cors'}` if there is any chance that the resources are served off of a server that doesn't support [CORS](https://developer.mozilla.org/en-US/docs/Glossary/CORS). In this example, [www.chromium.org](https://www.chromium.org/) doesn't support CORS.

 

Specifications
--------------




| Specification |
| --- |
| [Service Workers # extendableevent-interface](https://w3c.github.io/ServiceWorker/#extendableevent-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ExtendableEvent` | 41 | 17 | 44 | No | 24 | 11.1 | 41 | 41 | 44 | 24 | 11.3 | 4.0 |
| `ExtendableEvent` | 40 | 17 | 44 | No | 24 | 11.1 | 40 | 40 | 44 | 24 | 11.3 | 4.0 |
| `waitUntil` | 40 | 17 | 44 | No | 24 | 11.1 | 40 | 40 | 44 | 24 | 11.3 | 4.0 |


See also
--------


* [Using Service Workers](service_worker_api/using_service_workers)
* [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker)
* [Is ServiceWorker ready?](https://jakearchibald.github.io/isserviceworkerready/)
* [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
* [Using web workers](web_workers_api/using_web_workers)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ExtendableEvent>

ExtendableMessageEvent
======================



The `ExtendableMessageEvent` interface of the [Service Worker API](service_worker_api) represents the event object of a [`message`](serviceworkerglobalscope/message_event) event fired on a service worker (when a message is received on the [`ServiceWorkerGlobalScope`](serviceworkerglobalscope) from another context) — extends the lifetime of such events.

 This interface inherits from the [`ExtendableEvent`](extendableevent) interface.


 Event ExtendableEvent ExtendableMessageEvent

Constructor
-----------


 [`ExtendableMessageEvent()`](extendablemessageevent/extendablemessageevent)  Creates a new `ExtendableMessageEvent` object instance.

  
Instance properties
-------------------



*Inherits properties from its parent, [`ExtendableEvent`](extendableevent)*.

  
[`ExtendableMessageEvent.data`](extendablemessageevent/data) Read only 
  Returns the event's data. It can be any data type.

  
[`ExtendableMessageEvent.origin`](extendablemessageevent/origin) Read only 
  Returns the origin of the [`Client`](client) that sent the message.

  
[`ExtendableMessageEvent.lastEventId`](extendablemessageevent/lasteventid) Read only 
  Represents, in [server-sent events](server-sent_events/using_server-sent_events), the last event ID of the event source. This is an empty string.

  
[`ExtendableMessageEvent.source`](extendablemessageevent/source) Read only 
  Returns a reference to the [`Client`](client) object that sent the message.

  
[`ExtendableMessageEvent.ports`](extendablemessageevent/ports) Read only 
  Returns the array containing the [`MessagePort`](messageport) objects representing the ports of the associated message channel.

  

Instance methods
----------------


*Inherits methods from its parent, [`ExtendableEvent`](extendableevent)*.


Examples
--------



In the below example a page gets a handle to the [`ServiceWorker`](serviceworker) object via [`ServiceWorkerRegistration.active`](serviceworkerregistration/active), and then calls its `postMessage()` function.

 
```
// in the page being controlled
if (navigator.serviceWorker) {
  navigator.serviceWorker.register("service-worker.js");

  navigator.serviceWorker.addEventListener("message", (event) => {
    // event is a MessageEvent object
    console.log(`The service worker sent me a message: ${event.data}`);
  });

  navigator.serviceWorker.ready.then((registration) => {
    registration.active.postMessage("Hi service worker");
  });
}

```
 The service worker can receive the message by listening to the `message` event:

 
```
// in the service worker
addEventListener("message", (event) => {
  // event is an ExtendableMessageEvent object
  console.log(`The client sent me a message: ${event.data}`);

  event.source.postMessage("Hi client");
});

```


Specifications
--------------




| Specification |
| --- |
| [Service Workers # extendablemessageevent-interface](https://w3c.github.io/ServiceWorker/#extendablemessageevent-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ExtendableMessageEvent` | 51 | 17 | 44 | No | 38 | 11.1 | 51 | 51 | 44 | 41 | 11.3 | 5.0 |
| `ExtendableMessageEvent` | 51 | 17 | 44 | No | 38 | 11.1 | 51 | 51 | 44 | 41 | 11.3 | 5.0 |
| `data` | 51 | 17 | 44 | No | 38 | 11.1 | 51 | 51 | 44 | 41 | 11.3 | 5.0 |
| `lastEventId` | 51 | 17 | 44 | No | 38 | 11.1 | 51 | 51 | 44 | 41 | 11.3 | 5.0 |
| `origin` | 51 | 17 | 44 | No | 38 | 11.1 | 51 | 51 | 44 | 41 | 11.3 | 5.0 |
| `ports` | 51 | 17 | 44 | No | 38 | 11.1 | 51 | 51 | 44 | 41 | 11.3 | 5.0 |
| `source` | 51 | 17 | 44 | No | 38 | 11.1 | 51 | 51 | 44 | 41 | 11.3 | 5.0 |


See also
--------


* [Using Service Workers](service_worker_api/using_service_workers)
* [Service workers basic code example](https://github.com/mdn/dom-examples/tree/main/service-worker/simple-service-worker)
* [Is ServiceWorker ready?](https://jakearchibald.github.io/isserviceworkerready/)
* [Channel Messaging](channel_messaging_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ExtendableMessageEvent>

EyeDropper
==========



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `EyeDropper` interface represents an instance of an eyedropper tool that can be opened and used by the user to select colors from the screen.



Constructor
-----------


 
[`EyeDropper()`](eyedropper/eyedropper)  Experimental 
  Returns a new `EyeDropper` instance.

  
Instance methods
----------------



*The `EyeDropper` interface doesn't inherit any methods*.

  
[`EyeDropper.open()`](eyedropper/open)  Experimental 
  Returns a promise that resolves to an object that gives access to the selected color.

  

Examples
--------


### Opening the eyedropper tool and sampling a color



This example shows how to open an eyedropper tool and wait for the user to either select a pixel from the screen, or press `Escape` to cancel the eyedropper mode.

 #### HTML

 
```
<button id="start-button">Open the eyedropper</button> <span id="result"></span>

```
 #### JavaScript

 
```
document.getElementById("start-button").addEventListener("click", () => {
  const resultElement = document.getElementById("result");

  if (!window.EyeDropper) {
    resultElement.textContent =
      "Your browser does not support the EyeDropper API";
    return;
  }

  const eyeDropper = new EyeDropper();

  eyeDropper
    .open()
    .then((result) => {
      resultElement.textContent = result.sRGBHex;
      resultElement.style.backgroundColor = result.sRGBHex;
    })
    .catch((e) => {
      resultElement.textContent = e;
    });
});

```
 #### Result




### Aborting the eyedropper mode



This example shows that the eyedropper mode can also be aborted before the user has selected a color or pressed `Escape`.

 #### HTML

 
```
<button id="start-button">Open the eyedropper</button> <span id="result"></span>

```
 #### JavaScript

 
```
document.getElementById("start-button").addEventListener("click", () => {
  const resultElement = document.getElementById("result");

  if (!window.EyeDropper) {
    resultElement.textContent =
      "Your browser does not support the EyeDropper API";
    return;
  }

  const eyeDropper = new EyeDropper();
  const abortController = new AbortController();

  eyeDropper
    .open({ signal: abortController.signal })
    .then((result) => {
      resultElement.textContent = result.sRGBHex;
      resultElement.style.backgroundColor = result.sRGBHex;
    })
    .catch((e) => {
      resultElement.textContent = e;
    });

  setTimeout(() => {
    abortController.abort();
  }, 2000);
});

```
 #### Result




Specifications
--------------




| Specification |
| --- |
| [EyeDropper API # eyedropper-interface](https://wicg.github.io/eyedropper-api/#eyedropper-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `EyeDropper` | 95 | 95 | No | No | 81 | No | No | No | No | No | No | No |
| `EyeDropper` | 95 | 95 | No | No | 81 | No | No | No | No | No | No | No |
| `open` | 95 | 95 | No | No | 81 | No | No | No | No | No | No | No |
| `secure_context_required` | 96 | 96 | No | No | 82 | No | No | No | No | No | No | No |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/EyeDropper>

FeaturePolicy
=============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `FeaturePolicy` interface represents the set of [Permissions Policies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy) applied to the current execution context.



Instance methods
----------------


 
[`FeaturePolicy.allowsFeature`](featurepolicy/allowsfeature)  Experimental 
  Returns a Boolean that indicates whether or not a particular feature is enabled in the specified context.

  
[`FeaturePolicy.features`](featurepolicy/features)  Experimental 
  Returns a list of names of all features supported by the User Agent. Features whose names appear on the list might not be allowed by the Permissions Policy of the current execution context and/or might be restricted by user-granted permissions.

  
[`FeaturePolicy.allowedFeatures`](featurepolicy/allowedfeatures)  Experimental 
  Returns a list of names of all features supported by the User Agent and allowed by the Permissions Policy. Note that features appearing on this list might still be behind a user permission.

  
[`FeaturePolicy.getAllowlistForFeature`](featurepolicy/getallowlistforfeature)  Experimental 
  Returns the allow for the specified feature.

  
Specifications
--------------



**No specification found**No specification data found for `api.FeaturePolicy`.  
[Check for problems with this page](#on-github) or contribute a missing `spec_url` to [mdn/browser-compat-data](https://github.com/mdn/browser-compat-data). Also make sure the specification is included in [w3c/browser-specs](https://github.com/w3c/browser-specs).



Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FeaturePolicy` | 74 | 79 | 65 | No | 62 | No | 74 | 74 | No | 53 | No | 11.0 |
| `allowedFeatures` | 74 | 79 | 65 | No | 62 | No | 74 | 74 | No | 53 | No | 11.0 |
| `allowsFeature` | 74 | 79 | 65 | No | 62 | No | 74 | 74 | No | 53 | No | 11.0 |
| `features` | 74 | 79 | 70 | No | 62 | No | 74 | 74 | No | 53 | No | 11.0 |
| `getAllowlistForFeature` | 74 | 79 | 65 | No | 62 | No | 74 | 74 | No | 53 | No | 11.0 |


See also
--------


* [`Permissions-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy)
* [Privacy, permissions, and information security](https://developer.mozilla.org/en-US/docs/Web/Privacy)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FeaturePolicy>

Element
=======



`Element` is the most general base class from which all element objects (i.e. objects that represent elements) in a [`Document`](document) inherit. It only has methods and properties common to all kinds of elements. More specific classes inherit from `Element`.

 For example, the [`HTMLElement`](htmlelement) interface is the base interface for HTML elements, while the [`SVGElement`](svgelement) interface is the basis for all SVG elements. Most functionality is specified further down the class hierarchy.

 Languages outside the realm of the Web platform, like XUL through the `XULElement` interface, also implement `Element`.


 EventTarget Node Element

Instance properties
-------------------



*`Element` inherits properties from its parent interface, [`Node`](node), and by extension that interface's parent, [`EventTarget`](eventtarget).*

  
[`Element.assignedSlot`](element/assignedslot) Read only 
  Returns a [`HTMLSlotElement`](htmlslotelement) representing the [`<slot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot) the node is inserted in.

  
[`Element.attributes`](element/attributes) Read only 
  Returns a [`NamedNodeMap`](namednodemap) object containing the assigned attributes of the corresponding HTML element.

  
[`Element.childElementCount`](element/childelementcount) Read only 
  Returns the number of child elements of this element.

  
[`Element.children`](element/children) Read only 
  Returns the child elements of this element.

  
[`Element.classList`](element/classlist) Read only 
  Returns a [`DOMTokenList`](domtokenlist) containing the list of class attributes.

  [`Element.className`](element/classname)  A string representing the class of the element.

  
[`Element.clientHeight`](element/clientheight) Read only 
  Returns a number representing the inner height of the element.

  
[`Element.clientLeft`](element/clientleft) Read only 
  Returns a number representing the width of the left border of the element.

  
[`Element.clientTop`](element/clienttop) Read only 
  Returns a number representing the width of the top border of the element.

  
[`Element.clientWidth`](element/clientwidth) Read only 
  Returns a number representing the inner width of the element.

  
[`Element.elementTiming`](element/elementtiming)  Experimental 
  A string reflecting the [`elementtiming`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/elementtiming) attribute which marks an element for observation in the [`PerformanceElementTiming`](performanceelementtiming) API.

  
[`Element.firstElementChild`](element/firstelementchild) Read only 
  Returns the first child element of this element.

  [`Element.id`](element/id)  A string representing the id of the element.

  [`Element.innerHTML`](element/innerhtml)  A string representing the markup of the element's content.

  
[`Element.lastElementChild`](element/lastelementchild) Read only 
  Returns the last child element of this element.

  
[`Element.localName`](element/localname) Read only 
  A string representing the local part of the qualified name of the element.

  
[`Element.namespaceURI`](element/namespaceuri) Read only 
  The namespace URI of the element, or `null` if it is no namespace.

  **Note:** In Firefox 3.5 and earlier, HTML elements are in no namespace. In later versions, HTML elements are in the [`http://www.w3.org/1999/xhtml`](https://www.w3.org/1999/xhtml/) namespace in both HTML and XML trees.

   
[`Element.nextElementSibling`](element/nextelementsibling) Read only 
  An [`Element`](element), the element immediately following the given one in the tree, or `null` if there's no sibling node.

  [`Element.outerHTML`](element/outerhtml)  A string representing the markup of the element including its content. When used as a setter, replaces the element with nodes parsed from the given string.

  [`Element.part`](element/part)  Represents the part identifier(s) of the element (i.e. set using the `part` attribute), returned as a [`DOMTokenList`](domtokenlist).

  
[`Element.prefix`](element/prefix) Read only 
  A string representing the namespace prefix of the element, or `null` if no prefix is specified.

  
[`Element.previousElementSibling`](element/previouselementsibling) Read only 
  An [`Element`](element), the element immediately preceding the given one in the tree, or `null` if there is no sibling element.

  
[`Element.scrollHeight`](element/scrollheight) Read only 
  Returns a number representing the scroll view height of an element.

  [`Element.scrollLeft`](element/scrollleft)  A number representing the left scroll offset of the element.

  
[`Element.scrollLeftMax`](element/scrollleftmax)  Non-standard  Read only 
  Returns a number representing the maximum left scroll offset possible for the element.

  [`Element.scrollTop`](element/scrolltop)  A number representing number of pixels the top of the element is scrolled vertically.

  
[`Element.scrollTopMax`](element/scrolltopmax)  Non-standard  Read only 
  Returns a number representing the maximum top scroll offset possible for the element.

  
[`Element.scrollWidth`](element/scrollwidth) Read only 
  Returns a number representing the scroll view width of the element.

  
[`Element.shadowRoot`](element/shadowroot) Read only 
  Returns the open shadow root that is hosted by the element, or null if no open shadow root is present.

  [`Element.slot`](element/slot)  Returns the name of the shadow DOM slot the element is inserted in.

  
[`Element.tagName`](element/tagname) Read only 
  Returns a string with the name of the tag for the given element.

  

### Instance properties included from ARIA



*The `Element` interface includes the following properties, defined on the `ARIAMixin` mixin.*

  [`Element.ariaAtomic`](element/ariaatomic)  A string reflecting the [`aria-atomic`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-atomic) attribute, which indicates whether assistive technologies will present all, or only parts of, the changed region based on the change notifications defined by the [`aria-relevant`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-relevant) attribute.

  [`Element.ariaAutoComplete`](element/ariaautocomplete)  A string reflecting the [`aria-autocomplete`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-autocomplete) attribute, which indicates whether inputting text could trigger display of one or more predictions of the user's intended value for a combobox, searchbox, or textbox and specifies how predictions would be presented if they were made.

  [`Element.ariaBusy`](element/ariabusy)  A string reflecting the [`aria-busy`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-busy) attribute, which indicates whether an element is being modified, as assistive technologies may want to wait until the modifications are complete before exposing them to the user.

  [`Element.ariaChecked`](element/ariachecked)  A string reflecting the [`aria-checked`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-checked) attribute, which indicates the current "checked" state of checkboxes, radio buttons, and other widgets that have a checked state.

  [`Element.ariaColCount`](element/ariacolcount)  A string reflecting the [`aria-colcount`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-colcount) attribute, which defines the number of columns in a table, grid, or treegrid.

  [`Element.ariaColIndex`](element/ariacolindex)  A string reflecting the [`aria-colindex`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-colindex) attribute, which defines an element's column index or position with respect to the total number of columns within a table, grid, or treegrid.

  [`Element.ariaColSpan`](element/ariacolspan)  A string reflecting the [`aria-colspan`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-colspan) attribute, which defines the number of columns spanned by a cell or gridcell within a table, grid, or treegrid.

  [`Element.ariaCurrent`](element/ariacurrent)  A string reflecting the [`aria-current`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-current) attribute, which indicates the element that represents the current item within a container or set of related elements.

  [`Element.ariaDescription`](element/ariadescription)  A string reflecting the [`aria-description`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-description) attribute, which defines a string value that describes or annotates the current element.

  [`Element.ariaDisabled`](element/ariadisabled)  A string reflecting the [`aria-disabled`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-disabled) attribute, which indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.

  [`Element.ariaExpanded`](element/ariaexpanded)  A string reflecting the [`aria-expanded`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-expanded) attribute, which indicates whether a grouping element owned or controlled by this element is expanded or collapsed.

  [`Element.ariaHasPopup`](element/ariahaspopup)  A string reflecting the [`aria-haspopup`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-haspopup) attribute, which indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an element.

  [`Element.ariaHidden`](element/ariahidden)  A string reflecting the [`aria-hidden`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-hidden) attribute, which indicates whether the element is exposed to an accessibility API.

  [`Element.ariaKeyShortcuts`](element/ariakeyshortcuts)  A string reflecting the [`aria-keyshortcuts`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-keyshortcuts) attribute, which indicates keyboard shortcuts that an author has implemented to activate or give focus to an element.

  [`Element.ariaLabel`](element/arialabel)  A string reflecting the [`aria-label`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) attribute, which defines a string value that labels the current element.

  [`Element.ariaLevel`](element/arialevel)  A string reflecting the [`aria-level`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-level) attribute, which defines the hierarchical level of an element within a structure.

  [`Element.ariaLive`](element/arialive)  A string reflecting the [`aria-live`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-live) attribute, which indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region.

  [`Element.ariaModal`](element/ariamodal)  A string reflecting the [`aria-modal`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-modal) attribute, which indicates whether an element is modal when displayed.

  [`Element.ariaMultiline`](element/ariamultiline)  A string reflecting the [`aria-multiline`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-multiline) attribute, which indicates whether a text box accepts multiple lines of input or only a single line.

  [`Element.ariaMultiSelectable`](element/ariamultiselectable)  A string reflecting the [`aria-multiselectable`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-multiselectable) attribute, which indicates that the user may select more than one item from the current selectable descendants.

  [`Element.ariaOrientation`](element/ariaorientation)  A string reflecting the [`aria-orientation`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-orientation) attribute, which indicates whether the element's orientation is horizontal, vertical, or unknown/ambiguous.

  [`Element.ariaPlaceholder`](element/ariaplaceholder)  A string reflecting the [`aria-placeholder`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-placeholder) attribute, which defines a short hint intended to aid the user with data entry when the control has no value.

  [`Element.ariaPosInSet`](element/ariaposinset)  A string reflecting the [`aria-posinset`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-posinset) attribute, which defines an element's number or position in the current set of listitems or treeitems.

  [`Element.ariaPressed`](element/ariapressed)  A string reflecting the [`aria-pressed`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-pressed) attribute, which indicates the current "pressed" state of toggle buttons.

  [`Element.ariaReadOnly`](element/ariareadonly)  A string reflecting the [`aria-readonly`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-readonly) attribute, which indicates that the element is not editable, but is otherwise operable.

  
[`Element.ariaRelevant`](element/ariarelevant)  Non-standard 
  A string reflecting the [`aria-relevant`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-relevant) attribute, which indicates what notifications the user agent will trigger when the accessibility tree within a live region is modified. This is used to describe what changes in an `aria-live` region are relevant and should be announced.

  [`Element.ariaRequired`](element/ariarequired)  A string reflecting the [`aria-required`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-required) attribute, which indicates that user input is required on the element before a form may be submitted.

  [`Element.ariaRoleDescription`](element/ariaroledescription)  A string reflecting the [`aria-roledescription`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-roledescription) attribute, which defines a human-readable, author-localized description for the role of an element.

  [`Element.ariaRowCount`](element/ariarowcount)  A string reflecting the [`aria-rowcount`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowcount) attribute, which defines the total number of rows in a table, grid, or treegrid.

  [`Element.ariaRowIndex`](element/ariarowindex)  A string reflecting the [`aria-rowindex`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowindex) attribute, which defines an element's row index or position with respect to the total number of rows within a table, grid, or treegrid.

  [`Element.ariaRowSpan`](element/ariarowspan)  A string reflecting the [`aria-rowspan`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-rowspan) attribute, which defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid.

  [`Element.ariaSelected`](element/ariaselected)  A string reflecting the [`aria-selected`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-selected) attribute, which indicates the current "selected" state of elements that have a selected state.

  [`Element.ariaSetSize`](element/ariasetsize)  A string reflecting the [`aria-setsize`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-setsize) attribute, which defines the number of items in the current set of listitems or treeitems.

  [`Element.ariaSort`](element/ariasort)  A string reflecting the [`aria-sort`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-sort) attribute, which indicates if items in a table or grid are sorted in ascending or descending order.

  [`Element.ariaValueMax`](element/ariavaluemax)  A string reflecting the [`aria-valueMax`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemax) attribute, which defines the maximum allowed value for a range widget.

  [`Element.ariaValueMin`](element/ariavaluemin)  A string reflecting the [`aria-valueMin`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuemin) attribute, which defines the minimum allowed value for a range widget.

  [`Element.ariaValueNow`](element/ariavaluenow)  A string reflecting the [`aria-valueNow`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuenow) attribute, which defines the current value for a range widget.

  [`Element.ariaValueText`](element/ariavaluetext)  A string reflecting the [`aria-valuetext`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-valuetext) attribute, which defines the human-readable text alternative of aria-valuenow for a range widget.

  

Instance methods
----------------



*`Element` inherits methods from its parents [`Node`](node), and its own parent, [`EventTarget`](eventtarget).*

  [`EventTarget.addEventListener()`](eventtarget/addeventlistener)  Registers an event handler to a specific event type on the element.

  [`Element.after()`](element/after)  Inserts a set of [`Node`](node) objects or strings in the children list of the `Element`'s parent, just after the `Element`.

  [`Element.attachShadow()`](element/attachshadow)  Attaches a shadow DOM tree to the specified element and returns a reference to its [`ShadowRoot`](shadowroot).

  [`Element.animate()`](element/animate)  A shortcut method to create and run an animation on an element. Returns the created Animation object instance.

  [`Element.append()`](element/append)  Inserts a set of [`Node`](node) objects or strings after the last child of the element.

  [`Element.before()`](element/before)  Inserts a set of [`Node`](node) objects or strings in the children list of the `Element`'s parent, just before the `Element`.

  [`Element.closest()`](element/closest)  Returns the [`Element`](element) which is the closest ancestor of the current element (or the current element itself) which matches the selectors given in parameter.

  [`Element.computedStyleMap()`](element/computedstylemap)  Returns a [`StylePropertyMapReadOnly`](stylepropertymapreadonly) interface which provides a read-only representation of a CSS declaration block that is an alternative to [`CSSStyleDeclaration`](cssstyledeclaration).

  [`EventTarget.dispatchEvent()`](eventtarget/dispatchevent)  Dispatches an event to this node in the DOM and returns a boolean value that indicates whether no handler canceled the event.

  [`Element.getAnimations()`](element/getanimations)  Returns an array of Animation objects currently active on the element.

  [`Element.getAttribute()`](element/getattribute)  Retrieves the value of the named attribute from the current node and returns it as a string.

  [`Element.getAttributeNames()`](element/getattributenames)  Returns an array of attribute names from the current element.

  [`Element.getAttributeNode()`](element/getattributenode)  Retrieves the node representation of the named attribute from the current node and returns it as an [`Attr`](attr).

  [`Element.getAttributeNodeNS()`](element/getattributenodens)  Retrieves the node representation of the attribute with the specified name and namespace, from the current node and returns it as an [`Attr`](attr).

  [`Element.getAttributeNS()`](element/getattributens)  Retrieves the value of the attribute with the specified namespace and name from the current node and returns it as a string.

  [`Element.getBoundingClientRect()`](element/getboundingclientrect)  Returns the size of an element and its position relative to the viewport.

  
`Element.getBoxQuads()`  Experimental 
  Returns a list of [`DOMQuad`](domquad) objects representing the CSS fragments of the node.

  [`Element.getClientRects()`](element/getclientrects)  Returns a collection of rectangles that indicate the bounding rectangles for each line of text in a client.

  [`Element.getElementsByClassName()`](element/getelementsbyclassname)  Returns a live [`HTMLCollection`](htmlcollection) that contains all descendants of the current element that possess the list of classes given in the parameter.

  [`Element.getElementsByTagName()`](element/getelementsbytagname)  Returns a live [`HTMLCollection`](htmlcollection) containing all descendant elements, of a particular tag name, from the current element.

  [`Element.getElementsByTagNameNS()`](element/getelementsbytagnamens)  Returns a live [`HTMLCollection`](htmlcollection) containing all descendant elements, of a particular tag name and namespace, from the current element.

  [`Element.hasAttribute()`](element/hasattribute)  Returns a boolean value indicating if the element has the specified attribute or not.

  [`Element.hasAttributeNS()`](element/hasattributens)  Returns a boolean value indicating if the element has the specified attribute, in the specified namespace, or not.

  [`Element.hasAttributes()`](element/hasattributes)  Returns a boolean value indicating if the element has one or more HTML attributes present.

  [`Element.hasPointerCapture()`](element/haspointercapture)  Indicates whether the element on which it is invoked has pointer capture for the pointer identified by the given pointer ID.

  [`Element.insertAdjacentElement()`](element/insertadjacentelement)  Inserts a given element node at a given position relative to the element it is invoked upon.

  [`Element.insertAdjacentHTML()`](element/insertadjacenthtml)  Parses the text as HTML or XML and inserts the resulting nodes into the tree in the position given.

  [`Element.insertAdjacentText()`](element/insertadjacenttext)  Inserts a given text node at a given position relative to the element it is invoked upon.

  [`Element.matches()`](element/matches)  Returns a boolean value indicating whether or not the element would be selected by the specified selector string.

  [`Element.prepend()`](element/prepend)  Inserts a set of [`Node`](node) objects or strings before the first child of the element.

  [`Element.querySelector()`](element/queryselector)  Returns the first [`Node`](node) which matches the specified selector string relative to the element.

  [`Element.querySelectorAll()`](element/queryselectorall)  Returns a [`NodeList`](nodelist) of nodes which match the specified selector string relative to the element.

  [`Element.releasePointerCapture()`](element/releasepointercapture)  Releases (stops) pointer capture that was previously set for a specific [`pointer event`](pointerevent).

  [`Element.remove()`](element/remove)  Removes the element from the children list of its parent.

  [`Element.removeAttribute()`](element/removeattribute)  Removes the named attribute from the current node.

  [`Element.removeAttributeNode()`](element/removeattributenode)  Removes the node representation of the named attribute from the current node.

  [`Element.removeAttributeNS()`](element/removeattributens)  Removes the attribute with the specified name and namespace, from the current node.

  [`EventTarget.removeEventListener()`](eventtarget/removeeventlistener)  Removes an event listener from the element.

  [`Element.replaceChildren()`](element/replacechildren)  Replaces the existing children of a [`Node`](node) with a specified new set of children.

  [`Element.replaceWith()`](element/replacewith)  Replaces the element in the children list of its parent with a set of [`Node`](node) objects or strings.

  [`Element.requestFullscreen()`](element/requestfullscreen)  Asynchronously asks the browser to make the element fullscreen.

  [`Element.requestPointerLock()`](element/requestpointerlock)  Allows to asynchronously ask for the pointer to be locked on the given element.

  [`Element.scroll()`](element/scroll)  Scrolls to a particular set of coordinates inside a given element.

  [`Element.scrollBy()`](element/scrollby)  Scrolls an element by the given amount.

  [`Element.scrollIntoView()`](element/scrollintoview)  Scrolls the page until the element gets into the view.

  
[`Element.scrollIntoViewIfNeeded()`](element/scrollintoviewifneeded)  Non-standard 
  Scrolls the current element into the visible area of the browser window if it's not already within the visible area of the browser window. **Use the standard [`Element.scrollIntoView()`](element/scrollintoview) instead.**

  [`Element.scrollTo()`](element/scrollto)  Scrolls to a particular set of coordinates inside a given element.

  [`Element.setAttribute()`](element/setattribute)  Sets the value of a named attribute of the current node.

  [`Element.setAttributeNode()`](element/setattributenode)  Sets the node representation of the named attribute from the current node.

  [`Element.setAttributeNodeNS()`](element/setattributenodens)  Sets the node representation of the attribute with the specified name and namespace, from the current node.

  [`Element.setAttributeNS()`](element/setattributens)  Sets the value of the attribute with the specified name and namespace, from the current node.

  
[`Element.setCapture()`](element/setcapture)  Non-standard   Deprecated 
  Sets up mouse event capture, redirecting all mouse events to this element.

  
[`Element.setHTML()`](element/sethtml)  Experimental 
  Parses and [sanitizes](html_sanitizer_api) a string of HTML and inserts into the DOM as a subtree of the element.

  [`Element.setPointerCapture()`](element/setpointercapture)  Designates a specific element as the capture target of future [pointer events](pointer_events).

  [`Element.toggleAttribute()`](element/toggleattribute)  Toggles a boolean attribute, removing it if it is present and adding it if it is not present, on the specified element.

  

Events
------



Listen to these events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface.

  
[`beforematch`](element/beforematch_event)  Experimental 
  Fires on an element that is in the [*hidden until found*](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/hidden) state, when the browser is about to reveal its content because the user has found the content through the "find in page" feature or through fragment navigation.

  [`cancel`](htmldialogelement/cancel_event)  Fires on a [`<dialog>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog) when the user instructs the browser that they wish to dismiss the currently open modal dialog. The browser fires this event when the user presses the `Esc` key to close the modal dialog.

  
[`contentvisibilityautostatechange`](element/contentvisibilityautostatechange_event)  Experimental 
  Fires on any element with [`content-visibility: auto`](https://developer.mozilla.org/en-US/docs/Web/CSS/content-visibility) set on it when it starts or stops being [relevant to the user](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Containment#relevant_to_the_user) and [skipping its contents](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Containment#skips_its_contents).

  [`error`](element/error_event)  Fired when a resource failed to load, or can't be used. For example, if a script has an execution error or an image can't be found or is invalid.

  [`scroll`](element/scroll_event)  Fired when the document view or an element has been scrolled.

  [`securitypolicyviolation`](element/securitypolicyviolation_event)  Fired when a [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) is violated.

  [`select`](htmlinputelement/select_event)  Fired when some text has been selected.

  [`wheel`](element/wheel_event)  Fired when the user rotates a wheel button on a pointing device (typically a mouse).

  

### Clipboard events


 [`copy`](element/copy_event)   Fired when the user initiates a copy action through the browser's user interface. Also available via the [`oncopy`](htmlelement/copy_event) property. 

  [`cut`](element/cut_event)   Fired when the user initiates a cut action through the browser's user interface. Also available via the [`oncut`](htmlelement/cut_event) property. 

  [`paste`](element/paste_event)   Fired when the user initiates a paste action through the browser's user interface. Also available via the [`onpaste`](htmlelement/paste_event) property. 

  
### Composition events


 [`compositionend`](element/compositionend_event)  Fired when a text composition system such as an [input method editor](https://developer.mozilla.org/en-US/docs/Glossary/Input_method_editor) completes or cancels the current composition session.

  [`compositionstart`](element/compositionstart_event)  Fired when a text composition system such as an [input method editor](https://developer.mozilla.org/en-US/docs/Glossary/Input_method_editor) starts a new composition session.

  [`compositionupdate`](element/compositionupdate_event)  Fired when a new character is received in the context of a text composition session controlled by a text composition system such as an [input method editor](https://developer.mozilla.org/en-US/docs/Glossary/Input_method_editor).

  
### Focus events


 [`blur`](element/blur_event)  Fired when an element has lost focus.

  [`focus`](element/focus_event)  Fired when an element has gained focus.

  [`focusin`](element/focusin_event)  Fired when an element has gained focus, after [`focus`](element/focus_event).

  [`focusout`](element/focusout_event)  Fired when an element has lost focus, after [`blur`](element/blur_event).

  
### Fullscreen events


 [`fullscreenchange`](element/fullscreenchange_event)  Sent to an [`Element`](element) when it transitions into or out of [fullscreen](fullscreen_api/guide) mode.

  [`fullscreenerror`](element/fullscreenerror_event)  Sent to an `Element` if an error occurs while attempting to switch it into or out of [fullscreen](fullscreen_api/guide) mode.

  
### Keyboard events


 [`keydown`](element/keydown_event)  Fired when a key is pressed.

  
[`keypress`](element/keypress_event)  Deprecated 
  Fired when a key that produces a character value is pressed down.

  [`keyup`](element/keyup_event)  Fired when a key is released.

  
### Mouse events


 [`auxclick`](element/auxclick_event)  Fired when a non-primary pointing device button (e.g., any mouse button other than the left button) has been pressed and released on an element.

  [`click`](element/click_event)  Fired when a pointing device button (e.g., a mouse's primary button) is pressed and released on a single element.

  [`contextmenu`](element/contextmenu_event)  Fired when the user attempts to open a context menu.

  [`dblclick`](element/dblclick_event)  Fired when a pointing device button (e.g., a mouse's primary button) is clicked twice on a single element.

  
[`DOMActivate`](element/domactivate_event)  Deprecated 
  Occurs when an element is activated, for instance, through a mouse click or a keypress.

  [`mousedown`](element/mousedown_event)  Fired when a pointing device button is pressed on an element.

  [`mouseenter`](element/mouseenter_event)  Fired when a pointing device (usually a mouse) is moved over the element that has the listener attached.

  [`mouseleave`](element/mouseleave_event)  Fired when the pointer of a pointing device (usually a mouse) is moved out of an element that has the listener attached to it.

  [`mousemove`](element/mousemove_event)  Fired when a pointing device (usually a mouse) is moved while over an element.

  [`mouseout`](element/mouseout_event)  Fired when a pointing device (usually a mouse) is moved off the element to which the listener is attached or off one of its children.

  [`mouseover`](element/mouseover_event)  Fired when a pointing device is moved onto the element to which the listener is attached or onto one of its children.

  [`mouseup`](element/mouseup_event)  Fired when a pointing device button is released on an element.

  
[`webkitmouseforcechanged`](element/webkitmouseforcechanged_event)  Non-standard 
  Fired each time the amount of pressure changes on the trackpadtouchscreen.

  
[`webkitmouseforcedown`](element/webkitmouseforcedown_event)  Non-standard 
  Fired after the mousedown event as soon as sufficient pressure has been applied to qualify as a "force click".

  
[`webkitmouseforcewillbegin`](element/webkitmouseforcewillbegin_event)  Non-standard 
  Fired before the [`mousedown`](element/mousedown_event) event.

  
[`webkitmouseforceup`](element/webkitmouseforceup_event)  Non-standard 
  Fired after the [`webkitmouseforcedown`](element/webkitmouseforcedown_event) event as soon as the pressure has been reduced sufficiently to end the "force click".

  
### Touch events


 [`touchcancel`](element/touchcancel_event)  Fired when one or more touch points have been disrupted in an implementation-specific manner (for example, too many touch points are created).

  [`touchend`](element/touchend_event)  Fired when one or more touch points are removed from the touch surface.

  [`touchmove`](element/touchmove_event)  Fired when one or more touch points are moved along the touch surface.

  [`touchstart`](element/touchstart_event)  Fired when one or more touch points are placed on the touch surface.

  
Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-element](https://dom.spec.whatwg.org/#interface-element) |
| [Pointer Events # extensions-to-the-element-interface](https://w3c.github.io/pointerevents/#extensions-to-the-element-interface) |
| [Pointer Lock 2.0 # extensions-to-the-element-interface](https://w3c.github.io/pointerlock/#extensions-to-the-element-interface) |
| [Fullscreen API Standard # api](https://fullscreen.spec.whatwg.org/#api) |
| [DOM Parsing and Serialization # extensions-to-the-element-interface](https://w3c.github.io/DOM-Parsing/#extensions-to-the-element-interface) |
| [CSSOM View Module # extension-to-the-element-interface](https://w3c.github.io/csswg-drafts/cssom-view/#extension-to-the-element-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `DOMActivate_event` | 1 | 79 | 1 | No | 15 | 1 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `DOMMouseScroll_event` | No | No | 1 | No | No | No | No | No | 4 | No | No | No |
| `MozMousePixelScroll_event` | No | No | 6 | No | No | No | No | No | 6 | No | No | No |
| `Element` | 1 | 12 | 1 | 4 | 8 | 1 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 |
| `after` | 54 | 17 | 49 | No | 39 | 10 | 54 | 54 | 49 | 41 | 10 | 6.0 |
| `afterscriptexecute_event` | No | No | 2 | No | No | No | No | No | 4 | No | No | No |
| `animate` | 36 | 79 | 48 | No | 23 | 13.1 | 37 | 36 | 48 | 24 | 13.4 | 3.0 |
| `animationcancel_event` | 83The `onanimationcancel` event handler property is not supported. To listen to this event, use `element.addEventListener('animationcancel', function() {});`. See [bug 868224](https://crbug.com/868224). | 83The `onanimationcancel` event handler property is not supported. To listen to this event, use `element.addEventListener('animationcancel', function() {});`. See [bug 868224](https://crbug.com/868224). | 54 | No | 69The `onanimationcancel` event handler property is not supported. To listen to this event, use `element.addEventListener('animationcancel', function() {});`. See [bug 868224](https://crbug.com/868224). | 13.112–13.1Although the `onanimationcancel` event handler property is supported, the `animationcancel` event is never fired. | 83The `onanimationcancel` event handler property is not supported. To listen to this event, use `element.addEventListener('animationcancel', function() {});`. See [bug 868224](https://crbug.com/868224). | 83The `onanimationcancel` event handler property is not supported. To listen to this event, use `element.addEventListener('animationcancel', function() {});`. See [bug 868224](https://crbug.com/868224). | 54 | 59The `onanimationcancel` event handler property is not supported. To listen to this event, use `element.addEventListener('animationcancel', function() {});`. See [bug 868224](https://crbug.com/868224). | 13.412–13.4Although the `onanimationcancel` event handler property is supported, the `animationcancel` event is never fired. | 13.0The `onanimationcancel` event handler property is not supported. To listen to this event, use `element.addEventListener('animationcancel', function() {});`. See [bug 868224](https://crbug.com/868224). |
| `animationend_event` | 817943–79The `onanimationend` event handler property is not supported. To listen to this event, use `document.addEventListener('animationend', function() {});`. | 811812–18The `onanimationend` event handler property is not supported. To listen to this event, use `document.addEventListener('animationend', function() {});`. | 515–51The `onanimationend` event handler property is not supported. To listen to this event, use `document.addEventListener('animationend', function() {});`. | 10The `onanimationend` event handler property is not supported. To listen to this event, use `document.addEventListener('animationend', function() {});`. | 686630–66The `onanimationend` event handler property is not supported. To listen to this event, use `document.addEventListener('animationend', function() {});`. | 9 | 817943–79The `onanimationend` event handler property is not supported. To listen to this event, use `document.addEventListener('animationend', function() {});`. | 817943–79The `onanimationend` event handler property is not supported. To listen to this event, use `document.addEventListener('animationend', function() {});`. | 515–51The `onanimationend` event handler property is not supported. To listen to this event, use `document.addEventListener('animationend', function() {});`. | 585730–57The `onanimationend` event handler property is not supported. To listen to this event, use `document.addEventListener('animationend', function() {});`. | 9 | 13.012.04.0–12.0The `onanimationend` event handler property is not supported. To listen to this event, use `document.addEventListener('animationend', function() {});`. |
| `animationiteration_event` | 817943–79The `onanimationiteration` event handler property is not supported. To listen to this event, use `document.addEventListener('animationiteration', function() {});`. | 811812–18The `onanimationiteration` event handler property is not supported. To listen to this event, use `document.addEventListener('animationiteration', function() {});`. | 515–51The `onanimationiteration` event handler property is not supported. To listen to this event, use `document.addEventListener('animationiteration', function() {});`. | 10The `onanimationiteration` event handler property is not supported. To listen to this event, use `document.addEventListener('animationiteration', function() {});`. | 686630–66The `onanimationiteration` event handler property is not supported. To listen to this event, use `document.addEventListener('animationiteration', function() {});`. | 9 | 817943–79The `onanimationiteration` event handler property is not supported. To listen to this event, use `document.addEventListener('animationiteration', function() {});`. | 817943–79The `onanimationiteration` event handler property is not supported. To listen to this event, use `document.addEventListener('animationiteration', function() {});`. | 515–51The `onanimationiteration` event handler property is not supported. To listen to this event, use `document.addEventListener('animationiteration', function() {});`. | 585730–57The `onanimationiteration` event handler property is not supported. To listen to this event, use `document.addEventListener('animationiteration', function() {});`. | 9 | 13.012.04.0–12.0The `onanimationiteration` event handler property is not supported. To listen to this event, use `document.addEventListener('animationiteration', function() {});`. |
| `animationstart_event` | 817943–79The `onanimationstart` event handler property is not supported. To listen to this event, use `document.addEventListener('animationstart', function() {});`. | 811812–18The `onanimationstart` event handler property is not supported. To listen to this event, use `document.addEventListener('animationstart', function() {});`. | 515–51The `onanimationstart` event handler property is not supported. To listen to this event, use `document.addEventListener('animationstart', function() {});`. | 10The `onanimationstart` event handler property is not supported. To listen to this event, use `document.addEventListener('animationstart', function() {});`. | 686630–66The `onanimationstart` event handler property is not supported. To listen to this event, use `document.addEventListener('animationstart', function() {});`. | 9 | 817943–79The `onanimationstart` event handler property is not supported. To listen to this event, use `document.addEventListener('animationstart', function() {});`. | 817943–79The `onanimationstart` event handler property is not supported. To listen to this event, use `document.addEventListener('animationstart', function() {});`. | 515–51The `onanimationstart` event handler property is not supported. To listen to this event, use `document.addEventListener('animationstart', function() {});`. | 585730–57The `onanimationstart` event handler property is not supported. To listen to this event, use `document.addEventListener('animationstart', function() {});`. | 9 | 13.012.04.0–12.0The `onanimationstart` event handler property is not supported. To listen to this event, use `document.addEventListener('animationstart', function() {});`. |
| `append` | 54 | 17 | 49 | No | 41 | 10 | 54 | 54 | 49 | 41 | 10 | 6.0 |
| `ariaAtomic` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaAutoComplete` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaBusy` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaChecked` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaColCount` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaColIndex` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaColSpan` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaCurrent` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaDescription` | 83 | 83 | No | No | 69 | No | 83 | 83 | No | 59 | No | 13.0 |
| `ariaDisabled` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaExpanded` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaHasPopup` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaHidden` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaInvalid` | 102 | 102 | No | No | 88 | 12.1 | 102 | 102 | No | 70 | 12.2 | 19.0 |
| `ariaKeyShortcuts` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaLabel` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaLevel` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaLive` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaModal` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaMultiLine` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaMultiSelectable` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaOrientation` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaPlaceholder` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaPosInSet` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaPressed` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaReadOnly` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaRelevant` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaRequired` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaRoleDescription` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaRowCount` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaRowIndex` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaRowSpan` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaSelected` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaSetSize` | 84 | 84 | No | No | 70 | 12.1 | 84 | 84 | No | 60 | 12.2 | 14.0 |
| `ariaSort` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaValueMax` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaValueMin` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaValueNow` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `ariaValueText` | 81 | 81 | No | No | 68 | 12.1 | 81 | 81 | No | 58 | 12.2 | 13.0 |
| `assignedSlot` | 53 | 79 | 63 | No | 40 | 10 | 53 | 53 | 63 | 41 | 10 | 6.0 |
| `attachShadow` | 53 | 79 | 63 | No | 40 | 10 | 53 | 53 | 63 | 41 | 10 | 6.0 |
| `attributes` | 1 | 12 | 1 | 5.5 | 8 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `auxclick_event` | 55 | 79 | 53Starting in Firefox 68, the `auxclick` event is used to trigger the *new tab on middle-click* action; previously, this had been done with the `click` event. Apps can prevent middle-click from opening new tabs (or middle-click to paste, if that feature is enabled) by intercepting `auxclick` on links, and `auxclick` event handlers can now open popups without triggering the popup blocker. | No | 42 | No | 55 | 55 | 53 | 42 | No | 6.0 |
| `before` | 54 | 17 | 49 | No | 39 | 10 | 54 | 54 | 49 | 41 | 10 | 6.0 |
| `beforematch_event` | 102 | 102 | No | No | No | No | 102 | 102 | No | 70 | No | 19.0 |
| `beforescriptexecute_event` | No | No | 2 | No | No | No | No | No | 4 | No | No | No |
| `beforexrselect_event` | 83 | 83 | No | No | 69 | No | 83 | 83 | No | 59 | No | 13.0 |
| `blur_event` | 1 | 12 | 246–24The interface for this event is [`Event`](https://developer.mozilla.org/docs/Web/API/Event), not [`FocusEvent`](https://developer.mozilla.org/docs/Web/API/FocusEvent). | 9 | 11.6 | 3.1 | 4.4 | 18 | 246–24The interface for this event is [`Event`](https://developer.mozilla.org/docs/Web/API/Event), not [`FocusEvent`](https://developer.mozilla.org/docs/Web/API/FocusEvent). | 12.1 | 2 | 1.0 |
| `checkVisibility` | 105 | 105 | 106 | No | 91 | No | 105 | 105 | 106 | 72 | No | 20.0 |
| `childElementCount` | 2 | 12 | 3.5 | 9 | 10 | 4 | ≤37 | 18 | 4 | 10.1 | 3 | 1.0 |
| `children` | 1 | 12 | 3.5 | 96–9Also includes non-standard `HTMLCommentElement` nodes. | 10 | 4 | 4.4 | 18 | 4 | 10.1 | 3 | 1.0 |
| `classList` | 228–22Not supported for SVG elements. | 1612–16Not supported for SVG elements. | 3.6 | 10Not supported for SVG elements. | 11.5 | 76–7Not supported for SVG elements. | 4.43–4.4Not supported for SVG elements. | 2518–25Not supported for SVG elements. | 4 | 11.5 | 76–7Not supported for SVG elements. | 1.51.0–1.5Not supported for SVG elements. |
| `className` | 221–22Only supported for [`HTMLElement`](https://developer.mozilla.org/docs/Web/API/HTMLElement), not all `Element` objects, such as [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement). | 12 | 1 | 5 | 8 | 1 | 4.4 | 2518–25Only supported for [`HTMLElement`](https://developer.mozilla.org/docs/Web/API/HTMLElement), not all `Element` objects, such as [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement). | 4 | 10.1 | 1 | 1.51.0–1.5Only supported for [`HTMLElement`](https://developer.mozilla.org/docs/Web/API/HTMLElement), not all `Element` objects, such as [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement). |
| `click_event` | 1 | 12 | 6Beginning in Firefox 68, Firefox no longer incorrectly sends a `click` event for buttons other than the primary mouse button; previously, there were circumstances in which this would occur. One example: middle-clicking a link would send a `click` to the document's `<html>` element. | 9 | 11.6 | 3 | 4.4 | 18 | 6 | 12.1 | 1 | 1.0 |
| `clientHeight` | 1 | 12 | 1 | 5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `clientLeft` | 1 | 12 | 3 | 5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `clientTop` | 1 | 12 | 3 | 5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `clientWidth` | 1 | 12 | 1 | 5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `closest` | 41 | 15 | 35 | No | 28 | 6 | 41 | 41 | 35 | 28 | 9 | 4.0 |
| `compositionend_event` | 15 | 12 | 9 | 11 | ≤15 | 5 | ≤37 | 18 | 9 | ≤14 | 5 | 1.0 |
| `compositionstart_event` | 15 | 12 | 9 | 11 | ≤15 | 5 | ≤37 | 18 | 9 | ≤14 | 5 | 1.0 |
| `compositionupdate_event` | 18 | 12 | 9 | 11 | 15 | 5 | ≤37 | 18 | 9 | 14 | 5 | 1.0 |
| `computedStyleMap` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `contentvisibilityautostatechange_event` | 108 | 108 | 110 | No | 94 | No | 108 | 108 | No | 73 | No | No |
| `contextmenu_event` | 1 | 12 | 6 | 9 | 10.5 | 3 | 4.4 | 18 | 6 | 11.1 | NoSee [bug 213953](https://webkit.org/b/213953). | 1.0 |
| `copy_event` | 1 | 12 | 22 | 9Before Internet Explorer 9, this event is not supported via `addEventListener`; however, the event handler is supported since IE 5.5. The event can be listened to via `element.oncopy`. | ≤12.1 | 3 | 4.4 | 18 | 22 | ≤12.1 | 3 | 1.0 |
| `cut_event` | 1 | 12 | 22 | 9Before Internet Explorer 9, this event is not supported via `addEventListener`; however, the event handler is supported since IE 5.5. The event can be listened to via `element.oncopy`. | ≤12.1 | 3 | 4.4 | 18 | 22 | ≤12.1 | 3 | 1.0 |
| `dblclick_event` | 1 | 12 | 6Starting in Firefox 68, `dblclick` events are only sent for the primary mouse button, per the specification. | 8 | 11.6 | 3 | No | No | 6 | 12.1 | 1 | No |
| `elementTiming` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |
| `error_event` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `firstElementChild` | 2 | 12 | 3.5 | 9 | 10 | 4 | ≤37 | 18 | 4 | 10.1 | 3 | 1.0 |
| `focus_event` | 1 | 12 | 246–24The interface for this event is [`Event`](https://developer.mozilla.org/docs/Web/API/Event), not [`FocusEvent`](https://developer.mozilla.org/docs/Web/API/FocusEvent). | 9 | 11.6 | 3.1 | 4.4 | 18 | 246–24The interface for this event is [`Event`](https://developer.mozilla.org/docs/Web/API/Event), not [`FocusEvent`](https://developer.mozilla.org/docs/Web/API/FocusEvent). | 12.1 | 2 | 1.0 |
| `focusin_event` | 1 | 12 | 52 | 9 | 11.6 | 5 | ≤37 | 18 | 52 | 12.1 | 4.2 | 1.0 |
| `focusout_event` | 1 | 12 | 52 | 9 | 11.6 | 5 | ≤37 | 18 | 52 | 12.1 | 4.2 | 1.0 |
| `fullscreenchange_event` | 7115 | 791212–14 | 6410 | No | 581512.1–15 | 16.45.1 | 71≤37 | 7118 | 6410 | 501412.1–14 | 12Only available on iPad, not on iPhone. | 10.01.0 |
| `fullscreenerror_event` | 7118 | 791212–14 | 6410 | No | 581512.1–15 | 16.46 | 71≤37 | 7118 | 6410 | 501412.1–14 | 12Only available on iPad, not on iPhone. | 10.01.0 |
| `gesturechange_event` | No | No | No | No | No | 9.1 | No | No | No | No | 2 | No |
| `gestureend_event` | No | No | No | No | No | 9.1 | No | No | No | No | 2 | No |
| `gesturestart_event` | No | No | No | No | No | 9.1 | No | No | No | No | 2 | No |
| `getAnimations` | 84 | 84 | 75 | No | 70 | 13.1 | 84 | 84 | 79 | 60 | 13.4 | 14.0 |
| `getAttribute` | 1 | 12 | 1 | 5 | 8 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `getAttributeNS` | 1 | 12 | 1Starting in Firefox 13, `null` is always returned instead of the empty string, as per the DOM4 specification. Previously, there were cases in which an empty string could be returned. | 9 | ≤12.1 | 1 | 4.4 | 18 | 4Starting in Firefox 13, `null` is always returned instead of the empty string, as per the DOM4 specification. Previously, there were cases in which an empty string could be returned. | ≤12.1 | 1 | 1.0 |
| `getAttributeNames` | 61 | 18 | 45 | No | 48 | 10.1 | 61 | 61 | 45 | 45 | 10.3 | 8.0 |
| `getAttributeNode` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `getAttributeNodeNS` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `getBoundingClientRect` | 2 | 12 | 3 | 4 | 9.5 | 4 | 2 | 18 | 4 | 10.1 | 3.2Safari for iOS will modify the effective viewport based on the user zoom. This results in incorrect values whenever the user has zoomed. | 1.0 |
| `getBoxQuads` | No | No | 31 | No | No | No | No | No | No | No | No | No |
| `getClientRects` | 2 | 12 | 3 | 5 | 9.5 | 4 | 2 | 18 | 4 | 10.1 | 3.2 | 1.0 |
| `getElementsByClassName` | 1 | 1612–16Only supported for [`HTMLElement`](https://developer.mozilla.org/docs/Web/API/HTMLElement), not all `Element` objects, such as [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement). | 3Before Firefox 19, this method was returning a `NodeList`; it was then changed to reflect the change in the spec. | 9Only supported for [`HTMLElement`](https://developer.mozilla.org/docs/Web/API/HTMLElement), not all `Element` objects, such as [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement). | 9.5 | 3.1 | 4.4 | 18 | 4 | 10.1 | 2 | 1.0 |
| `getElementsByTagName` | 1Initially, this method was returning a `NodeList`; it was then changed to reflect the spec change. | 12 | 1Before Firefox 19, this method was returning a `NodeList`; it was then changed to reflect the change in the spec. | 5.5 | 8Initially, this method was returning a `NodeList`; it was then changed to reflect the spec change. | 1Initially, this method was returning a `NodeList`; it was then changed to reflect the spec change. | 4.4Initially, this method was returning a `NodeList`; it was then changed to reflect the spec change. | 18Initially, this method was returning a `NodeList`; it was then changed to reflect the spec change. | 4Before Firefox 19, this method was returning a `NodeList`; it was then changed to reflect the change in the spec. | 10.1 | 1Initially, this method was returning a `NodeList`; it was then changed to reflect the spec change. | 1.0Initially, this method was returning a `NodeList`; it was then changed to reflect the spec change. |
| `getElementsByTagNameNS` | 1Initially, this method was returning a `NodeList`; it was then changed to reflect the spec change. | 12 | 1["The behavior of `element.getElementsByTagNameNS` changed between Firefox 3.5 and Firefox 3.6. In Firefox 3.5 and before, this function would automatically case-fold any queries so that a search for \"foo\" would match \"Foo\" or \"foo\". In Firefox 3.6 and later this function is now case-sensitive so that a query for \"foo\" will only match \"foo\" and not \"Foo\". For more background on this, please see the [comment from Henri Sivonen about the change](https://bugzil.la/542185#c5). You can also look at the [relevant part of the standard, which states which parts of the API are case-sensitive and which parts aren't](https://developer.mozilla.org/docs/Case_Sensitivity_in_class_and_id_Names).", "Before Firefox 19, this method was returning a `NodeList`; it was then changed to reflects the spec change."] | 9 | ≤12.1Initially, this method was returning a `NodeList`; it was then changed to reflect the spec change. | 1Initially, this method was returning a `NodeList`; it was then changed to reflect the spec change. | 4.4Initially, this method was returning a `NodeList`; it was then changed to reflect the spec change. | 18Initially, this method was returning a `NodeList`; it was then changed to reflect the spec change. | 4Before Firefox 19, this method was returning a `NodeList`; it was then changed to reflects the spec change. | ≤12.1Initially, this method was returning a `NodeList`; it was then changed to reflect the spec change. | 1Initially, this method was returning a `NodeList`; it was then changed to reflect the spec change. | 1.0Initially, this method was returning a `NodeList`; it was then changed to reflect the spec change. |
| `gotpointercapture_event` | 57 | 17 | 59 | No | 44 | 13 | 57 | 57 | 79 | 43 | 13 | 7.0 |
| `hasAttribute` | 1 | 12 | 1 | 8 | 8 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `hasAttributeNS` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `hasAttributes` | 1 | 12 | 1Before Firefox 35, it was implemented on the `Node` interface. | 8 | ≤12.1 | 1 | 4.4 | 18 | 4Before Firefox 35, it was implemented on the `Node` interface. | ≤12.1 | 1 | 1.0 |
| `hasPointerCapture` | 55 | 79 | 59 | No | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `id` | 231–23Only supported for [`HTMLElement`](https://developer.mozilla.org/docs/Web/API/HTMLElement), not all `Element` objects, such as [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement). | 12 | 1 | 5 | ≤12.1 | 1 | 4.4 | 2518–25Only supported for [`HTMLElement`](https://developer.mozilla.org/docs/Web/API/HTMLElement), not all `Element` objects, such as [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement). | 4 | ≤12.1 | 1 | 1.51.0–1.5Only supported for [`HTMLElement`](https://developer.mozilla.org/docs/Web/API/HTMLElement), not all `Element` objects, such as [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement). |
| `innerHTML` | 1 | 12 | 1 | 4 | 8 | 1 | 1 | 18 | 4 | 10.1 | 1 | 1.0 |
| `insertAdjacentElement` | 1 | 1712–17Only supported for [`HTMLElement`](https://developer.mozilla.org/docs/Web/API/HTMLElement), not all `Element` objects, such as [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement). | 48 | 5Only supported for [`HTMLElement`](https://developer.mozilla.org/docs/Web/API/HTMLElement), not all `Element` objects, such as [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement). | 8 | 3 | 4.4 | 18 | 48 | 10.1 | 1 | 1.0 |
| `insertAdjacentHTML` | 1 | 1712–17Only supported for [`HTMLElement`](https://developer.mozilla.org/docs/Web/API/HTMLElement), not all `Element` objects, such as [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement). | 8 | 4["Before Internet Explorer 10, throws an \"Invalid target element for this operation.\" error when called on a `<table>`, `<tbody>`, `<thead>`, or `<tr>` element.", "Only supported for [`HTMLElement`](https://developer.mozilla.org/docs/Web/API/HTMLElement), not all `Element` objects, such as [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement)."] | 8 | 4 | ≤37 | 18 | 8 | 10.1 | 4 | 1.0 |
| `insertAdjacentText` | 1 | 1712–17Only supported for [`HTMLElement`](https://developer.mozilla.org/docs/Web/API/HTMLElement), not all `Element` objects, such as [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement). | 48 | 5Only supported for [`HTMLElement`](https://developer.mozilla.org/docs/Web/API/HTMLElement), not all `Element` objects, such as [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement). | ≤12.1 | 4 | 2.2 | 18 | 48 | ≤12.1 | 4 | 1.0 |
| `keydown_event` | 1 | 12 | 6 | 9 | ≤12.1 | 1.2 | 4.4 | 18 | 6 | ≤12.1 | 1 | 1.0 |
| `keypress_event` | 1Chrome does not fire the `keypress` event for [known keyboard shortcuts](https://crbug.com/13891#c50). Which keyboard shortcuts are known depends on the user's system. Use the `keydown` event to implement keyboard shortcuts. | 12 | 6As of Firefox 65, the `keypress` event is no longer fired for [non-printable keys](https://developer.mozilla.org/docs/Web/API/KeyboardEvent/keyCode#Non-printable_keys_(function_keys)), except for the Enter key, and the Shift + Enter and Ctrl + Enter key combinations (these were kept for cross-browser compatibility purposes). | 9 | ≤12.1Opera does not fire the `keypress` event for [known keyboard shortcuts](https://crbug.com/13891#c50). Which keyboard shortcuts are known depends on the user's system. Use the `keydown` event to implement keyboard shortcuts. | 1.3 | 1Chrome does not fire the `keypress` event for [known keyboard shortcuts](https://crbug.com/13891#c50). Which keyboard shortcuts are known depends on the user's system. Use the `keydown` event to implement keyboard shortcuts. | 18Chrome does not fire the `keypress` event for [known keyboard shortcuts](https://crbug.com/13891#c50). Which keyboard shortcuts are known depends on the user's system. Use the `keydown` event to implement keyboard shortcuts. | 6As of Firefox 65, the `keypress` event is no longer fired for [non-printable keys](https://developer.mozilla.org/docs/Web/API/KeyboardEvent/keyCode#Non-printable_keys_(function_keys)), except for the Enter key, and the Shift + Enter and Ctrl + Enter key combinations (these were kept for cross-browser compatibility purposes). | ≤12.1Opera does not fire the `keypress` event for [known keyboard shortcuts](https://crbug.com/13891#c50). Which keyboard shortcuts are known depends on the user's system. Use the `keydown` event to implement keyboard shortcuts. | 1 | 1.0Samsung Internet does not fire the `keypress` event for [known keyboard shortcuts](https://crbug.com/13891#c50). Which keyboard shortcuts are known depends on the user's system. Use the `keydown` event to implement keyboard shortcuts. |
| `keyup_event` | 1 | 12 | 6 | 9 | ≤12.1 | 1.2 | 4.4 | 18 | 6 | ≤12.1 | 1 | 1.0 |
| `lastElementChild` | 2 | 12 | 3.5 | 9 | 10 | 4 | ≤37 | 18 | 4 | 10.1 | 3 | 1.0 |
| `localName` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `lostpointercapture_event` | 57 | 17 | 59 | No | 44 | 13 | 57 | 57 | 79 | 43 | 13 | 7.0 |
| `matches` | 334 | 151212–79 | 44343.6["Before Firefox 4, invalid selector strings caused false to be returned instead of throwing an exception.", "See [bug 1119718](https://bugzil.la/1119718) for removal."] | 9 | 211511.5–15 | 85 | ≤374.4 | 3318 | 44344See [bug 1119718](https://bugzil.la/1119718) for removal. | 211411.5–14 | 84.2 | 2.01.0 |
| `mousedown_event` | 2 | 12 | 6 | 9 | 11.6 | 4 | ≤37 | 18 | 6 | 12.1 | 3.2 | 1.0 |
| `mouseenter_event` | 30 | 12 | 10 | 5.5 | 17 | 7 | ≤37 | 30 | 10 | 18 | 7 | 2.0 |
| `mouseleave_event` | 30 | 12 | 10 | 5.5 | 17 | 7 | ≤37 | 30 | 10 | 18 | 7 | 2.0 |
| `mousemove_event` | 2 | 12 | 6 | 9 | 11.6 | 4 | ≤37 | 18 | 6 | 12.1 | 3.2 | 1.0 |
| `mouseout_event` | 1 | 12 | 6 | 9 | ≤12.1 | 1 | ≤37 | 18 | 6 | ≤12.1 | 1 | 1.0 |
| `mouseover_event` | 2 | 12 | 6 | 9 | 9.5 | 4 | ≤37 | 18 | 6 | 10.1 | 3.2 | 1.0 |
| `mouseup_event` | 2 | 12 | 6 | 9 | 11.6 | 4 | ≤37 | 18 | 6 | 12.1 | 3.2 | 1.0 |
| `mousewheel_event` | 1 | 12 | No | 9 | ≤15 | 3 | 4.4 | 18 | No | ≤14 | 1 | 1.0 |
| `namespaceURI` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `nextElementSibling` | 2 | 12 | 3.5 | 9 | 10 | 4 | ≤37 | 18 | 4 | 10.1 | 3 | 1.0 |
| `outerHTML` | 1 | 12 | 11 | 4 | 8 | 1.3 | 1 | 18 | 14 | 10.1 | 1 | 1.0 |
| `part` | 73 | 79 | 72 | No | 60 | 13.1 | 73 | 73 | 79 | 52 | 13.4 | 11.0 |
| `paste_event` | 1 | 12 | 22 | 9["Before Internet Explorer 11, copying files does not trigger the `paste` event.", "Before Internet Explorer 9, this event is not supported via `addEventListener`; however, the event handler is supported since IE 5.5. The event can be listened to via `element.oncopy`."] | ≤12.1 | 3 | ≤37 | 18 | 22 | ≤12.1 | 3 | 1.0 |
| `pointercancel_event` | 55 | 1212–79 | 59 | 1110 | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `pointerdown_event` | 55 | 1212–79 | 59 | 1110 | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `pointerenter_event` | 55 | 1212–79 | 59 | 1110 | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `pointerleave_event` | 55 | 1212–79 | 59 | 1110 | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `pointermove_event` | 55 | 1212–79 | 59 | 1110 | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `pointerout_event` | 55 | 1212–79 | 59 | 1110 | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `pointerover_event` | 55 | 1212–79 | 59 | 1110 | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `pointerrawupdate_event` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |
| `pointerup_event` | 55 | 1212–79 | 59 | 1110 | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `prefix` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `prepend` | 54 | 17 | 49 | No | 41 | 10 | 54 | 54 | 49 | 41 | 10 | 6.0 |
| `previousElementSibling` | 2 | 12 | 3.5 | 9 | 10 | 4 | ≤37 | 18 | 4 | 10.1 | 3 | 1.0 |
| `querySelector` | 1 | 12 | 3.5 | 98`querySelector()` is supported, but only for CSS 2.1 selectors. | 10 | 3.1 | 4.4 | 18 | 4 | 10.1 | 2 | 1.0 |
| `querySelectorAll` | 1 | 12 | 3.5 | 98`querySelectorAll()` is supported, but only for CSS 2.1 selectors. | 10 | 3.1 | 4.4 | 18 | 4 | 10.1 | 2 | 1.0 |
| `releasePointerCapture` | 55 | 12 | 59 | 1110 | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `remove` | 24 | 12 | 23 | No | 15 | 7 | 4.4 | 25 | 23 | 14 | 7 | 1.5 |
| `removeAttribute` | 1 | 12This function doesn't respect boolean attributes' default values. See [bug 12087679](https://developer.microsoft.com/microsoft-edge/platform/issues/12087679/). | 1 | 5 | 8 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `removeAttributeNS` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `removeAttributeNode` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `replaceChildren` | 86 | 86 | 78 | No | 72 | 14 | 86 | 86 | 79 | 61 | 14 | 14.0 |
| `replaceWith` | 54 | 17 | 49 | No | 39 | 10 | 54 | 54 | 49 | 41 | 10 | 6.0 |
| `requestFullscreen` | 7115 | 791212–14 | 649Before Firefox 44, Firefox incorrectly allowed elements inside a `<frame>` or `<object>` element to request, and to be granted, fullscreen. In Firefox 44 and onwards this has been fixed: only elements in the top-level document or in an `<iframe>` element with the `allowfullscreen` attribute can be displayed fullscreen. | 11 | 581512.1–15 | 16.45.1 | 71≤37 | 7118 | 649Before Firefox 44, Firefox incorrectly allowed elements inside a `<frame>` or an `<object>` to request, and to be granted, fullscreen. In Firefox 44 and onwards this has been fixed: only elements in the top-level document or in an ``<iframe>`` with the `allowfullscreen` attribute can be displayed fullscreen. | 501412.1–14 | 12Only available on iPad, not on iPhone. Shows an overlay button which can not be disabled. | 10.01.0 |
| `requestPointerLock` | 37From version 92, returns a promise instead of `undefined`. The behavior reflects [a proposed specification change](https://github.com/w3c/pointerlock/pull/49).22–38 | 13From version 92, returns a promise instead of `undefined`. The behavior reflects [a proposed specification change](https://github.com/w3c/pointerlock/pull/49). | 5014–50 | No | 24From version 78, returns a promise instead of `undefined`. The behavior reflects [a proposed specification change](https://github.com/w3c/pointerlock/pull/49).15–25 | 10.1 | 37From version 92, returns a promise instead of `undefined`. The behavior reflects [a proposed specification change](https://github.com/w3c/pointerlock/pull/49).4.4–38 | 37From version 92, returns a promise instead of `undefined`. The behavior reflects [a proposed specification change](https://github.com/w3c/pointerlock/pull/49).25–38 | 5014–50 | 24From version 65, returns a promise instead of `undefined`. The behavior reflects [a proposed specification change](https://github.com/w3c/pointerlock/pull/49).14–25 | No | 3.0From version 16, returns a promise instead of `undefined`. The behavior reflects [a proposed specification change](https://github.com/w3c/pointerlock/pull/49).1.5–3.0 |
| `role` | 103 | 103 | No | No | 89 | 12.1 | 103 | 103 | No | 71 | 12.2 | 20.0 |
| `scroll` | 61 | 79 | 36 | No | 48 | 10.1 | 61 | 61 | 36 | 45 | 10.3 | 8.0 |
| `scrollBy` | 61 | 79 | 36 | No | 48 | 10.1 | 61 | 61 | 36 | 45 | 10.3 | 8.0 |
| `scrollHeight` | 1 | 12 | 213–21Before Firefox 21, when an element's content does not generate a vertical scrollbar, then its `scrollHeight` property is equal to its `clientHeight` property. This can mean either the content is too short to require a scrollbar or that the element has a CSS style `overflow` value of `visible` (non-scrollable). | 5In Internet Explorer 5 through 7, if padding is set, the value of `scrollHeight` is equal to the sum of the top and bottom padding. This behavior was fixed in Internet Explorer 8. | 8 | 1 | 4.4 | 18 | 214–21Before Firefox 21, when an element's content does not generate a vertical scrollbar, then its `scrollHeight` property is equal to its `clientHeight` property. This can mean either the content is too short to require a scrollbar or that the element has a CSS style `overflow` value of `visible` (non-scrollable). | 10.1 | 1 | 1.0 |
| `scrollIntoView` | 1 | 7917–79The only parameter supported is `alignToTop`.12–17["Only supported for [`HTMLElement`](https://developer.mozilla.org/docs/Web/API/HTMLElement), not all `Element` objects, such as [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement).", "No support for `smooth` behavior."] | 1 | 5["Only supported for [`HTMLElement`](https://developer.mozilla.org/docs/Web/API/HTMLElement), not all `Element` objects, such as [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement).", "No support for `smooth` behavior or `center` options."] | ≤12.1 | 3["No support for `center` option.", "Before Safari 15.4, there was no support for the `smooth` behavior."] | 4.4 | 18 | 4 | ≤12.1 | 1["No support for `center` option.", "Before iOS 15.4, there was no support for the `smooth` behavior."] | 1.0 |
| `scrollIntoViewIfNeeded` | 1 | 79 | No | No | 15 | 3 | 4.4 | 18 | No | 14 | 1 | 1.0 |
| `scrollLeft` | 861–86For right-to-left elements, this property uses 0-100 (most left to most right) instead of negative values. See [bug 721759](https://crbug.com/721759). | 8612–86For right-to-left elements, this property uses 0-100 (most left to most right) instead of negative values. See [bug 721759](https://crbug.com/721759). | 1 | 5For right-to-left elements, this property uses 100-0 (most left to most right) instead of negative values. | 8 | 1 | 864.4–86For right-to-left elements, this property uses 0-100 (most left to most right) instead of negative values. See [bug 721759](https://crbug.com/721759). | 8618–86For right-to-left elements, this property uses 0-100 (most left to most right) instead of negative values. See [bug 721759](https://crbug.com/721759). | 4 | 10.1 | 1 | 14.01.0–14.0For right-to-left elements, this property uses 0-100 (most left to most right) instead of negative values. See [bug 721759](https://crbug.com/721759). |
| `scrollLeftMax` | No | No | 16 | No | No | No | No | No | 16 | No | No | No |
| `scrollTo` | 61 | 79 | 36 | No | 48 | 10.1 | 61 | 61 | 36 | 45 | 10.3 | 8.0 |
| `scrollTop` | 1 | 12 | 1 | 5 | 8 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `scrollTopMax` | No | No | 16 | No | No | No | No | No | 16 | No | No | No |
| `scrollWidth` | 1 | 12 | 1 | 5In Internet Explorer 5 through 7, if padding is set, the value of `scrollWidth` is equal to the sum of the left and right padding. This behavior was fixed in Internet Explorer 8. | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `scroll_event` | 1 | 12 | 6 | 9 | ≤12.1 | 1.3 | 4.4 | 18 | 6 | ≤12.1 | 1 | 1.0 |
| `scrollend_event` | preview | No | 109 | No | No | No | No | No | 109 | No | No | No |
| `securitypolicyviolation_event` | 41 | 15 | 63 | No | 28 | 10 | 41 | 41 | 63 | 28 | 10 | 4.0 |
| `setAttribute` | 1 | 12 | 1 | 5In Internet Explorer 7 and earlier, `setAttribute` doesn't set styles and removes events when you try to set them. | 8 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `setAttributeNS` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `setAttributeNode` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `setAttributeNodeNS` | 1 | 12Returns a `ClientRectList` with [`ClientRect`](https://docs.microsoft.com/en-us/previous-versions/hh826029(v=vs.85)) objects (which do not contain `x` and `y` properties) instead of [`DOMRect`](https://developer.mozilla.org/docs/Web/API/DOMRect) objects. | 1 | 9Returns a `ClientRectList` with [`ClientRect`](https://docs.microsoft.com/en-us/previous-versions/hh826029(v=vs.85)) objects (which do not contain `x` and `y` properties) instead of [`DOMRect`](https://developer.mozilla.org/docs/Web/API/DOMRect) objects. | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `setCapture` | No | 12–79 | 4 | 5The `retargetToElement` parameter to `Element.setCapture()` was introduced in Internet Explorer 5.5. | No | No | No | No | 4 | No | No | No |
| `setHTML` | 105 | 105 | 94 | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `setPointerCapture` | 55 | 12 | 59Before Firefox 82, `setPointerCapture()` throws `InvalidPointerId` for an invalid `pointerId` argument. From Firefox 82, it throws [the specified](https://w3c.github.io/pointerevents/#setting-pointer-capture) `NotFoundError` exception. See [bug 1662124](https://bugzil.la/1662124). | 1110 | 42 | 13 | 55 | 55 | 79Before Firefox 82, `setPointerCapture()` throws `InvalidPointerId` for an invalid `pointerId` argument. From Firefox 82, it throws [the specified](https://w3c.github.io/pointerevents/#setting-pointer-capture) `NotFoundError` exception. See [bug 1662124](https://bugzil.la/1662124). | 42 | 13 | 6.0 |
| `shadowRoot` | 35 | 79 | 63 | No | 22 | 10 | 37 | 35 | 63 | 22 | 10 | 3.0 |
| `slot` | 53 | 79 | 63 | No | 40 | 10 | 53 | 53 | 63 | 41 | 10 | 6.0 |
| `tagName` | 1 | 12 | 1 | 5 | 8 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `toggleAttribute` | 69 | 18 | 63 | No | 56 | 12 | 69 | 69 | 63 | 48 | 12 | 10.0 |
| `touchcancel_event` | 22 | 12 | 52 | No | No | No | 4.4 | 25 | 6 | 14 | ≤3 | 1.5 |
| `touchend_event` | 22 | 12 | 52 | No | No | No | 4.4 | 25 | 6 | 14 | ≤3 | 1.5 |
| `touchmove_event` | 22 | 12 | 52 | No | No | No | 4.4 | 25 | 6 | 14 | ≤3 | 1.5 |
| `touchstart_event` | 22 | 12 | 52 | No | No | No | 4.4 | 25 | 6 | 14 | ≤3 | 1.5 |
| `transitioncancel_event` | 8774–87The `ontransitioncancel` event handler property is not supported. To listen to this event, use `element.addEventListener('transitioncancel', function() {});`. | 8779–87The `ontransitioncancel` event handler property is not supported. To listen to this event, use `element.addEventListener('transitioncancel', function() {});`. | 53 | No | 7362–73The `ontransitioncancel` event handler property is not supported. To listen to this event, use `element.addEventListener('transitioncancel', function() {});`. | 13.112–13.1Although the `ontransitioncancel` event handler property is supported, the `transitioncancel` event is never fired. | 8774–87The `ontransitioncancel` event handler property is not supported. To listen to this event, use `element.addEventListener('transitioncancel', function() {});`. | 8774–87The `ontransitioncancel` event handler property is not supported. To listen to this event, use `element.addEventListener('transitioncancel', function() {});`. | 53 | 6253–62The `ontransitioncancel` event handler property is not supported. To listen to this event, use `element.addEventListener('transitioncancel', function() {});`. | 13.412–13.4Although the `ontransitioncancel` event handler property is supported, the `transitioncancel` event is never fired. | 14.011.0–14.0The `ontransitioncancel` event handler property is not supported. To listen to this event, use `element.addEventListener('transitioncancel', function() {});`. |
| `transitionend_event` | 261 | 791812–18The `ontransitionend` event handler property is not supported. To listen to this event, use `element.addEventListener('transitionend', function() {});`. | 51 | 10The `ontransitionend` event handler property is not supported. To listen to this event, use `element.addEventListener('transitionend', function() {});`. | 1512.111.6–15 | 74 | 4.44.4 | 2618 | 51 | 1412.112–14 | 73.2 | 1.51.0 |
| `transitionrun_event` | 74 | 12 | 53 | 10The `ontransitionrun` event handler property is not supported. To listen to this event, use `element.addEventListener('transitionrun', function() {});`. | 62 | 13.112The event handler exists but will never be called. | 74 | 74 | 53 | 53 | 13.412The event handler exists but will never be called. | 11.0 |
| `transitionstart_event` | 74 | 12 | 53 | 10The `ontransitionstart` event handler property is not supported. To listen to this event, use `element.addEventListener('transitionstart', function() {});`. | 62 | 13.112The event handler exists but will never be called. | 74 | 74 | 53 | 53 | 13.412The event handler exists but will never be called. | 11.0 |
| `webkitmouseforcechanged_event` | No | No | No | No | No | 9 | No | No | No | No | No | No |
| `webkitmouseforcedown_event` | No | No | No | No | No | 9 | No | No | No | No | No | No |
| `webkitmouseforceup_event` | No | No | No | No | No | 9 | No | No | No | No | No | No |
| `webkitmouseforcewillbegin_event` | No | No | No | No | No | 9 | No | No | No | No | No | No |
| `wheel_event` | 31 | 12 | 17 | 9The `onwheel` event handler property is not supported. To listen to this event, use `element.addEventListener('wheel', function() {});`. See [IE bug 782835](https://connect.microsoft.com/IE/feedback/details/782835/missing-onwheel-attribute-for-the-wheel-event-although-its-supported-via-addeventlistener). | 18 | 7 | 4.4.3 | 31 | 17 | 18 | No | 2.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Element>

FederatedCredential
===================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `FederatedCredential` interface of the [Credential Management API](credential_management_api) provides information about credentials from a federated identity provider. A federated identity provider is an entity that a website trusts to correctly authenticate a user, and that provides an API for that purpose. [OpenID Connect](https://openid.net/developers/specs/) is an example of a federated identity provider framework.

  **Note:** The [Federated Credential Management API (FedCM)](fedcm_api) provides a more complete solution for handling identity federation in the browser, and uses the [`IdentityCredential`](identitycredential) type.

  In browsers that support it, an instance of this interface may be passed in the `credential` member of the `init` object for global [`fetch()`](fetch).


 Credential FederatedCredential

Constructor
-----------


 
[`FederatedCredential()`](federatedcredential/federatedcredential)  Experimental 
  Creates a new `FederatedCredential` object.

  
Instance properties
-------------------



*Inherits properties from its ancestor, [`Credential`](credential).*

  
[`FederatedCredential.provider`](federatedcredential/provider) Read only   Experimental 
  Returns a string containing a credential's federated identity provider.

  
[`FederatedCredential.protocol`](federatedcredential/protocol) Read only   Experimental 
  Returns a string containing a credential's federated identity protocol.

  

### Event handlers


None.


Instance methods
----------------


None.


Examples
--------



```
const cred = new FederatedCredential({
  id,
  name,
  provider: "https://account.google.com",
  iconURL,
});

// Store it
navigator.credentials.store(cred).then(() => {
  // Do something else.
});

```

Specifications
--------------




| Specification |
| --- |
| [Credential Management Level 1 # federated](https://w3c.github.io/webappsec-credential-management/#federated) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FederatedCredential` | 51 | 79 | No | No | 38 | No | 51 | 51 | No | 41 | No | 5.0 |
| `FederatedCredential` | 51 | 79 | No | No | 38 | No | 51 | 51 | No | 41 | No | 5.0 |
| `iconURL` | 51 | 79 | No | No | 38 | No | 51 | 51 | No | 41 | No | 6.0 |
| `name` | 51 | 79 | No | No | 38 | No | 51 | 51 | No | 41 | No | 6.0 |
| `protocol` | 51 | 79 | No | No | 38 | No | 51 | 51 | No | 41 | No | 5.0 |
| `provider` | 51 | 79 | No | No | 38 | No | 51 | 51 | No | 41 | No | 5.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FederatedCredential>

FetchEvent
==========



This is the event type for `fetch` events dispatched on the [service worker global scope](serviceworkerglobalscope). It contains information about the fetch, including the request and how the receiver will treat the response. It provides the [`event.respondWith()`](fetchevent/respondwith) method, which allows us to provide a response to this fetch.


 Event ExtendableEvent FetchEvent

Constructor
-----------


 [`FetchEvent()`](fetchevent/fetchevent)  Creates a new `FetchEvent` object. This constructor is not typically used. The browser creates these objects itself and provides them to `fetch` event callbacks.

  
Instance properties
-------------------



*Inherits properties from its ancestor, [`Event`](event)*.

  
[`FetchEvent.clientId`](fetchevent/clientid) Read only 
  The [`id`](client/id) of the same-origin [`client`](client) that initiated the fetch.

  
[`FetchEvent.handled`](fetchevent/handled) Read only 
  A promise that is pending while the event has not been handled, and fulfilled once it has.

  
[`FetchEvent.preloadResponse`](fetchevent/preloadresponse) Read only 
  A [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) for a [`Response`](response), or `undefined` if this fetch is not a navigation, or [navigation preload](navigationpreloadmanager) is not enabled.

  
[`FetchEvent.replacesClientId`](fetchevent/replacesclientid) Read only 
  The [`id`](client/id) of the [`client`](client) that is being replaced during a page navigation.

  
[`FetchEvent.resultingClientId`](fetchevent/resultingclientid) Read only 
  The [`id`](client/id) of the [`client`](client) that replaces the previous client during a page navigation.

  
[`FetchEvent.request`](fetchevent/request) Read only 
  The [`Request`](request) the browser intends to make.

  

Instance methods
----------------



*Inherits methods from its parent, [`ExtendableEvent`](extendableevent)*.

  [`FetchEvent.respondWith()`](fetchevent/respondwith)  Prevent the browser's default fetch handling, and provide (a promise for) a response yourself.

  [`ExtendableEvent.waitUntil()`](extendableevent/waituntil)  Extends the lifetime of the event. Used to notify the browser of tasks that extend beyond the returning of a response, such as streaming and caching.

  

Examples
--------



 This fetch event uses the browser default for non-GET requests. For GET requests it tries to return a match in the cache, and falls back to the network. If it finds a match in the cache, it asynchronously updates the cache for next time. 

 
```
self.addEventListener("fetch", (event) => {
  // Let the browser do its default thing
  // for non-GET requests.
  if (event.request.method !== "GET") return;

  // Prevent the default, and handle the request ourselves.
  event.respondWith(
    (async () => {
      // Try to get the response from a cache.
      const cache = await caches.open("dynamic-v1");
      const cachedResponse = await cache.match(event.request);

      if (cachedResponse) {
        // If we found a match in the cache, return it, but also
        // update the entry in the cache in the background.
        event.waitUntil(cache.add(event.request));
        return cachedResponse;
      }

      // If we didn't find a match in the cache, use the network.
      return fetch(event.request);
    })()
  );
});

```


Specifications
--------------




| Specification |
| --- |
| [Service Workers # fetchevent-interface](https://w3c.github.io/ServiceWorker/#fetchevent-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FetchEvent` | 44 | 17 | 44 | No | 31 | 11.1 | 44 | 44 | 44 | 32 | 11.3 | 4.0 |
| `FetchEvent` | 40 | 17 | 44 | No | 27 | 11.1 | 40 | 40 | 44 | 27 | 11.3 | 4.0 |
| `clientId` | 49 | 17 | 45 | No | 36 | 11.1 | 49 | 49 | 45 | 36 | 11.3 | 5.0 |
| `handled` | 86 | 86 | 84 | No | 72 | 16 | 86 | 86 | 84 | 61 | 16 | 14.0 |
| `isReload` | 40May be removed in a future release, see [bug 652994](https://crbug.com/652994). | 17 | 44–74 | No | 27 | No | 40 | 40May be removed in a future release, see [bug 652994](https://crbug.com/652994). | 44–79 | 27 | No | 4.0 |
| `preloadResponse` | 59 | 18 | 99 | No | 46 | 15.4 | 59 | 59 | 99 | 43 | 15.4 | 7.0 |
| `replacesClientId` | No | No | No | No | No | 11.1–16See [bug 226638](https://webkit.org/b/226638). | No | No | No | No | 11.3–16See [bug 226638](https://webkit.org/b/226638). | No |
| `request` | 40 | 17 | 44 | No | 27 | 11.1 | 40 | 40 | 44 | 27 | 11.3 | 4.0 |
| `respondWith` | 42 | 17 | 44 | No | 29 | 11.1 | 42 | 42 | 44 | 29 | 11.3 | 4.0 |
| `resultingClientId` | 72 | 79 | 65 | No | 60 | 16 | 72 | 72 | 65 | 50 | 16 | 11.0 |


See also
--------


* [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
* [Fetch API](fetch_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent>

File
====



The `File` interface provides information about files and allows JavaScript in a web page to access their content.

 `File` objects are generally retrieved from a [`FileList`](filelist) object returned as a result of a user selecting files using the [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) element, or from a drag and drop operation's [`DataTransfer`](datatransfer) object.

 A `File` object is a specific kind of [`Blob`](blob), and can be used in any context that a Blob can. In particular, [`FileReader`](filereader), [`URL.createObjectURL()`](url/createobjecturl), [`createImageBitmap()`](createimagebitmap), and [`XMLHttpRequest.send()`](xmlhttprequest#send()) accept both `Blob`s and `File`s.

 See [Using files from web applications](file_api/using_files_from_web_applications) for more information and examples.


 Blob File

Constructor
-----------


 [`File()`](file/file)  Returns a newly constructed `File`.

  
Instance properties
-------------------



 
[`File.prototype.lastModified`](file/lastmodified) Read only 
  Returns the last modified time of the file, in millisecond since the UNIX epoch (January 1st, 1970 at Midnight).

  
[`File.prototype.lastModifiedDate`](file/lastmodifieddate)  Deprecated  Read only   Non-standard 
  Returns the last modified [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) of the file referenced by the `File` object.

  
[`File.prototype.name`](file/name) Read only 
  Returns the name of the file referenced by the `File` object.

  
[`File.prototype.webkitRelativePath`](file/webkitrelativepath) Read only 
  Returns the path the URL of the [`File`](file) is relative to.

   `File` implements [`Blob`](blob), so it also has the following properties available to it:

  
[`File.prototype.size`](blob/size) Read only 
  Returns the size of the file in bytes.

  
[`File.prototype.type`](file/type) Read only 
  Returns the [MIME](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) type of the file.

  

Instance methods
----------------



*The `File` interface doesn't define any methods, but inherits methods from the [`Blob`](blob) interface:*

  [`Blob.prototype.slice([start[, end[, contentType]]])`](blob/slice)  Returns a new `Blob` object containing the data in the specified range of bytes of the source `Blob`.

  [`Blob.prototype.stream()`](blob/stream)  Transforms the `File` into a [`ReadableStream`](readablestream) that can be used to read the `File` contents.

  [`Blob.prototype.text()`](blob/text)  Transforms the `File` into a stream and reads it to completion. It returns a promise that resolves with a string (text).

  [`Blob.prototype.arrayBuffer()`](blob/arraybuffer)  Transforms the `File` into a stream and reads it to completion. It returns a promise that resolves with an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer).

  

Specifications
--------------




| Specification |
| --- |
| [File API # file-section](https://w3c.github.io/FileAPI/#file-section) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `File` | 38 | 79 | 28 | No | 25 | 10.1 | 38 | 38 | 28 | 25 | 10.3 | 3.0 |
| `File` | 13 | 12 | 73–7Non-standard implementation. | 10 | 11.5 | 4 | ≤37 | 18 | 74–7Non-standard implementation. | 11.5 | 3.2 | 1.0 |
| `lastModified` | 13 | 18 | 15 | No | ≤15 | 10 | ≤37 | 18 | 15 | ≤14 | 10 | 1.0 |
| `lastModifiedDate` | 13 | 12 | 15–61 | 10 | ≤15 | 7–10 | ≤37 | 18 | No | ≤14 | 7–10 | 1.0 |
| `name` | 13 | 12 | 3.6 | 10 | ≤15 | 8 | ≤37 | 18 | 4 | ≤14 | 8 | 1.0 |
| `type` | 13 | 12 | 3.6 | 10 | ≤15 | 8 | ≤37 | 18 | 4 | ≤14 | 8 | 1.0 |
| `webkitRelativePath` | 13 | 13 | 50 | No | 15 | 11.1 | ≤37 | 18 | 50 | 14 | 11.3 | 1.0 |


See also
--------


* [Using files from web applications](file_api/using_files_from_web_applications)
* [`FileReader`](filereader)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/File>

FileEntrySync
=============



**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.


**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The `FileEntrySync` interface represents a file in a file system. It lets you write content to a file.

   **Warning:** This interface is deprecated and is no more on the standard track. *Do not use it anymore.* Use the [File and Directory Entries API](file_and_directory_entries_api) instead. 

 

Basic concepts
--------------


To write content to file, create a FileWriter object by calling [`createWriter()`](#createwriter).


Method overview
---------------




|  |
| --- |
| `FileWriterSync
[createWriter](#createreader) ());` |
| `File [file](#file) ());` |


Instance methods
----------------


### createWriter()



Creates a new `FileWriter` associated with the file that the `FileEntry` represents.

 
```
void createWriter ();

```
 #### Parameter

 None.

 #### Returns

 A `FileWriterSync` object.

 #### Exceptions

 This method can raise a [DOMException](domexception) with the following codes:

 

| Exception | Description |
| --- | --- |
| `NOT_FOUND_ERR` | The file does not exist. |
| `INVALID_STATE_ERR` | The file is no longer valid for some reason other than it having been deleted. |



### file()



Returns a File that represents the current state of the file that this `FileEntry` represents.

 
```
void file ();

```
 #### Parameter

 None.

 #### Returns

 A `File` object.

 #### Exceptions

 This method can raise a [DOMException](domexception) with the following codes:

 

| Exception | Description |
| --- | --- |
| `NOT_FOUND_ERR` | The file does not exist. |
| `INVALID_STATE_ERR` | The file is no longer valid for some reason other than it having been deleted. |



Specifications
--------------


This feature is not part of any specification anymore. It is no longer on track to become a standard.


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FileEntrySync` | 13 | 79 | No | No | No | No | 37 | 18 | No | No | No | 1.0 |


See also
--------


* [File and Directory Entries API](file_and_directory_entries_api/introduction)
* [Basic Concepts About the File and Directory Entries API](file_and_directory_entries_api/introduction)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FileEntrySync>

FileList
========



An object of this type is returned by the `files` property of the HTML [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) element; this lets you access the list of files selected with the `<input type="file">` element. It's also used for a list of files dropped into web content when using the drag and drop API; see the [`DataTransfer`](datatransfer) object for details on this usage.

 All `<input>` element nodes have a `files` attribute of type `FileList` on them which allows access to the items in this list. For example, if the HTML includes the following file input:

 
```
<input id="fileItem" type="file" />

```
 The following line of code fetches the first file in the node's file list as a [`File`](file) object:

 
```
const file = document.getElementById("fileItem").files[0];

```
  **Note:** This interface was an [attempt to create an unmodifiable list](https://stackoverflow.com/questions/74630989/why-use-domstringlist-rather-than-an-array/74641156#74641156) and only continues to be supported to not break code that's already using it. Modern APIs use types that wrap around ECMAScript array types instead, so you can treat them like ECMAScript arrays, and at the same time impose additional semantics on their usage (such as making their items read-only).

 

Instance properties
-------------------


 
[`length`](filelist/length) Read only 
  A read-only value indicating the number of files in the list.

  
Instance methods
----------------


 
[`item()`](filelist/item) Read only 
  Returns a [`File`](file) object representing the file at the specified index in the file list.

  
Example
-------


### Logging filenames



In this example, we log the names of all the files selected by the user.

 #### HTML

 
```
<input id="myfiles" multiple type="file" />
<pre class="output">Selected files:</pre>

```
 #### CSS

 
```
.output {
  overflow: scroll;
  margin: 1rem 0;
  height: 200px;
}

```
 #### JavaScript

 
```
const output = document.querySelector(".output");
const fileInput = document.querySelector("#myfiles");

fileInput.addEventListener("change", () => {
  for (const file of fileInput.files) {
    output.innerText += `\n${file.name}`;
  }
});

```
 #### Result




Specifications
--------------




| Specification |
| --- |
| [File API # filelist-section](https://w3c.github.io/FileAPI/#filelist-section) |
| [HTML Standard # dom-input-files-dev](https://html.spec.whatwg.org/multipage/input.html#dom-input-files-dev) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FileList` | 2 | 12 | 3 | 10 | 11.1 | 4 | ≤37 | 18 | 4 | 11.1 | 3.2 | 1.0 |
| `item` | 2 | 12 | 3 | 10 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `length` | 2 | 12 | 3 | 10 | 11.1 | 4 | ≤37 | 18 | 4 | 11.1 | 3.2 | 1.0 |


See also
--------


* [Using files from web applications](file_api/using_files_from_web_applications)
* [`File`](file)
* [`FileReader`](filereader)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FileList>

FileReader
==========



The `FileReader` object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using [`File`](file) or [`Blob`](blob) objects to specify the file or data to read.

 File objects may be obtained from a [`FileList`](filelist) object returned as a result of a user selecting files using the [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) element, or from a drag and drop operation's [`DataTransfer`](datatransfer) object.

 `FileReader` can only access the contents of files that the user has explicitly selected, either using an HTML `<input type="file">` element or by drag and drop. It cannot be used to read a file by pathname from the user's file system. To read files on the client's file system by pathname, use the [File System Access API](file_system_access_api). To read server-side files, use standard Ajax solutions, with CORS permission if reading cross-domain.


 **Note:** This feature is available in [Web Workers](web_workers_api)

   EventTarget FileReader

Constructor
-----------



 [`FileReader()`](filereader/filereader)  Returns a new `FileReader` object.

   See [Using files from web applications](file_api/using_files_from_web_applications) for details and examples.



Instance properties
-------------------


 
[`FileReader.error`](filereader/error) Read only 
  A [`DOMException`](domexception) representing the error that occurred while reading the file.

  
[`FileReader.readyState`](filereader/readystate) Read only 
  A number indicating the state of the `FileReader`. This is one of the following:

 

| Name | Value | Description |
| --- | --- | --- |
| `EMPTY` | `0` | No data has been loaded yet. |
| `LOADING` | `1` | Data is currently being loaded. |
| `DONE` | `2` | The entire read request has been completed. |

  
[`FileReader.result`](filereader/result) Read only 
  The file's contents. This property is only valid after the read operation is complete, and the format of the data depends on which of the methods was used to initiate the read operation.

  
Instance methods
----------------


 [`FileReader.abort()`](filereader/abort)  Aborts the read operation. Upon return, the `readyState` will be `DONE`.

  [`FileReader.readAsArrayBuffer()`](filereader/readasarraybuffer)  Starts reading the contents of the specified [`Blob`](blob), once finished, the `result` attribute contains an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) representing the file's data.

  [`FileReader.readAsBinaryString()`](filereader/readasbinarystring)  Starts reading the contents of the specified [`Blob`](blob), once finished, the `result` attribute contains the raw binary data from the file as a string.

  [`FileReader.readAsDataURL()`](filereader/readasdataurl)  Starts reading the contents of the specified [`Blob`](blob), once finished, the `result` attribute contains a `data:` URL representing the file's data.

  [`FileReader.readAsText()`](filereader/readastext)  Starts reading the contents of the specified [`Blob`](blob), once finished, the `result` attribute contains the contents of the file as a text string. An optional encoding name can be specified.

  
Events
------



Listen to these events using [`addEventListener()`](eventtarget/addeventlistener) or by assigning an event listener to the `oneventname` property of this interface. Remove the event listeners with [`removeEventListener()`](eventtarget/removeeventlistener), once `FileReader` is no longer used, to avoid memory leaks.

  [`abort`](filereader/abort_event)  Fired when a read has been aborted, for example because the program called [`FileReader.abort()`](filereader/abort).

  [`error`](filereader/error_event)  Fired when the read failed due to an error.

  [`load`](filereader/load_event)  Fired when a read has completed successfully.

  [`loadend`](filereader/loadend_event)  Fired when a read has completed, successfully or not.

  [`loadstart`](filereader/loadstart_event)  Fired when a read has started.

  [`progress`](filereader/progress_event)  Fired periodically as data is read.

  

Specifications
--------------




| Specification |
| --- |
| [File API # APIASynch](https://w3c.github.io/FileAPI/#APIASynch) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FileReader` | 6 | 12 | 3.6 | 10 | ≤12.1 | 6 | 3 | 18 | 32 | ≤12.1 | 6 | 1.0 |
| `FileReader` | 6 | 12 | 3.6Before Firefox 4, `Blob` parameters were `File` parameters. | 10 | 11 | 6 | 3 | 18 | 32 | 11 | 6 | 1.0 |
| `abort` | 6 | 12 | 3.6 | 10 | 11 | 6 | 3 | 18 | 32 | 11 | 6 | 1.0 |
| `abort_event` | 6 | 12 | 3.6 | 10 | 11 | 6 | 3 | 18 | 32 | 11 | 6 | 1.0 |
| `error` | 6 | 12 | 3.6["Before Firefox 13, the `error` property returned a `FileError` object.", "From Firefox 13 to Firefox 58, the `error` property returned a `DOMError` object.", "From Firefox 58, the `error` property returns a `DOMException` object."] | 10The `error` property returns a `DOMError` object. | 11 | 6The `error` property returns a `DOMError` object. | 3 | 18 | 32["From Firefox 32 to Firefox 58, the `error` property returned a `DOMError` object.", "From Firefox 58, the `error` property returns a `DOMException` object."] | 11 | 6The `error` property returns a `DOMError` object. | 1.0 |
| `error_event` | 6 | 12 | 3.6 | 10 | 11 | 6 | 3 | 18 | 32 | 11 | 6 | 1.0 |
| `load_event` | 6 | 12 | 3.6 | 10 | 11 | 6 | 3 | 18 | 32 | 11 | 6 | 1.0 |
| `loadend_event` | 6 | 12 | 3.6 | 10 | 11 | 6 | 3 | 18 | 32 | 11 | 6 | 1.0 |
| `loadstart_event` | 6 | 12 | 793.6–79`loadstart` event dispatches synchronously (should be asynchronously as per spec). | 10 | 11 | 6 | 3 | 18 | 7932–79`loadstart` event dispatches synchronously (should be asynchronously as per spec). | 11 | 6 | 1.0 |
| `progress_event` | 6 | 12 | 3.6 | 10 | 11 | 6 | 3 | 18 | 32 | 11 | 6 | 1.0 |
| `readAsArrayBuffer` | 6 | 12 | 3.6 | 10 | 12 | 6 | 3 | 18 | 32 | 12 | 6 | 1.0 |
| `readAsBinaryString` | 6 | 12 | 3.6 | No | 11 | 6 | 3 | 18 | 32 | 11 | 6 | 1.0 |
| `readAsDataURL` | 6 | 12 | 3.6 | 10 | 11 | 6 | 3 | 18 | 32Using the camera in Android 8.x raises an exception. See [bug 1511083](https://bugzil.la/1511083). | 11 | 6 | 1.0 |
| `readAsText` | 6 | 12 | 3.6 | 10 | 11 | 6 | 3 | 18 | 32 | 11 | 6 | 1.0 |
| `readyState` | 6 | 12 | 3.6 | 10 | 11 | 6 | 3 | 18 | 32 | 11 | 6 | 1.0 |
| `result` | 6 | 12 | 3.6 | 10 | 11 | 6 | 3 | 18 | 32 | 11 | 6 | 1.0 |
| `worker_support` | 6 | 12 | 46 | 11 | 11 | 6 | ≤37 | 18 | 46 | 11 | 6 | 1.0 |


See also
--------


* [Using files from web applications](file_api/using_files_from_web_applications)
* [`File`](file)
* [`Blob`](blob)
* [`FileReaderSync`](filereadersync)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FileReader>

FileReaderSync
==============



The `FileReaderSync` interface allows to read [`File`](file) or [`Blob`](blob) objects synchronously.


 **Note:** This feature is available in [Web Workers](web_workers_api)

   **Warning:** This interface is **only available** in [workers](worker) as it enables synchronous I/O that could potentially block.

 

Constructor
-----------


 [`FileReaderSync()`](filereadersync/filereadersync)  Returns a new `FileReaderSync` object.

  
Instance properties
-------------------


This interface does not have any properties.


Instance methods
----------------


 [`FileReaderSync.readAsArrayBuffer()`](filereadersync/readasarraybuffer)  This method converts a specified [`Blob`](blob) or a [`File`](file) into an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) representing the input data as a binary string.

  
[`FileReaderSync.readAsBinaryString()`](filereadersync/readasbinarystring)  Deprecated 
  This method converts a specified [`Blob`](blob) or a [`File`](file) into a string representing the input data as a binary string. This method is deprecated, consider using `readAsArrayBuffer()` instead.

  [`FileReaderSync.readAsText()`](filereadersync/readastext)  This method converts a specified [`Blob`](blob) or a [`File`](file) into a string representing the input data as a text string. The optional `encoding` parameter indicates the encoding to be used (e.g., iso-8859-1 or UTF-8). If not present, the method will apply a detection algorithm for it.

  [`FileReaderSync.readAsDataURL()`](filereadersync/readasdataurl)  This method converts a specified [`Blob`](blob) or a [`File`](file) into a string representing the input data as a data URL.

  
Specifications
--------------




| Specification |
| --- |
| [File API # FileReaderSync](https://w3c.github.io/FileAPI/#FileReaderSync) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FileReaderSync` | 7 | 12 | 8 | 10 | ≤12.1 | 6 | 4.4 | 18 | 8 | ≤12.1 | 6 | 1.0 |
| `FileReaderSync` | 7 | 12 | 8 | 10 | ≤12.1 | 6 | 4.4 | 18 | 8 | ≤12.1 | 6 | 1.0 |
| `readAsArrayBuffer` | 9 | 12 | 8 | 10 | ≤12.1 | 6 | 4.4 | 18 | 8 | ≤12.1 | 6 | 1.0 |
| `readAsBinaryString` | 7 | 12 | 8 | 11 | 15 | 6 | 4.4 | 18 | 8 | 14 | 6 | 1.0 |
| `readAsDataURL` | 7 | 12 | 8 | 10 | ≤12.1 | 6 | 4.4 | 18 | 8 | ≤12.1 | 6 | 1.0 |
| `readAsText` | 7 | 12 | 8 | 10 | ≤12.1 | 6 | 4.4 | 18 | 8 | ≤12.1 | 6 | 1.0 |
| `worker_support` | 7 | 12 | 8 | 10 | ≤15 | 6 | 4.4 | 18 | 8 | ≤14 | 6 | 1.0 |


See also
--------


* [`FileReader`](filereader)
* [`Blob`](blob)
* [`File`](file)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FileReaderSync>

FileSystem
==========



The File and Directory Entries API interface `FileSystem` is used to represent a file system. These objects can be obtained from the [`filesystem`](filesystementry/filesystem) property on any file system entry. Some browsers offer additional APIs to create and manage file systems, such as Chrome's [`requestFileSystem()`](window/requestfilesystem) method.

 This interface will not grant you access to the users' filesystem. Instead, you will have a "virtual drive" within the browser sandbox if you want to gain access to the users' file system, you need to invoke the user, for example by installing a Chrome extension. The relevant Chrome API can be found [here](https://developer.chrome.com/docs/extensions/reference/fileSystem/).



Basic concepts
--------------



There are two ways to get access to a `FileSystem` object:

 1. You can directly ask for one representing a sandboxed file system created just for your web app directly by calling `window.requestFileSystem()`. If that call is successful, it executes a callback handler, which receives as a parameter a `FileSystem` object describing the file system.
2. You can get it from a file system entry object, through its [`filesystem`](filesystementry/filesystem) property.



Instance properties
-------------------


 
[`FileSystem.name`](filesystem/name) Read only 
  A string representing the file system's name. This name is unique among the entire list of exposed file systems.

  
[`FileSystem.root`](filesystem/root) Read only 
  A [`FileSystemDirectoryEntry`](filesystemdirectoryentry) object which represents the file system's root directory. Through this object, you can gain access to all files and directories in the file system.

  
Specifications
--------------




| Specification |
| --- |
| [File and Directory Entries API # api-domfilesystem](https://wicg.github.io/entries-api/#api-domfilesystem) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FileSystem` | 7 | ≤18Edge only supports this API in drag-and-drop scenarios using the `[DataTransferItem.webkitGetAsEntry()](https://developer.mozilla.org/docs/Web/API/DataTransferItem/webkitGetAsEntry)` method. It's not available for use in file or folder picker panels (such as when you use an `[<input>](https://developer.mozilla.org/docs/Web/HTML/Element/input)` element with the `[HTMLInputElement.webkitdirectory](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/webkitdirectory)` attribute. | 50 | No | 15 | 11.1 | ≤37 | 18 | 50 | 14 | 11.3 | 1.0 |
| `name` | 7 | ≤18 | 50 | No | 15 | 11.1 | ≤37 | 18 | 50 | 14 | 11.3 | 1.0 |
| `root` | 7 | ≤18 | 50 | No | 15 | 11.1 | ≤37 | 18 | 50 | 14 | 11.3 | 1.0 |


See also
--------


* [File and Directory Entries API](file_and_directory_entries_api)
* [Introduction to the File and Directory Entries API](file_and_directory_entries_api/introduction)
* [`FileSystemEntry`](filesystementry), [`FileSystemFileEntry`](filesystemfileentry), and [`FileSystemDirectoryEntry`](filesystemdirectoryentry)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FileSystem>

FileSystemFileHandle
====================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `FileSystemFileHandle` interface of the [File System Access API](file_system_access_api) represents a handle to a file system entry. The interface is accessed through the [`window.showOpenFilePicker()`](window/showopenfilepicker) method.

 Note that read and write operations depend on file-access permissions that do not persist after a page refresh if no other tabs for that origin remain open. The [`queryPermission`](filesystemhandle/querypermission) method of the [`FileSystemHandle`](filesystemhandle) interface can be used to verify permission state before accessing a file.


 FileSystemHandle FileSystemFileHandle

Instance properties
-------------------


*Inherits properties from its parent, [`FileSystemHandle`](filesystemhandle).*


Instance methods
----------------



*Inherits methods from its parent, [`FileSystemHandle`](filesystemhandle).*

  [`getFile()`](filesystemfilehandle/getfile)   Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which resolves to a [`File`](file) object representing the state on disk of the entry represented by the handle. 

  [`createSyncAccessHandle()`](filesystemfilehandle/createsyncaccesshandle)   Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which resolves to a [`FileSystemSyncAccessHandle`](filesystemsyncaccesshandle) object that can be used to synchronously read from and write to a file. The synchronous nature of this method brings performance advantages, but it is only usable inside dedicated [Web Workers](web_workers_api). 

  [`createWritable()`](filesystemfilehandle/createwritable)   Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which resolves to a newly created [`FileSystemWritableFileStream`](filesystemwritablefilestream) object that can be used to write to a file. 

  

Examples
--------


### Reading a File



The following asynchronous function presents a file picker and once a file is chosen, uses the `getFile()` method to retrieve the contents.

 
```
async function getTheFile() {
  const pickerOpts = {
    types: [
      {
        description: "Images",
        accept: {
          "image/\*": [".png", ".gif", ".jpeg", ".jpg"],
        },
      },
    ],
    excludeAcceptAllOption: true,
    multiple: false,
  };

  // open file picker
  const [fileHandle] = await window.showOpenFilePicker(pickerOpts);
  // get file contents
  const fileData = await fileHandle.getFile();
  return fileData;
}

```


### Writing a File



The following asynchronous function writes the given contents to the file handle, and thus to disk.

 
```
async function writeFile(fileHandle, contents) {
  // Create a FileSystemWritableFileStream to write to.
  const writable = await fileHandle.createWritable();

  // Write the contents of the file to the stream.
  await writable.write(contents);

  // Close the file and write the contents to disk.
  await writable.close();
}

```


### Synchronously reading and writing a file



The following asynchronous event handler function is contained inside a Web Worker. On receiving a message from the main thread it:

 * Creates a synchronous file access handle.
* Gets the size of the file and creates an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) to contain it.
* Reads the file contents into the buffer.
* Encodes the message and writes it to the end of the file.
* Persists the changes to disk and closes the access handle.

 
```
onmessage = async (e) => {
  // Retrieve message sent to work from main script
  const message = e.data;

  // Get handle to draft file
  const root = await navigator.storage.getDirectory();
  const draftHandle = await root.getFileHandle("draft.txt", { create: true });
  // Get sync access handle
  const accessHandle = await draftHandle.createSyncAccessHandle();

  // Get size of the file.
  const fileSize = accessHandle.getSize();
  // Read file content to a buffer.
  const buffer = new DataView(new ArrayBuffer(fileSize));
  const readBuffer = accessHandle.read(buffer, { at: 0 });

  // Write the message to the end of the file.
  const encoder = new TextEncoder();
  const encodedMessage = encoder.encode(message);
  const writeBuffer = accessHandle.write(encodedMessage, { at: readBuffer });

  // Persist changes to disk.
  accessHandle.flush();

  // Always close FileSystemSyncAccessHandle if done.
  accessHandle.close();
};

```
  **Note:** In earlier versions of the spec, [`close()`](filesystemsyncaccesshandle/close), [`flush()`](filesystemsyncaccesshandle/flush), [`getSize()`](filesystemsyncaccesshandle/getsize), and [`truncate()`](filesystemsyncaccesshandle/truncate) were wrongly specified as asynchronous methods. This has now been [amended](https://github.com/whatwg/fs/issues/7), but some browsers still support the asynchronous versions.

 

Specifications
--------------




| Specification |
| --- |
| [File System Standard # api-filesystemfilehandle](https://fs.spec.whatwg.org/#api-filesystemfilehandle) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FileSystemFileHandle` | 86 | 86 | 111 | No | 72 | 15.2 | 86 | 86 | 111 | 61 | 15.2 | 14.0 |
| `createSyncAccessHandle` | 102 | 102 | 111 | No | 88 | 15.2 | 109 | 109 | 111 | 74 | 15.2 | No |
| `createWritable` | 86 | 86 | 111 | No | 72 | No | No | 86 | 111 | 61 | No | 14.0 |
| `getFile` | 86 | 86 | 111 | No | 72 | 15.2 | No | 86 | 111 | 61 | 15.2 | 14.0 |


See also
--------


* [File System Access API](file_system_access_api)
* [The File System Access API: simplifying access to local files](https://web.dev/file-system-access/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileHandle>

FileSystemHandle
================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `FileSystemHandle` interface of the [`File System Access API`](file_system_access_api) is an object which represents a file or directory entry. Multiple handles can represent the same entry. For the most part you do not work with `FileSystemHandle` directly but rather its child interfaces [`FileSystemFileHandle`](filesystemfilehandle) and [`FileSystemDirectoryHandle`](filesystemdirectoryhandle).



Interfaces based on FileSystemHandle
------------------------------------



Below is a list of interfaces based on the FileSystemHandle interface.

  [`FileSystemFileHandle`](filesystemfilehandle)  Represents a handle to a file entry.

  [`FileSystemDirectoryHandle`](filesystemdirectoryhandle)  Provides a handle to a directory entry.

  

Instance properties
-------------------


 
[`kind`](filesystemhandle/kind) Read only 
  Returns the type of entry. This is `'file'` if the associated entry is a file or `'directory'`.

  
[`name`](filesystemhandle/name) Read only 
  Returns the name of the associated entry.

  
Instance methods
----------------


 [`isSameEntry()`](filesystemhandle/issameentry)  Compares two [`handles`](filesystemhandle) to see if the associated entries (either a file or directory) match.

  
[`queryPermission()`](filesystemhandle/querypermission)  Experimental 
  Queries the current permission state of the current handle.

  
[`remove()`](filesystemhandle/remove)  Experimental   Non-standard 
  Requests removal of the entry represented by the handle from the underlying file system.

  
[`requestPermission()`](filesystemhandle/requestpermission)  Experimental 
  Requests read or readwrite permissions for the file handle.

  
Examples
--------


### Checking Type



The below code allows the user to choose a file from the file picker and then tests to see whether the handle returned is a file or directory

 
```
// store a reference to our file handle
let fileHandle;

async function getFile() {
  // open file picker
  [fileHandle] = await window.showOpenFilePicker();

  if (fileHandle.kind === "file") {
    // run file code
  } else if (fileHandle.kind === "directory") {
    // run directory code
  }
}

```


### Query/Request Permissions



The following asynchronous function returns true if user has granted read or readwrite permissions to the file handle. Permission is requested if not.

 
```
// fileHandle is a FileSystemFileHandle
// withWrite is a boolean set to true if write

async function verifyPermission(fileHandle, withWrite) {
  const opts = {};
  if (withWrite) {
    opts.mode = "readwrite";
  }

  // Check if we already have permission, if so, return true.
  if ((await fileHandle.queryPermission(opts)) === "granted") {
    return true;
  }

  // Request permission to the file, if the user grants permission, return true.
  if ((await fileHandle.requestPermission(opts)) === "granted") {
    return true;
  }

  // The user did not grant permission, return false.
  return false;
}

```


### Comparing Entries



The following function compares a single entry with an array of entries, and returns a new array with any matching entries removed.

 
```
function removeMatches(fileEntry, entriesArr) {
  const newArr = entriesArr.filter((entry) => !fileEntry.isSameEntry(entry));

  return newArr;
}

```


Specifications
--------------




| Specification |
| --- |
| [File System Standard # api-filesystemhandle](https://fs.spec.whatwg.org/#api-filesystemhandle) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FileSystemHandle` | 86 | 86 | 111 | No | 72 | 15.2 | No | 86 | 111 | 61 | 15.2 | 14.0 |
| `isSameEntry` | 86 | 86 | 111 | No | 72 | 15.2 | No | 86 | 111 | 61 | 15.2 | 14.0 |
| `kind` | 86 | 86 | 111 | No | 72 | 15.2 | No | 86 | 111 | 61 | 15.2 | 14.0 |
| `move` | No | No | 111 | No | No | No | No | No | 111 | No | No | No |
| `name` | 86 | 86 | 111 | No | 72 | 15.2 | No | 86 | 111 | 61 | 15.2 | 14.0 |
| `queryPermission` | 86 | 86 | No | No | 72 | No | No | 86 | No | 61 | No | 14.0 |
| `remove` | 110 | 110 | No | No | 96 | No | No | 110 | No | 74 | No | No |
| `requestPermission` | 86 | 86 | No | No | 72 | No | No | 86 | No | 61 | No | 14.0 |


See also
--------


* [File System Access API](file_system_access_api)
* [The File System Access API: simplifying access to local files](https://web.dev/file-system-access/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FileSystemHandle>

FileSystemWritableFileStream
============================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `FileSystemWritableFileStream` interface of the [`File System Access API`](file_system_access_api) is a [`WritableStream`](writablestream) object with additional convenience methods, which operates on a single file on disk. The interface is accessed through the [`FileSystemFileHandle.createWritable()`](filesystemfilehandle/createwritable) method.


 WritableStream FileSystemWritableFileStream

Instance properties
-------------------


*Inherits properties from its parent, [`WritableStream`](writablestream).*


Instance methods
----------------



*Inherits methods from its parent, [`WritableStream`](writablestream).*

  [`FileSystemWritableFileStream.write`](filesystemwritablefilestream/write)  Writes content into the file the method is called on, at the current file cursor offset.

  [`FileSystemWritableFileStream.seek`](filesystemwritablefilestream/seek)  Updates the current file cursor offset to the position (in bytes) specified.

  [`FileSystemWritableFileStream.truncate`](filesystemwritablefilestream/truncate)  Resizes the file associated with the stream to be the specified size in bytes.

  

Examples
--------



This asynchronous function opens the 'Save File' picker, which returns a [`FileSystemFileHandle`](filesystemfilehandle) once a file is selected. From which a writable stream is then created using the [`FileSystemFileHandle.createWritable()`](filesystemfilehandle/createwritable) method.

 A user defined [`Blob`](blob) is then written to the stream which is subsequently closed.

 
```
async function saveFile() {
  // create a new handle
  const newHandle = await window.showSaveFilePicker();

  // create a FileSystemWritableFileStream to write to
  const writableStream = await newHandle.createWritable();

  // write our file
  await writableStream.write(imgBlob);

  // close the file and write the contents to disk.
  await writableStream.close();
}

```
 The following show different examples of options that can be passed into the `write()` method.

 
```
// just pass in the data (no options)
writableStream.write(data);

// writes the data to the stream from the determined position
writableStream.write({ type: "write", position, data });

// updates the current file cursor offset to the position specified
writableStream.write({ type: "seek", position });

// resizes the file to be size bytes long
writableStream.write({ type: "truncate", size });

```


Specifications
--------------




| Specification |
| --- |
| [File System Standard # api-filesystemwritablefilestream](https://fs.spec.whatwg.org/#api-filesystemwritablefilestream) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FileSystemWritableFileStream` | 86 | 86 | 111 | No | 72 | No | No | No | 111 | No | No | No |
| `seek` | 86 | 86 | 111 | No | 72 | No | No | No | 111 | No | No | No |
| `truncate` | 86 | 86 | 111 | No | 72 | No | No | No | 111 | No | No | No |
| `write` | 86 | 86 | 111 | No | 72 | No | No | No | 111 | No | No | No |


See also
--------


* [File System Access API](file_system_access_api)
* [The File System Access API: simplifying access to local files](https://web.dev/file-system-access/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FileSystemWritableFileStream>

FileSystemDirectoryEntry
========================



The `FileSystemDirectoryEntry` interface of the [File and Directory Entries API](file_and_directory_entries_api) represents a directory in a file system. It provides methods which make it possible to access and manipulate the files in a directory, as well as to access the entries within the directory.


 FileSystemEntry FileSystemDirectoryEntry

Basic concepts
--------------


You can create a new directory by calling [`getDirectory()`](filesystemdirectoryentry/getdirectory). If you want to create subdirectories, create each child directory in sequence. If you try creating a directory using a full path that includes parent directories that do not exist yet, an error is returned. So create the hierarchy by recursively adding a new path after creating the parent directory.


### Example



In the following code snippet, we create a directory called "Documents."

 
```
// Taking care of the browser-specific prefixes.
window.requestFileSystem =
  window.requestFileSystem || window.webkitRequestFileSystem;
window.directoryEntry = window.directoryEntry || window.webkitDirectoryEntry;

// …

function onFs(fs) {
  fs.root.getDirectory(
    "Documents",
    { create: true },
    (directoryEntry) => {
      //directoryEntry.isFile === false
      //directoryEntry.isDirectory === true
      //directoryEntry.name === 'Documents'
      //directoryEntry.fullPath === '/Documents'
    },
    onError
  );
}

// Opening a file system with temporary storage
window.requestFileSystem(TEMPORARY, 1024 \* 1024 /\*1MB\*/, onFs, onError);

```


Instance properties
-------------------


*This interface has no properties of its own, but inherits properties from its parent interface, [`FileSystemEntry`](filesystementry).*


Instance methods
----------------



*This interface inherits methods from its parent interface, [`FileSystemEntry`](filesystementry).*

  [`createReader()`](filesystemdirectoryentry/createreader)  Creates a [`FileSystemDirectoryReader`](filesystemdirectoryreader) object which can be used to read the entries in this directory.

  [`getDirectory()`](filesystemdirectoryentry/getdirectory)  Returns a [`FileSystemDirectoryEntry`](filesystemdirectoryentry) object representing a directory located at a given path, relative to the directory on which the method is called.

  [`getFile()`](filesystemdirectoryentry/getfile)  Returns a [`FileSystemFileEntry`](filesystemfileentry) object representing a file located within the directory's hierarchy, given a path relative to the directory on which the method is called.

  

Specifications
--------------




| Specification |
| --- |
| [File and Directory Entries API # api-directoryentry](https://wicg.github.io/entries-api/#api-directoryentry) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FileSystemDirectoryEntry` | 8 | 79 | 50 | No | 15 | 11.1 | ≤37 | 18 | 50 | 14 | 11.3 | 1.0 |
| `createReader` | 13 | 79 | 50 | No | No | 11.1 | ≤37 | 18 | 50 | 14 | 11.3 | 1.0 |
| `getDirectory` | 8 | 79 | 50In Firefox, the `errorCallback`'s input parameter is a `[DOMException](https://developer.mozilla.org/docs/Web/API/DOMException)` rather than a `[FileError](https://developer.mozilla.org/docs/Web/API/FileError)` object. | No | No | 11.1 | ≤37 | 18 | 50In Firefox, the `errorCallback`'s input parameter is a `[DOMException](https://developer.mozilla.org/docs/Web/API/DOMException)` rather than a `[FileError](https://developer.mozilla.org/docs/Web/API/FileError)` object. | 14 | 11.3 | 1.0 |
| `getFile` | 8 | 79 | 50In Firefox, the `errorCallback`'s input parameter is a `[DOMException](https://developer.mozilla.org/docs/Web/API/DOMException)` rather than a `[FileError](https://developer.mozilla.org/docs/Web/API/FileError)` object. | No | No | 11.1 | ≤37 | 18 | 50In Firefox, the `errorCallback`'s input parameter is a `[DOMException](https://developer.mozilla.org/docs/Web/API/DOMException)` rather than a `[FileError](https://developer.mozilla.org/docs/Web/API/FileError)` object. | 14 | 11.3 | 1.0 |
| `removeRecursively` | 8 | 79 | 50–52While the `removeRecursively()` method existed, it immediately called the error callback with `NS_ERROR_DOM_SECURITY_ERR`. | No | No | No | ≤37 | 18 | 50–52While the `removeRecursively()` method existed, it immediately called the error callback with `NS_ERROR_DOM_SECURITY_ERR`. | 14 | No | 1.0 |


See also
--------


* [File and Directory Entries API](file_and_directory_entries_api)
* [Introduction to the File and Directory Entries API](file_and_directory_entries_api/introduction)
* [`FileSystemDirectoryReader`](filesystemdirectoryreader)
* [`FileSystemEntry`](filesystementry)
* [`FileSystemFileEntry`](filesystemfileentry)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryEntry>

FileSystemDirectoryHandle
=========================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `FileSystemDirectoryHandle` interface of the [`File System Access API`](file_system_access_api) provides a handle to a file system directory.

 The interface can be accessed via the [`window.showDirectoryPicker()`](window/showdirectorypicker), [`StorageManager.getDirectory()`](storagemanager/getdirectory), [`DataTransferItem.getAsFileSystemHandle()`](datatransferitem/getasfilesystemhandle), and [`FileSystemDirectoryHandle.getDirectoryHandle()`](filesystemdirectoryhandle/getdirectoryhandle) methods.


 FileSystemHandle FileSystemDirectoryHandle

Instance properties
-------------------


*Inherits properties from its parent, [`FileSystemHandle`](filesystemhandle).*


Instance methods
----------------



*Inherits methods from its parent, [`FileSystemHandle`](filesystemhandle).*

  [`FileSystemDirectoryHandle.entries()`](filesystemdirectoryhandle/entries)  Returns a new *async iterator* of a given object's own enumerable property `[key, value]` pairs

  [`FileSystemDirectoryHandle.getFileHandle()`](filesystemdirectoryhandle/getfilehandle)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) fulfilled with a [`FileSystemFileHandle`](filesystemfilehandle) for a file with the specified name, within the directory the method is called.

  [`FileSystemDirectoryHandle.getDirectoryHandle()`](filesystemdirectoryhandle/getdirectoryhandle)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) fulfilled with a [`FileSystemDirectoryHandle`](filesystemdirectoryhandle) for a subdirectory with the specified name within the directory handle on which the method is called.

  [`FileSystemDirectoryHandle.keys()`](filesystemdirectoryhandle/keys)  Returns a new *async iterator* containing the keys for each item in `FileSystemDirectoryHandle`.

  [`FileSystemDirectoryHandle.removeEntry()`](filesystemdirectoryhandle/removeentry)  Attempts to asynchronously remove an entry if the directory handle contains a file or directory called the name specified.

  [`FileSystemDirectoryHandle.resolve()`](filesystemdirectoryhandle/resolve)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) fulfilled with an [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of directory names from the parent handle to the specified child entry, with the name of the child entry as the last array item.

  [`FileSystemDirectoryHandle.values()`](filesystemdirectoryhandle/values)  Returns a new *async iterator* containing the values for each index in the `FileSystemDirectoryHandle` object.

  [`FileSystemDirectoryHandle[@@asyncIterator]()`](filesystemdirectoryhandle/entries)  Returns the `entries` function by default.

  

Examples
--------



The following example returns a directory handle with the specified name, if the directory does not exist it is created.

 
```
const dirName = "directoryToGetName";

// assuming we have a directory handle: 'currentDirHandle'
const subDir = currentDirHandle.getDirectoryHandle(dirName, { create: true });

```
 The following asynchronous function uses `resolve()` to find the path to a chosen file, relative to a specified directory handle.

 
```
async function returnPathDirectories(directoryHandle) {
  // Get a file handle by showing a file picker:
  const handle = await self.showOpenFilePicker();
  if (!handle) {
    // User cancelled, or otherwise failed to open a file.
    return;
  }

  // Check if handle exists inside directory our directory handle
  const relativePaths = await directoryHandle.resolve(handle);

  if (relativePath === null) {
    // Not inside directory handle
  } else {
    // relativePath is an array of names, giving the relative path

    for (const name of relativePaths) {
      // log each entry
      console.log(name);
    }
  }
}

```
 The following example scans recursively through a directory to return [`FileSystemFileHandle`](filesystemfilehandle) objects for each file in that directory:

 
```
async function\* getFilesRecursively(entry) {
  if (entry.kind === "file") {
    const file = await entry.getFile();
    if (file !== null) {
      file.relativePath = getRelativePath(entry);
      yield file;
    }
  } else if (entry.kind === "directory") {
    for await (const handle of entry.values()) {
      yield\* getFilesRecursively(handle);
    }
  }
}
for await (const fileHandle of getFilesRecursively(directoryHandle)) {
  console.log(fileHandle);
}

```


Specifications
--------------




| Specification |
| --- |
| [File System Standard # api-filesystemdirectoryhandle](https://fs.spec.whatwg.org/#api-filesystemdirectoryhandle) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@asyncIterator` | 86 | 86 | 111 | No | 72 | 16.4 | No | 86 | 111 | 61 | 16.4 | 14.0 |
| `FileSystemDirectoryHandle` | 86 | 86 | 111 | No | 72 | 15.2 | No | 86 | 111 | 61 | 15.2 | 14.0 |
| `entries` | 86 | 86 | 111 | No | 72 | 15.2 | No | 86 | 111 | 61 | 15.2 | 14.0 |
| `getDirectoryHandle` | 86 | 86 | 111 | No | 72 | 15.2 | No | 86 | 111 | 61 | 15.2 | 14.0 |
| `getFileHandle` | 86 | 86 | 111 | No | 72 | 15.2 | No | 86 | 111 | 61 | 15.2 | 14.0 |
| `keys` | 86 | 86 | 111 | No | 72 | 15.2 | No | 86 | 111 | 61 | 15.2 | 14.0 |
| `removeEntry` | 86 | 86 | 111 | No | 72 | 15.2 | No | 86 | 111 | 61 | 15.2 | 14.0 |
| `resolve` | 86 | 86 | 111 | No | 72 | 15.2 | No | 86 | 111 | 61 | 15.2 | 14.0 |
| `values` | 86 | 86 | 111 | No | 72 | 15.2 | No | 86 | 111 | 61 | 15.2 | 14.0 |


See also
--------


* [File System Access API](file_system_access_api)
* [The File System Access API: simplifying access to local files](https://web.dev/file-system-access/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryHandle>

FileSystemDirectoryReader
=========================


The `FileSystemDirectoryReader` interface of the [File and Directory Entries API](file_and_directory_entries_api) lets you access the [`FileSystemFileEntry`](filesystemfileentry)-based objects (generally [`FileSystemFileEntry`](filesystemfileentry) or [`FileSystemDirectoryEntry`](filesystemdirectoryentry)) representing each entry in a directory.


Instance methods
----------------


 [`readEntries()`](filesystemdirectoryreader/readentries)  Returns an array containing some number of the directory's entries. Each item in the array is an object based on [`FileSystemEntry`](filesystementry)—typically either [`FileSystemFileEntry`](filesystemfileentry) or [`FileSystemDirectoryEntry`](filesystemdirectoryentry).

  
Specifications
--------------




| Specification |
| --- |
| [File and Directory Entries API # api-directoryreader](https://wicg.github.io/entries-api/#api-directoryreader) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FileSystemDirectoryReader` | 8 | ≤18 | 50 | No | 15 | 11.1 | ≤37 | 18 | 50 | 14 | 11.3 | 1.0 |
| `readEntries` | 8 | 79 | 50 | No | 15 | 11.1 | ≤37 | 18 | 50 | 14 | 11.3 | 1.0 |


See also
--------


* [File and Directory Entries API](file_and_directory_entries_api)
* [Introduction to the File and Directory Entries API](file_and_directory_entries_api/introduction)
* [`FileSystemDirectoryEntry`](filesystemdirectoryentry)
* [`FileSystem`](filesystem)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryReader>

FileSystemEntry
===============


The `FileSystemEntry` interface of the File and Directory Entries API represents a single entry in a file system. The entry can be a file or a directory (directories are represented by the [`FileSystemDirectoryEntry`](filesystemdirectoryentry) interface). It includes methods for working with files—including copying, moving, removing, and reading files—as well as information about a file it points to—including the file name and its path from the root to the entry.


Basic concepts
--------------



You don't create `FileSystemEntry` objects directly. Instead, you will receive an object based on this interface through other APIs. This interface serves as a base class for the [`FileSystemFileEntry`](filesystemfileentry) and [`FileSystemDirectoryEntry`](filesystemdirectoryentry) interfaces, which provide features specific to file system entries representing files and directories, respectively.

 The `FileSystemEntry` interface includes methods that you would expect for manipulating files and directories, but it also includes a convenient method for obtaining the URL of the entry: [`toURL()`](#tourl). It also introduces a new URL scheme: `filesystem:`.

 You can use the `filesystem:` scheme on Google Chrome to see all the files and folders that are stored in the origin of your app. Just use `filesystem:` scheme for the root directory of the origin of the app. For example, if your app is in [`http://www.example.com`](https://www.example.com), open `filesystem:http://www.example.com/temporary/` in a tab. Chrome shows a read-only list of all the files and folders stored the origin of your app.



### Example



To see an example of how `toURL()` works, see the [method description](#tourl). The snippet below shows you how you can remove a file by name.

 
```
// Taking care of the browser-specific prefixes.
window.requestFileSystem =
  window.requestFileSystem || window.webkitRequestFileSystem;

// …

// Opening a file system with temporary storage
window.requestFileSystem(
  TEMPORARY,
  1024 \* 1024 /\*1MB\*/,
  (fs) => {
    fs.root.getFile(
      "log.txt",
      {},
      (fileEntry) => {
        fileEntry.remove(() => {
          console.log("File removed.");
        }, onError);
      },
      onError
    );
  },
  onError
);

```


Instance properties
-------------------



*This interface provides the following properties.*

  
[`filesystem`](filesystementry/filesystem) Read only 
  A [`FileSystem`](filesystem) object representing the file system in which the entry is located.

  
[`fullPath`](filesystementry/fullpath) Read only 
  A string object which provides the full, absolute path from the file system's root to the entry; it can also be thought of as a path which is relative to the root directory, prepended with a "/" character.

  
[`isDirectory`](filesystementry/isdirectory) Read only 
  A boolean value which is `true` if the entry represents a directory; otherwise, it's `false`.

  
[`isFile`](filesystementry/isfile) Read only 
  A Boolean which is `true` if the entry represents a file. If it's not a file, this value is `false`.

  
[`name`](filesystementry/name) Read only 
  A string containing the name of the entry (the final part of the path, after the last "/" character).

  

Instance methods
----------------



*This interface defines the following methods.*

  
[`copyTo()`](filesystementry/copyto)  Deprecated   Non-standard 
  Copies the file or directory to a new location on the file system.

  
[`getMetadata()`](filesystementry/getmetadata)  Deprecated   Non-standard 
  Obtains metadata about the file, such as its modification date and size.

  [`getParent()`](filesystementry/getparent)  Returns a [`FileSystemDirectoryEntry`](filesystemdirectoryentry) representing the entry's parent directory.

  
[`moveTo()`](filesystementry/moveto)  Deprecated   Non-standard 
  Moves the file or directory to a new location on the file system, or renames the file or directory.

  
[`remove()`](filesystementry/remove)  Deprecated   Non-standard 
  Removes the specified file or directory. You can only remove directories which are empty.

  
[`toURL()`](filesystementry/tourl)  Deprecated   Non-standard 
  Creates and returns a URL which identifies the entry. This URL uses the URL scheme `"filesystem:"`.

  

Specifications
--------------




| Specification |
| --- |
| [File and Directory Entries API # api-entry](https://wicg.github.io/entries-api/#api-entry) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FileSystemEntry` | 8 | 79 | 50 | No | No | 11.1 | ≤37 | 18 | 50 | 14 | 11.3 | 1.0 |
| `copyTo` | 8 | 79 | No | No | No | No | ≤37 | 18 | No | 14 | No | 1.0 |
| `filesystem` | 8 | 79 | 50 | No | No | 11.1 | ≤37 | 18 | 50 | 14 | 11.3 | 1.0 |
| `fullPath` | 8 | 79 | 50 | No | No | 11.1 | ≤37 | 18 | 50 | 14 | 11.3 | 1.0 |
| `getMetadata` | 8 | 79 | No | No | No | No | ≤37 | 18 | No | 14 | No | 1.0 |
| `getParent` | 8 | 79 | 52 | No | No | 11.1 | ≤37 | 18 | 52 | 14 | 11.3 | 1.0 |
| `isDirectory` | 8 | 79 | 50 | No | No | 11.1 | ≤37 | 18 | 50 | 14 | 11.3 | 1.0 |
| `isFile` | 8 | 79 | 50 | No | No | 11.1 | ≤37 | 18 | 50 | 14 | 11.3 | 1.0 |
| `moveTo` | 8 | 79 | No | No | No | No | ≤37 | 18 | No | 14 | No | 1.0 |
| `name` | 8 | 79 | 50 | No | No | 11.1 | ≤37 | 18 | 50 | 14 | 11.3 | 1.0 |
| `remove` | 8 | 79 | No | No | No | No | ≤37 | 18 | No | 14 | No | 1.0 |
| `toURL` | 8 | 79 | No | No | No | No | ≤37 | 18 | No | 14 | No | 1.0 |


See also
--------


* [File and Directory Entries API](file_and_directory_entries_api)
* [Introduction to the File and Directory Entries API](file_and_directory_entries_api/introduction)
* [`FileSystemFileEntry`](filesystemfileentry) and [`FileSystemDirectoryEntry`](filesystemdirectoryentry) are based on `FileSystemEntry`.


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FileSystemEntry>

FileSystemFileEntry
===================



The `FileSystemFileEntry` interface of the [File and Directory Entries API](file_and_directory_entries_api/introduction) represents a file in a file system. It offers properties describing the file's attributes, as well as the [`file()`](filesystemfileentry/file) method, which creates a [`File`](file) object that can be used to read the file.


 FileSystemEntry FileSystemFileEntry

Instance properties
-------------------


*Inherits the properties of its parent interface, [`FileSystemEntry`](filesystementry), but has no properties unique to this interface.*


Instance methods
----------------


 [`file()`](filesystemfileentry/file)  Creates a new [`File`](file) object which can be used to read the file.

  
Specifications
--------------




| Specification |
| --- |
| [File and Directory Entries API # api-fileentry](https://wicg.github.io/entries-api/#api-fileentry) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FileSystemFileEntry` | 8 | 79 | 50 | No | No | 11.1 | ≤37 | 18 | 50 | 14 | 11.3 | 1.0 |
| `createWriter` | 8 | 79 | 50–52While the `createWriter()` method existed, it immediately called `errorCallback` with the `NS_ERROR_DOM_SECURITY_ERR` error. | No | No | No | ≤37 | 18 | 50–52While the `createWriter()` method existed, it immediately called `errorCallback` with the `NS_ERROR_DOM_SECURITY_ERR` error. | 14 | No | 1.0 |
| `file` | 8 | 79 | 50 | No | No | 11.1 | ≤37 | 18 | 50 | 14 | 11.3 | 1.0 |


See also
--------


* [File and Directory Entries API](file_and_directory_entries_api)
* [Introduction to the File and Directory Entries API](file_and_directory_entries_api/introduction)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileEntry>

FileSystemSync
==============



**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.


**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 In the [File and Directory Entries API](file_and_directory_entries_api/introduction), a `FileSystemSync` object represents a file system. It has two properties.

   **Warning:** This interface is deprecated and is no more on the standard track. *Do not use it anymore.* Use the [File and Directory Entries API](file_and_directory_entries_api) instead. 

 

Basic concepts
--------------


The `FileSystemSync` object is your gateway to the entire API and you will use it a lot. So once you have a reference, cache the object in a global variable or class property.


Instance properties
-------------------


 
`name` Read only   Non-standard   Deprecated 
  A string that represents the name of the file system. The name must be unique across the list of exposed file systems.

  
`root` Read only   Non-standard   Deprecated 
  A `DirectoryEntry` that is the root directory of the file system.

  
Specifications
--------------


This feature is not part of any specification anymore. It is no longer on track to become a standard.


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FileSystemSync` | 13 | 79 | No | No | 15 | 6 | ≤37 | 18 | No | 14 | 6 | 1.0 |
| `name` | 13 | 79 | No | No | 15 | 6 | ≤37 | 18 | No | 14 | 6 | 1.0 |
| `root` | 13 | 79 | No | No | 15 | 6 | ≤37 | 18 | No | 14 | 6 | 1.0 |


See also
--------


* [File and Directory Entries API](file_and_directory_entries_api)
* [Introduction to the File and Directory Entries API](file_and_directory_entries_api/introduction)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FileSystemSync>

FileSystemSyncAccessHandle
==========================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `FileSystemSyncAccessHandle` interface of the [File System Access API](file_system_access_api) represents a synchronous handle to a file system entry. The synchronous nature of the file reads and writes allows for higher performance for critical methods in contexts where asynchronous operations come with high overhead, e.g., [WebAssembly](https://developer.mozilla.org/en-US/docs/WebAssembly).

 This class is only accessible inside dedicated [Web Workers](web_workers_api) for files within the [origin private file system](file_system_access_api#origin_private_file_system).

 The interface is accessed through the [`FileSystemFileHandle.createSyncAccessHandle()`](filesystemfilehandle/createsyncaccesshandle) method.



Instance properties
-------------------


None.


Instance methods
----------------


 [`close()`](filesystemsyncaccesshandle/close)  Closes an open synchronous file handle, disabling any further operations on it and releasing the exclusive lock previously put on the file associated with the file handle.

  [`flush()`](filesystemsyncaccesshandle/flush)  Persists any changes made to the file associated with the handle via the [`write()`](filesystemsyncaccesshandle/write) method to disk.

  [`getSize()`](filesystemsyncaccesshandle/getsize)  Returns the size of the file associated with the handle in bytes.

  [`read()`](filesystemsyncaccesshandle/read)  Reads the content of the file associated with the handle into a specified buffer, optionally at a given offset.

  [`truncate()`](filesystemsyncaccesshandle/truncate)  Resizes the file associated with the handle to a specified number of bytes.

  [`write()`](filesystemsyncaccesshandle/write)  Writes the content of a specified buffer to the file associated with the handle, optionally at a given offset.

  
Examples
--------



The following asynchronous event handler function is contained inside a Web Worker. On receiving a message from the main thread it:

 * Creates a synchronous file access handle.
* Gets the size of the file and creates an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) to contain it.
* Reads the file contents into the buffer.
* Encodes the message and writes it to the end of the file.
* Persists the changes to disk and closes the access handle.

 
```
onmessage = async (e) => {
  // Retrieve message sent to work from main script
  const message = e.data;

  // Get handle to draft file
  const root = await navigator.storage.getDirectory();
  const draftHandle = await root.getFileHandle("draft.txt", { create: true });
  // Get sync access handle
  const accessHandle = await draftHandle.createSyncAccessHandle();

  // Get size of the file.
  const fileSize = accessHandle.getSize();
  // Read file content to a buffer.
  const buffer = new DataView(new ArrayBuffer(fileSize));
  const readBuffer = accessHandle.read(buffer, { at: 0 });

  // Write the message to the end of the file.
  const encoder = new TextEncoder();
  const encodedMessage = encoder.encode(message);
  const writeBuffer = accessHandle.write(encodedMessage, { at: readBuffer });

  // Persist changes to disk.
  accessHandle.flush();

  // Always close FileSystemSyncAccessHandle if done.
  accessHandle.close();
};

```
  **Note:** In earlier versions of the spec, [`close()`](filesystemsyncaccesshandle/close), [`flush()`](filesystemsyncaccesshandle/flush), [`getSize()`](filesystemsyncaccesshandle/getsize), and [`truncate()`](filesystemsyncaccesshandle/truncate) were wrongly specified as asynchronous methods. This has now been [amended](https://github.com/whatwg/fs/issues/7), but some browsers still support the asynchronous versions.

 

Specifications
--------------




| Specification |
| --- |
| [File System Standard # api-filesystemsyncaccesshandle](https://fs.spec.whatwg.org/#api-filesystemsyncaccesshandle) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FileSystemSyncAccessHandle` | 102 | 102 | 111 | No | 88 | 15.2 | 109 | 109 | 111 | 74 | 15.2 | No |
| `close` | 102 | 102 | 111 | No | 88 | 15.2 | 109 | 109 | 111 | 74 | 15.2 | No |
| `flush` | 102 | 102 | 111 | No | 88 | 15.2 | 109 | 109 | 111 | 74 | 15.2 | No |
| `getSize` | 102 | 102 | 111 | No | 88 | 15.2 | 109 | 109 | 111 | 74 | 15.2 | No |
| `read` | 102 | 102 | 111 | No | 88 | 15.2 | 109 | 109 | 111 | 74 | 15.2 | No |
| `truncate` | 102 | 102 | 111 | No | 88 | 15.2 | 109 | 109 | 111 | 74 | 15.2 | No |
| `write` | 102 | 102 | 111 | No | 88 | 15.2 | 109 | 109 | 111 | 74 | 15.2 | No |


See also
--------


* [File System Access API](file_system_access_api)
* [The File System Access API: simplifying access to local files](https://web.dev/file-system-access/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FileSystemSyncAccessHandle>

FocusEvent
==========



The `FocusEvent` interface represents focus-related events, including [`focus`](element/focus_event), [`blur`](element/blur_event), [`focusin`](element/focusin_event), and [`focusout`](element/focusout_event).


 Event UIEvent FocusEvent

Constructor
-----------


 [`FocusEvent()`](focusevent/focusevent)  Creates a `FocusEvent` event with the given parameters.

  
Instance properties
-------------------



*This interface also inherits properties from its parent [`UIEvent`](uievent), and indirectly from [`Event`](event)*.

  [`FocusEvent.relatedTarget`](focusevent/relatedtarget)  An [`EventTarget`](eventtarget) representing a secondary target for this event. In some cases (such as when tabbing in or out a page), this property may be set to `null` for security reasons.

  

Instance methods
----------------


*This interface has no specific methods. It inherits methods from its parent [`UIEvent`](uievent), and indirectly from [`Event`](event).*


Order of events
---------------



The *UI Events* specification states that focus events [occur in a set order](https://w3c.github.io/uievents/#events-focusevent-event-order) relative to one another, and goes on to describe the typical sequence of events that fire when the focus is shifted from element A to element B:

 1. `focusout`: sent before element A loses focus.
2. `focusin`: sent before element B receives focus.
3. `blur`: sent after element A loses focus.
4. `focus`: sent after element B receives focus.

 However, current browser implementations fire these four events in a different order:

 1. `blur`: sent after element A loses focus.
2. `focusout`: sent after the `blur` event.
3. `focus`: sent after element B receives focus.
4. `focusin`: sent after the `focus` event.



Specifications
--------------




| Specification |
| --- |
| [UI Events # interface-focusevent](https://w3c.github.io/uievents/#interface-focusevent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FocusEvent` | 26 | 12 | 24 | No | 15 | 7 | 4.4 | 26 | 24 | 14 | 7 | 1.5 |
| `FocusEvent` | 26 | 12 | 24 | 9 | 15 | 7 | 4.4 | 26 | 24 | 14 | 7 | 1.5 |
| `relatedTarget` | 26 | 12 | 24 | 9 | 15 | 7 | 4.4 | 26 | 24 | 14 | 7 | 1.5 |


See also
--------


* The [`Event`](event) base interface


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FocusEvent>

FontFaceSet
===========



The `FontFaceSet` interface of the [CSS Font Loading API](css_font_loading_api) manages the loading of font-faces and querying of their download status.

 This property is available as [`Document.fonts`](document/fonts), or `self.fonts` in [web workers](web_workers_api).


 EventTarget FontFaceSet

Instance properties
-------------------


 
[`FontFaceSet.status`](fontfaceset/status) Read only 
  Indicates the font-face's loading status. It will be one of `'loading'` or `'loaded'`.

  
[`FontFaceSet.ready`](fontfaceset/ready) Read only 
  [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which resolves once font loading and layout operations have completed.

  
[`FontFaceSet.size`](fontfaceset/size) Read only 
  Returns the number of values in the `FontFaceSet`.

  
### Events


 [`loading`](fontfaceset/loading_event)  Fires when a font-face set has started loading.

  [`loadingdone`](fontfaceset/loadingdone_event)  Fires when a font face set has finished loading.

  [`loadingerror`](fontfaceset/loadingerror_event)  Fires when an error occurred whilst loading a font-face set.

  
Instance methods
----------------


 [`FontFaceSet.add()`](fontfaceset/add)  Adds a font to the font set.

  [`FontFaceSet.check()`](fontfaceset/check)  A boolean value that indicates whether a font is loaded, but doesn't initiate a load when it isn't.

  [`FontFaceSet.clear()`](fontfaceset/clear)  Removes all manually-added fonts from the font set. [CSS-connected](https://www.w3.org/TR/css-font-loading-3/#css-connected) fonts are unaffected.

  [`FontFaceSet.delete()`](fontfaceset/delete)  Removes a manually-added font from the font set. [CSS-connected](https://www.w3.org/TR/css-font-loading-3/#css-connected) fonts are unaffected.

  [`FontFaceSet.entries()`](fontfaceset/entries)  Returns a new iterator with the values for each element in the `FontFaceSet` in insertion order.

  [`FontFaceSet.forEach()`](fontfaceset/foreach)  Executes a provided function for each value in the `FontFaceSet` object.

  [`FontFaceSet.has()`](fontfaceset/has)  Returns a [`Boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean) asserting whether an element is present with the given value.

  [`FontFaceSet.keys()`](fontfaceset/keys)  An alias for [`CustomStateSet.values()`](customstateset/values).

  [`FontFaceSet.load()`](fontfaceset/load)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which resolves to a list of font-faces for a requested font.

  [`FontFaceSet.values()`](fontfaceset/values)  Returns a new iterator object that yields the values for each element in the `FontFaceSet` object in insertion order.

  
Specifications
--------------




| Specification |
| --- |
| [CSS Font Loading Module Level 3 # FontFaceSet-interface](https://w3c.github.io/csswg-drafts/css-font-loading/#FontFaceSet-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@iterator` | 48 | 79 | 41 | No | 35 | 10 | 48 | 48 | 41 | 35 | 10 | 5.0 |
| `FontFaceSet` | No | No | No | No | No | 10 | No | No | No | No | 10 | No |
| `FontFaceSet` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 3.0 |
| `add` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 3.0 |
| `check` | 35The method returns `false` instead of `true` for nonexistent or locally installed fonts. See [bug 591602](https://crbug.com/591602). | 79The method returns `false` instead of `true` for nonexistent or locally installed fonts. See [bug 591602](https://crbug.com/591602). | 41 | No | 22The method returns `false` instead of `true` for nonexistent or locally installed fonts. See [bug 591602](https://crbug.com/591602). | 10 | 37The method returns `false` instead of `true` for nonexistent or locally installed fonts. See [bug 591602](https://crbug.com/591602). | 35The method returns `false` instead of `true` for nonexistent or locally installed fonts. See [bug 591602](https://crbug.com/591602). | 41 | 22The method returns `false` instead of `true` for nonexistent or locally installed fonts. See [bug 591602](https://crbug.com/591602). | 10 | 3.0The method returns `false` instead of `true` for nonexistent or locally installed fonts. See [bug 591602](https://crbug.com/591602). |
| `clear` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 3.0 |
| `delete` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 3.0 |
| `entries` | 48 | 79 | 41 | No | 35 | 10 | 48 | 48 | 41 | 35 | 10 | 5.0 |
| `forEach` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 3.0 |
| `has` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 3.0 |
| `keys` | 48 | 79 | 41 | No | 35 | 10 | 48 | 48 | 41 | 35 | 10 | 5.0 |
| `load` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 3.0 |
| `loading_event` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 3.0 |
| `loadingdone_event` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 3.0 |
| `loadingerror_event` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 3.0 |
| `ready` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 3.0 |
| `size` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 3.0 |
| `status` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 3.0 |
| `values` | 48 | 79 | 41 | No | 35 | 10 | 48 | 48 | 41 | 35 | 10 | 5.0 |
| `worker_support` | 69 | 79 | 105 | No | 56 | No | 69 | 69 | 105 | 48 | No | 10.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FontFaceSet>

FontData
========



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `FontData` interface of the [Local Font Access API](local_font_access_api) represents a single local font face.



Instance properties
-------------------


 
[`FontData.family`](fontdata/family) Read only   Experimental 
  Returns the family of the font face.

  
[`FontData.fullName`](fontdata/fullname) Read only   Experimental 
  Returns the full name of the font face.

  
[`FontData.postscriptName`](fontdata/postscriptname) Read only   Experimental 
  Returns the PostScript name of the font face.

  
[`FontData.style`](fontdata/style) Read only   Experimental 
  Returns the style of the font face.

  
Instance methods
----------------


 
[`FontData.blob()`](fontdata/blob) Read only   Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that fulfills with a [`Blob`](blob) containing the raw bytes of the underlying font file.

  
Examples
--------


For a working live demo, see [Font Select Demo](https://local-font-access.glitch.me/demo/).


### Font enumeration



The following snippet will query for all available fonts, and log metadata. This could be used, for example, to populate a font-picker control.

 
```
async function logFontData() {
  try {
    const availableFonts = await window.queryLocalFonts();
    for (const fontData of availableFonts) {
      console.log(fontData.postscriptName);
      console.log(fontData.fullName);
      console.log(fontData.family);
      console.log(fontData.style);
    }
  } catch (err) {
    console.error(err.name, err.message);
  }
}

```


### Accessing low-level data



The [`blob()`](fontdata/blob) method provides access to low-level [SFNT](https://en.wikipedia.org/wiki/SFNT) data — this is a font file format that can contain other font formats, such as PostScript, TrueType, OpenType, or Web Open Font Format (WOFF).

 
```
async function computeOutlineFormat() {
  try {
    const availableFonts = await window.queryLocalFonts({
      postscriptNames: ["ComicSansMS"],
    });
    for (const fontData of availableFonts) {
      // `blob()` returns a Blob containing valid and complete
      // SFNT-wrapped font data.
      const sfnt = await fontData.blob();
      // Slice out only the bytes we need: the first 4 bytes are the SFNT
      // version info.
      // Spec: https://docs.microsoft.com/en-us/typography/opentype/spec/otff#organization-of-an-opentype-font
      const sfntVersion = await sfnt.slice(0, 4).text();

      let outlineFormat = "UNKNOWN";
      switch (sfntVersion) {
        case "\x00\x01\x00\x00":
        case "true":
        case "typ1":
          outlineFormat = "truetype";
          break;
        case "OTTO":
          outlineFormat = "cff";
          break;
      }
      console.log("Outline format:", outlineFormat);
    }
  } catch (err) {
    console.error(err.name, err.message);
  }
}

```


Specifications
--------------




| Specification |
| --- |
| [Local Font Access # fontdata-interface](https://wicg.github.io/local-font-access/#fontdata-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FontData` | 103 | 103 | No | No | No | No | No | No | No | No | No | No |
| `blob` | 103 | 103 | No | No | No | No | No | No | No | No | No | No |
| `family` | 103 | 103 | No | No | No | No | No | No | No | No | No | No |
| `fullName` | 103 | 103 | No | No | No | No | No | No | No | No | No | No |
| `postscriptName` | 103 | 103 | No | No | No | No | No | No | No | No | No | No |
| `style` | 103 | 103 | No | No | No | No | No | No | No | No | No | No |


* [Use advanced typography with local fonts](https://developer.chrome.com/articles/local-fonts/)
* [`@font-face`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FontData>

FontFace
========



The `FontFace` interface of the [CSS Font Loading API](css_font_loading_api) represents a single usable font face.

  This interface defines the source of a font face, either a URL to an external resource or a buffer, and font properties such as `style`, `weight`, and so on. For URL font sources it allows authors to trigger when the remote font is fetched and loaded, and to track loading status. 



Constructor
-----------


 [`FontFace()`](fontface/fontface)  Constructs and returns a new `FontFace` object, built from an external resource described by a URL or from an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer).

  
Instance properties
-------------------


 [`FontFace.ascentOverride`](fontface/ascentoverride)  A string that retrieves or sets the *ascent metric* of the font. It is equivalent to the [`ascent-override`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/ascent-override) descriptor.

  [`FontFace.descentOverride`](fontface/descentoverride)  A string that retrieves or sets the *descent metric* of the font. It is equivalent to the [`descent-override`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/descent-override) descriptor.

  [`FontFace.display`](fontface/display)  A string that determines how a font face is displayed based on whether and when it is downloaded and ready to use.

  [`FontFace.family`](fontface/family)  A string that retrieves or sets the *family* of the font. It is equivalent to the [`font-family`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-family) descriptor.

  [`FontFace.featureSettings`](fontface/featuresettings)  A string that retrieves or sets infrequently used font features that are not available from a font's variant properties. It is equivalent to the CSS [`font-feature-settings`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-feature-settings) property.

  [`FontFace.lineGapOverride`](fontface/linegapoverride)  A string that retrieves or sets the *line-gap metric* of the font. It is equivalent to the [`line-gap-override`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/line-gap-override) descriptor.

  
[`FontFace.loaded`](fontface/loaded) Read only 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with the current `FontFace` object when the font specified in the object's constructor is done loading or rejects with a `SyntaxError` [`DOMException`](domexception).

  
[`FontFace.status`](fontface/status) Read only 
  Returns an enumerated value indicating the status of the font, one of `"unloaded"`, `"loading"`, `"loaded"`, or `"error"`.

  [`FontFace.stretch`](fontface/stretch)  A string that retrieves or sets how the font *stretches*. It is equivalent to the [`font-stretch`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-stretch) descriptor.

  [`FontFace.style`](fontface/style)  A string that retrieves or sets the *style* of the font. It is equivalent to the [`font-style`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-style) descriptor.

  [`FontFace.unicodeRange`](fontface/unicoderange)  A string that retrieves or sets the *range of unicode codepoints* encompassing the font. It is equivalent to the [`unicode-range`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/unicode-range) descriptor.

  [`FontFace.variant`](fontface/variant)  A string that retrieves or sets the *variant* of the font.

  
[`FontFace.variationSettings`](fontface/variationsettings)  Experimental 
  A string that retrieves or sets the *variation settings* of the font. It is equivalent to the [`font-variation-settings`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-variation-settings) descriptor.

  [`FontFace.weight`](fontface/weight)  A string that contains the *weight* of the font. It is equivalent to the [`font-weight`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-weight) descriptor.

  [`FontFace.load()`](fontface/load)  Loads a font based on current object's constructor-passed requirements, including a location or source buffer, and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with the current FontFace object.

  
Examples
--------



 The code below defines a font face using data at the URL "myfont.woff" with a few font descriptors. Just to show how it works, we then define the `stretch` descriptor using a property. 

 
```
//Define a FontFace
const font = new FontFace("myfont", "url(myfont.woff)", {
  style: "italic",
  weight: "400",
});

font.stretch = "condensed";

```
 Next we load the font using [`FontFace.load()`](fontface/load) and use the returned promise to track completion or report an error.

 
```
//Load the font
font.load().then(
  () => {
    // Resolved - add font to document.fonts
  },
  (err) => {
    console.error(err);
  }
);

```
  To actually *use* the font we will need to add it to a [`FontFaceSet`](fontfaceset). We could do that before or after loading the font. 

 For additional examples see [CSS Font Loading API > Examples](css_font_loading_api#examples).



Specifications
--------------




| Specification |
| --- |
| [CSS Font Loading Module Level 3 # fontface-interface](https://w3c.github.io/csswg-drafts/css-font-loading/#fontface-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FontFace` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 4.0 |
| `FontFace` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 4.0 |
| `ascentOverride` | 87 | 87 | 89 | No | 73 | No | 87 | 87 | 89 | 62 | No | 14.0 |
| `descentOverride` | 87 | 87 | 89 | No | 73 | No | 87 | 87 | 89 | 62 | No | 14.0 |
| `display` | 60 | 79 | 58 | No | 47 | 11.1 | 60 | 60 | 58 | 44 | 11.3 | 8.0 |
| `family` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 4.0 |
| `featureSettings` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 4.0 |
| `lineGapOverride` | 87 | 87 | 89 | No | 73 | No | 87 | 87 | 89 | 62 | No | 14.0 |
| `load` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 4.0 |
| `loaded` | 37 | 79 | 41 | No | 24 | 10 | 37 | 37 | 41 | 24 | 10 | 4.0 |
| `status` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 4.0 |
| `stretch` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 4.0 |
| `style` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 4.0 |
| `unicodeRange` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 4.0 |
| `variant` | 35 | 79 | 41 | No | 22 | 10–13.1 | 37 | 35 | 41 | 22 | 10–13.4 | 4.0 |
| `variationSettings` | No | No | 62 | No | No | No | No | No | 62 | No | No | No |
| `weight` | 35 | 79 | 41 | No | 22 | 10 | 37 | 35 | 41 | 22 | 10 | 4.0 |
| `worker_support` | 69 | 79 | 105 | No | 56 | No | 69 | 69 | 105 | 48 | No | 10.0 |


See also
--------


* [@font-face](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FontFace>

FontFaceSetLoadEvent
====================



The `FontFaceSetLoadEvent` interface of the [CSS Font Loading API](css_font_loading_api) represents events fired at a [`FontFaceSet`](fontfaceset) after it starts loading font faces.

 Events are fired when font loading starts ([`loading`](fontfaceset/loading_event)), loading completes ([`loadingdone`](fontfaceset/loadingdone_event)) or there is an error loading one of the fonts ([`loadingerror`](fontfaceset/loadingerror_event)).


 Event FontFaceSetLoadEvent

Constructor
-----------


 [`FontFaceSetLoadEvent()`](fontfacesetloadevent/fontfacesetloadevent)  Creates a new `FontFaceSetLoadEvent` object.

  
Instance properties
-------------------



*Also inherits properties from its parent [`Event`](event)*.

  
[`FontFaceSetLoadEvent.fontfaces`](fontfacesetloadevent/fontfaces) Read only 
   Returns an array of [`FontFace`](fontface) instances. Depending on the event, the array will contain font faces that are loading (`loading`), have successfully loaded (`loadingdone`), or have failed to load (`loadingerror`). 

  

Instance methods
----------------


*Inherits methods from its parent, [`Event`](event)*.


Specifications
--------------




| Specification |
| --- |
| [CSS Font Loading Module Level 3 # fontfacesetloadevent](https://w3c.github.io/csswg-drafts/css-font-loading/#fontfacesetloadevent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FontFaceSetLoadEvent` | 57 | 79 | 41 | No | 44 | No | No | 57 | 41 | 43 | No | 7.0 |
| `FontFaceSetLoadEvent` | 35 | 79 | 41 | No | 22 | No | No | 35 | 41 | 22 | No | 3.0 |
| `fontfaces` | 35 | 79 | 41 | No | 22 | No | No | 35 | 41 | 22 | No | 3.0 |
| `worker_support` | 69 | 79 | 105 | No | 56 | No | No | 69 | 105 | 48 | No | 10.0 |


See also
--------


* [`Document.fonts`](document/fonts)
* [`WorkerGlobalScope.fonts`](workerglobalscope/fonts)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FontFaceSetLoadEvent>

FormData
========



The `FormData` interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using the [`fetch()`](fetch) or [`XMLHttpRequest.send()`](xmlhttprequest/send) method. It uses the same format a form would use if the encoding type were set to `"multipart/form-data"`.

 You can also pass it directly to the [`URLSearchParams`](urlsearchparams) constructor if you want to generate query parameters in the way a [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) would do if it were using simple `GET` submission.

 An object implementing `FormData` can directly be used in a [`for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) structure, instead of [`entries()`](formdata/entries): `for (const p of myFormData)` is equivalent to `for (const p of myFormData.entries())`.

  **Note:** This feature is available in [Web Workers](web_workers_api).

 

Constructor
-----------


 [`FormData()`](formdata/formdata)  Creates a new `FormData` object.

  
Instance methods
----------------


 [`FormData.append()`](formdata/append)  Appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist.

  [`FormData.delete()`](formdata/delete)  Deletes a key/value pair from a `FormData` object.

  [`FormData.entries()`](formdata/entries)  Returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) that iterates through all key/value pairs contained in the `FormData`.

  [`FormData.get()`](formdata/get)  Returns the first value associated with a given key from within a `FormData` object.

  [`FormData.getAll()`](formdata/getall)  Returns an array of all the values associated with a given key from within a `FormData`.

  [`FormData.has()`](formdata/has)  Returns whether a `FormData` object contains a certain key.

  [`FormData.keys()`](formdata/keys)  Returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) iterates through all keys of the key/value pairs contained in the `FormData`.

  [`FormData.set()`](formdata/set)  Sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist.

  [`FormData.values()`](formdata/values)  Returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) that iterates through all values contained in the `FormData`.

  
Specifications
--------------




| Specification |
| --- |
| [XMLHttpRequest Standard # interface-formdata](https://xhr.spec.whatwg.org/#interface-formdata) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@iterator` | 50 | 18 | 44 | No | 37 | 11.1 | 50 | 50 | 44 | 37 | 11.3 | 5.0 |
| `FormData` | 5 | 12 | 4 | 10 | 12 | 5 | 3 | 18 | 4 | 12 | 5 | 1.0 |
| `FormData` | 5 | 12 | 4Before Firefox 7, specifying a [`Blob`](https://developer.mozilla.org/docs/Web/API/Blob) as the data to append to the object, the filename reported in the `Content-Disposition` HTTP header was an empty string, resulting in errors on some servers. Starting with Firefox 7, the filename `blob` is sent. | 10 | 12 | 5 | 3XHR in Android 4.0 sends empty content for `FormData` with `blob`. | 18 | 4Before Firefox 7, specifying a [`Blob`](https://developer.mozilla.org/docs/Web/API/Blob) as the data to append to the object, the filename reported in the `Content-Disposition` HTTP header was an empty string, resulting in errors on some servers. Starting with Firefox 7, the filename `blob` is sent. | 12 | 5 | 1.0 |
| `append` | 5 | 12 | 4Before Firefox 7, specifying a [`Blob`](https://developer.mozilla.org/docs/Web/API/Blob) as the data to append to the object, the filename reported in the `Content-Disposition` HTTP header was an empty string, resulting in errors on some servers. Starting with Firefox 7, the filename `blob` is sent. | 10With the "Include local directory pass when uploading files to a server" option enabled, IE will change the filename inside the [`Blob`](https://developer.mozilla.org/docs/Web/API/Blob) on the fly. To have direct control of the sent filename, the developer should send the filename as the third parameter value, i.e. `formData.append(name, value, filename)`. | 12 | 5 | 3XHR in Android 4.0 sends empty content for `FormData` with `blob`. | 18 | 4Before Firefox 7, specifying a [`Blob`](https://developer.mozilla.org/docs/Web/API/Blob) as the data to append to the object, the filename reported in the `Content-Disposition` HTTP header was an empty string, resulting in errors on some servers. Starting with Firefox 7, the filename `blob` is sent. | 12 | 5 | 1.0 |
| `delete` | 50 | 18 | 39 | No | 37 | 11.1 | 50 | 50 | 39 | 37 | 11.3 | 5.0 |
| `entries` | 50 | 18 | 44 | No | 37 | 11.1 | 50 | 50 | 44 | 37 | 11.3 | 5.0 |
| `forEach` | 50 | 18 | 47 | No | 37 | 11.1 | 50 | 50 | 47 | 37 | 11.3 | 5.0 |
| `get` | 50 | 18 | 39 | No | 37 | 11.1 | 50 | 50 | 39 | 37 | 11.3 | 5.0 |
| `getAll` | 50 | 18 | 39 | No | 37 | 11.1 | 50 | 50 | 39 | 37 | 11.3 | 5.0 |
| `has` | 50 | 18 | 39 | No | 37 | 11.1 | 50 | 50 | 39 | 37 | 11.3 | 5.0 |
| `keys` | 50 | 18 | 44 | No | 37 | 11.1 | 50 | 50 | 44 | 37 | 11.3 | 5.0 |
| `set` | 50 | 18 | 39 | No | 37 | 11.1 | 50 | 50 | 39 | 37 | 11.3 | 5.0 |
| `values` | 50 | 18 | 44 | No | 37 | 11.1 | 50 | 50 | 44 | 37 | 11.3 | 5.0 |
| `worker_support` | 50 | 79 | 39 | No | 37 | 13.1 | 50 | 50 | 39 | 37 | 13.4 | 5.0 |


See also
--------


* [Using FormData objects](formdata/using_formdata_objects)
* [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FormData>

FormDataEvent
=============



The `FormDataEvent` interface represents a [`formdata` event](htmlformelement/formdata_event) — such an event is fired on an [`HTMLFormElement`](htmlformelement) object after the entry list representing the form's data is constructed. This happens when the form is submitted, but can also be triggered by the invocation of a [`FormData()`](formdata/formdata) constructor.

 This allows a [`FormData`](formdata) object to be quickly obtained in response to a `formdata` event firing, rather than needing to put it together yourself when you wish to submit form data via a method like [`XMLHttpRequest`](xmlhttprequest) (see [Using FormData objects](formdata/using_formdata_objects)).


 Event FormDataEvent

Constructor
-----------


 [`FormDataEvent()`](formdataevent/formdataevent)  Creates a new `FormDataEvent` object instance.

  
Instance properties
-------------------



*Inherits properties from its parent interface, [`Event`](event).*

  [`FormDataEvent.formData`](formdataevent/formdata)  Contains the [`FormData`](formdata) object representing the data contained in the form when the event was fired.

  

Instance methods
----------------


*Inherits methods from its parent interface, [`Event`](event).*


Examples
--------



```
// grab reference to form

const formElem = document.querySelector("form");

// submit handler

formElem.addEventListener("submit", (e) => {
  // on form submission, prevent default
  e.preventDefault();

  console.log(form.querySelector('input[name="field1"]')); // FOO
  console.log(form.querySelector('input[name="field2"]')); // BAR

  // construct a FormData object, which fires the formdata event
  const formData = new FormData(formElem);
  // formdata gets modified by the formdata event
  console.log(formData.get("field1")); // foo
  console.log(formData.get("field2")); // bar
});

// formdata handler to retrieve data

formElem.addEventListener("formdata", (e) => {
  console.log("formdata fired");

  // modifies the form data
  const formData = e.formData;
  formData.set("field1", formData.get("field1").toLowerCase());
  formData.set("field2", formData.get("field2").toLowerCase());
});

```

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-formdataevent-interface](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#the-formdataevent-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FormDataEvent` | 77 | 79 | 72 | No | 64 | 15 | 77 | 77 | 79 | 55 | 15 | 12.0 |
| `FormDataEvent` | 77 | 79 | 72 | No | 64 | 15 | 77 | 77 | 79 | 55 | 15 | 12.0 |
| `formData` | 77 | 79 | 72 | No | 64 | 15 | 77 | 77 | 79 | 55 | 15 | 12.0 |


See also
--------


* [`XMLHTTPRequest`](xmlhttprequest)
* [`FormData`](formdata)
* [Using FormData objects](formdata/using_formdata_objects)
* [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FormDataEvent>

GainNode
========



The `GainNode` interface represents a change in volume. It is an [`AudioNode`](audionode) audio-processing module that causes a given gain to be applied to the input data before its propagation to the output. A `GainNode` always has exactly one input and one output, both with the same number of channels.

 The gain is a unitless value, changing with time, that is multiplied to each corresponding sample of all input channels. If modified, the new gain is instantly applied, causing unaesthetic 'clicks' in the resulting audio. To prevent this from happening, never change the value directly but use the exponential interpolation methods on the [`AudioParam`](audioparam) interface.

  ![The GainNode is increasing the gain of the output.] 


 EventTarget AudioNode GainNode 

|  |  |
| --- | --- |
| Number of inputs | `1` |
| Number of outputs | `1` |
| Channel count mode | `"max"` |
| Channel count | `2` (not used in the default count mode) |
| Channel interpretation | `"speakers"` |



Constructor
-----------


 [`GainNode()`](gainnode/gainnode)  Creates and returns a new `GainNode` object. As an alternative, you can use the [`BaseAudioContext.createGain()`](baseaudiocontext/creategain) factory method; see [Creating an AudioNode](audionode#creating_an_audionode).

  
Instance properties
-------------------



*Inherits properties from its parent, [`AudioNode`](audionode)*.

  
[`GainNode.gain`](gainnode/gain) Read only 
  An [a-rate](audioparam#a-rate) [`AudioParam`](audioparam) representing the amount of gain to apply. You have to set [`AudioParam.value`](audioparam/value) or use the methods of `AudioParam` to change the effect of gain.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`AudioNode`](audionode)*.


Example
-------


See [`BaseAudioContext.createGain()`](baseaudiocontext/creategain#examples) for example code showing how to use an `AudioContext` to create a `GainNode`.


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # GainNode](https://webaudio.github.io/web-audio-api/#GainNode) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GainNode` | 55 | 79 | 53 | No | 42 | 14.1 | 55 | 55 | 53 | 42 | 14.5 | 6.0 |
| `GainNode` | 24 | 12 | 25 | No | 15 | 7 | ≤37 | 25 | 25 | 14 | 7 | 1.5 |
| `gain` | 24 | 12 | 25 | No | 15 | 7 | ≤37 | 25 | 25 | 14 | 7 | 1.5 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GainNode>

Gamepad
=======



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `Gamepad` interface of the [Gamepad API](gamepad_api) defines an individual gamepad or other controller, allowing access to information such as button presses, axis positions, and id.

 A Gamepad object can be returned in one of two ways: via the `gamepad` property of the [`gamepadconnected`](window/gamepadconnected_event) and [`gamepaddisconnected`](window/gamepaddisconnected_event) events, or by grabbing any position in the array returned by the [`Navigator.getGamepads()`](navigator/getgamepads) method.



Instance properties
-------------------


 
[`Gamepad.axes`](gamepad/axes) Read only 
  An array representing the controls with axes present on the device (e.g. analog thumb sticks).

  
[`Gamepad.buttons`](gamepad/buttons) Read only 
  An array of [`gamepadButton`](gamepadbutton) objects representing the buttons present on the device.

  
[`Gamepad.connected`](gamepad/connected) Read only 
  A boolean indicating whether the gamepad is still connected to the system.

  
[`Gamepad.displayId`](gamepad/displayid) Read only   Deprecated   Non-standard 
  Returns the [`VRDisplay.displayId`](vrdisplay/displayid) of an associated [`VRDisplay`](vrdisplay) (if relevant) — the `VRDisplay` that the gamepad is controlling the displayed scene of.

  
[`Gamepad.hand`](gamepad/hand) Read only   Experimental 
  An enum defining what hand the controller is being held in, or is most likely to be held in.

  
[`Gamepad.hapticActuators`](gamepad/hapticactuators) Read only   Experimental 
  An array containing [`GamepadHapticActuator`](gamepadhapticactuator) objects, each of which represents haptic feedback hardware available on the controller.

  
[`Gamepad.vibrationActuator`](gamepad/vibrationactuator) Read only   Non-standard 
  A [`GamepadHapticActuator`](gamepadhapticactuator) object, which represents haptic feedback hardware available on the controller.

  
[`Gamepad.id`](gamepad/id) Read only 
  A string containing identifying information about the controller.

  
[`Gamepad.index`](gamepad/index) Read only 
  An integer that is auto-incremented to be unique for each device currently connected to the system.

  
[`Gamepad.mapping`](gamepad/mapping) Read only 
  A string indicating whether the browser has remapped the controls on the device to a known layout.

  
[`Gamepad.pose`](gamepad/pose) Read only   Experimental 
  A [`GamepadPose`](gamepadpose) object representing the pose information associated with a WebVR controller (e.g. its position and orientation in 3D space).

  
[`Gamepad.timestamp`](gamepad/timestamp) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) representing the last time the data for this gamepad was updated.

  
Example
-------



```
window.addEventListener("gamepadconnected", (e) => {
  console.log(
    "Gamepad connected at index %d: %s. %d buttons, %d axes.",
    e.gamepad.index,
    e.gamepad.id,
    e.gamepad.buttons.length,
    e.gamepad.axes.length
  );
});

```

Specifications
--------------




| Specification |
| --- |
| [Gamepad # gamepad-interface](https://w3c.github.io/gamepad/#gamepad-interface) |
| [Gamepad Extensions # partial-gamepad-interface](https://w3c.github.io/gamepad/extensions.html#partial-gamepad-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Gamepad` | 21 | 12 | 29 | No | 15 | 10.1 | 4.4 | 25 | 32 | 14 | 10.3 | 1.5 |
| `axes` | 21 | 12 | 29 | No | 15 | 10.1 | 4.4 | 25 | 32 | 14 | 10.3 | 1.5 |
| `buttons` | 21 | 12 | 29 | No | 15 | 10.1 | 4.4 | 25 | 32 | 14 | 10.3 | 1.5 |
| `connected` | 25 | 12 | 29 | No | 15 | 10.1 | 4.4 | 25 | 32 | 14 | 10.3 | 1.5 |
| `displayId` | No | 79–8015–79 | 9864–98macOS support was enabled in Firefox 64.55–98Windows support was enabled in Firefox 55. | No | No | No | No | 55–80Currently supported only by Google Daydream. | 55 | 42–57Currently supported only by Google Daydream. | No | 6.0–13.0Currently supported only by Google Daydream. |
| `hand` | No | 15–79 | 55 | No | No | No | No | No | 55 | No | No | No |
| `hapticActuators` | No | 15–79 | 55 | No | No | No | No | No | 55 | No | No | No |
| `id` | 21 | 12 | 29 | No | 15 | 10.1 | 4.4 | 25 | 32 | 14 | 10.3 | 1.5 |
| `index` | 21 | 12 | 29 | No | 15 | 10.1 | 4.4 | 25 | 32 | 14 | 10.3 | 1.5 |
| `mapping` | 21 | 12 | 29 | No | 15 | 10.1 | 4.4 | 25 | 32 | 14 | 10.3 | 1.5 |
| `pose` | No | 15–79 | 55 | No | No | No | No | No | 55 | No | No | No |
| `secure_context_required` | 86 | 86 | 91 | No | 72 | No | No | 86 | 91 | No | No | No |
| `timestamp` | 21 | 12 | 29 | No | 15 | 10.1 | 4.4 | 25 | 32 | 14 | 10.3 | 1.5 |
| `vibrationActuator` | 68 | 79 | No | No | 55 | 16.4 | No | 68 | No | 48 | 16.4 | 10.0 |


See also
--------


* [Using the Gamepad API](gamepad_api/using_the_gamepad_api)
* [Gamepad API](gamepad_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Gamepad>

GamepadButton
=============



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `GamepadButton` interface defines an individual button of a gamepad or other controller, allowing access to the current state of different types of buttons available on the control device.

 A `GamepadButton` object is returned by querying any value of the array returned by the `buttons` property of the [`Gamepad`](gamepad) interface.



Instance properties
-------------------


 
[`GamepadButton.pressed`](gamepadbutton/pressed) Read only 
  A boolean value indicating whether the button is currently pressed (`true`) or unpressed (`false`).

  
[`GamepadButton.touched`](gamepadbutton/touched) Read only 
  A boolean value indicating whether the button is currently touched (`true`) or not touched (`false`).

  
[`GamepadButton.value`](gamepadbutton/value) Read only 
  A double value used to represent the current state of analog buttons, such as the triggers on many modern gamepads. The values are normalized to the range 0.0 —1.0, with 0.0 representing a button that is not pressed, and 1.0 representing a button that is fully pressed.

  
Example
-------



The button values in the following example are stored as an array of [`GamepadButton`](gamepadbutton) objects. This simple example checks to see if the [`GamepadButton.value`](gamepadbutton/value) of a button is greater than `0`, or if the [`GamepadButton.pressed`](gamepadbutton/pressed) property indicates the button has been pressed.

 
```
function gameLoop() {
  const gp = navigator.getGamepads()[0];

  if (gp.buttons[0].value > 0 || gp.buttons[0].pressed) {
    b--;
  } else if (gp.buttons[1].value > 0 || gp.buttons[1].pressed) {
    a++;
  } else if (gp.buttons[2].value > 0 || gp.buttons[2].pressed) {
    b++;
  } else if (gp.buttons[3].value > 0 || gp.buttons[3].pressed) {
    a--;
  }

  ball.style.left = `${a \* 2}px`; // ball is a UI widget
  ball.style.top = `${b \* 2}px`;

  requestAnimationFrame(gameLoop);
}

```


Specifications
--------------




| Specification |
| --- |
| [Gamepad # gamepadbutton-interface](https://w3c.github.io/gamepad/#gamepadbutton-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GamepadButton` | 21 | 12 | 29 | No | 15 | 10.1 | 4.4 | 25 | 32 | 14 | 10.3 | 1.5 |
| `pressed` | 21 | 12 | 29 | No | 15 | 10.1 | 4.4 | 25 | 32 | 14 | 10.3 | 1.5 |
| `secure_context_required` | 86 | 86 | 91 | No | 72 | No | No | 86 | 91 | No | No | No |
| `touched` | 73 | 15 | 55 | No | 60 | No | No | 73 | 55 | 52 | No | 11.0 |
| `value` | 21 | 12 | 29 | No | 15 | 10.1 | 4.4 | 25 | 32 | 14 | 10.3 | 1.5 |


See also
--------


[Using the Gamepad API](gamepad_api/using_the_gamepad_api)



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GamepadButton>

GamepadEvent
============



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The GamepadEvent interface of the Gamepad API contains references to gamepads connected to the system, which is what the gamepad events [`gamepadconnected`](window/gamepadconnected_event) and [`gamepaddisconnected`](window/gamepaddisconnected_event) are fired in response to.


 Event GamepadEvent

Constructor
-----------


 [`GamepadEvent()`](gamepadevent/gamepadevent)  Returns a new `GamepadEvent` object.

  
Instance properties
-------------------


 
[`GamepadEvent.gamepad`](gamepadevent/gamepad) Read only 
  Returns a [`Gamepad`](gamepad) object, providing access to the associated gamepad data for the event fired.

  
Examples
--------



The gamepad property being called on a fired [`gamepadconnected`](window/gamepadconnected_event) event.

 
```
window.addEventListener("gamepadconnected", (e) => {
  console.log(
    "Gamepad connected at index %d: %s. %d buttons, %d axes.",
    e.gamepad.index,
    e.gamepad.id,
    e.gamepad.buttons.length,
    e.gamepad.axes.length
  );
});

```
 And on a [`gamepaddisconnected`](window/gamepaddisconnected_event) event.

 
```
window.addEventListener("gamepaddisconnected", (e) => {
  console.log(
    "Gamepad disconnected from index %d: %s",
    e.gamepad.index,
    e.gamepad.id
  );
});

```


Specifications
--------------




| Specification |
| --- |
| [Gamepad # gamepadevent-interface](https://w3c.github.io/gamepad/#gamepadevent-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GamepadEvent` | 35 | 12 | 29 | No | 22 | 10.1 | 37 | 35 | 32 | 22 | 10.3 | 3.0 |
| `GamepadEvent` | 21 | 12 | 29 | No | 15 | 10.1 | 4.4 | 25 | 32 | 14 | 10.3 | 1.5 |
| `gamepad` | 21 | 12 | 29 | No | 15 | 10.1 | 4.4 | 25 | 32 | 14 | 10.3 | 1.5 |
| `secure_context_required` | 86 | 86 | 91 | No | 72 | No | No | 86 | 91 | No | No | No |


See also
--------


[Using the Gamepad API](gamepad_api/using_the_gamepad_api)



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GamepadEvent>

GamepadHapticActuator
=====================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `GamepadHapticActuator` interface of the [Gamepad API](gamepad_api) represents hardware in the controller designed to provide haptic feedback to the user (if available), most commonly vibration hardware.

 This interface is accessible through the [`Gamepad.hapticActuators`](gamepad/hapticactuators) property.



Instance properties
-------------------


 
[`GamepadHapticActuator.type`](gamepadhapticactuator/type) Read only 
  Returns an enum representing the type of the haptic hardware.

  
Instance methods
----------------


 
[`GamepadHapticActuator.pulse()`](gamepadhapticactuator/pulse) Read only 
  Makes the hardware pulse at a certain intensity for a specified duration.

  
[`GamepadHapticActuator.playEffect()`](gamepadhapticactuator/playeffect) Read only   Non-standard 
  Makes the hardware play a specific vibration pattern.

  
Examples
--------



```
const gamepad = navigator.getGamepads()[0];

gamepad.hapticActuators[0].pulse(1.0, 200);

gamepad.vibrationActuator.playEffect("dual-rumble", {
  startDelay: 0,
  duration: 200,
  weakMagnitude: 1.0,
  strongMagnitude: 1.0,
});

```

Specifications
--------------




| Specification |
| --- |
| [Gamepad Extensions # gamepadhapticactuator-interface](https://w3c.github.io/gamepad/extensions.html#gamepadhapticactuator-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GamepadHapticActuator` | 68 | 15 | 55 | No | 55 | 16.4 | 68 | 68 | 55 | 48 | 16.4 | 10.0 |
| `playEffect` | 68 | 15 | No | No | 55 | 16.4 | 68 | 68 | No | 48 | 16.4 | 10.0 |
| `pulse` | No | 15–79 | 55 | No | No | No | No | No | 55 | No | No | No |
| `reset` | 68 | 15 | No | No | 55 | 16.4 | 68 | 68 | No | 48 | 16.4 | 10.0 |
| `secure_context_required` | 86 | 86 | 91 | No | 72 | No | No | 86 | 91 | No | No | No |
| `type` | 68 | 15 | 55 | No | 55 | 16.4 | 68 | 68 | 55 | 48 | 16.4 | 10.0 |


See also
--------


* [Gamepad API](gamepad_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GamepadHapticActuator>

FragmentDirective
=================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `FragmentDirective` interface is an object representing the text fragments highlighted in the current document.

 It is accessed via the [`Document.fragmentDirective`](document/fragmentdirective) property.



Instance properties
-------------------


None.


Instance methods
----------------


None.


Examples
--------



Try running the following in a supporting browser's devtools, in a tab with one or more matched text fragments:

 
```
document.fragmentDirective;

```
 You should get a [`FragmentDirective`](fragmentdirective) object instance returned with a structure similar to the following:

 
```
items: [
  {
    prefix: "",
    textStart: "Module Workers",
    textEnd: "",
    suffix: "support",
    type: "text",
  },
  {
    prefix: "feedback on",
    textStart: "usability",
    textEnd: "",
    suffix: "",
    type: "text",
  },
];

```
 This functionality is mainly intended for feature detection at present, but in future, it could be expanded to include other information such as translation hints.



Specifications
--------------




| Specification |
| --- |
| [URL Fragment Text Directives # fragmentdirective](https://wicg.github.io/scroll-to-text-fragment/#fragmentdirective) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `FragmentDirective` | 81 | 83 | No | No | 68 | No | 81 | 81 | No | 58 | No | 13.0 |


See also
--------


* [Text fragments](https://developer.mozilla.org/en-US/docs/Web/Text_fragments)
* [`::target-text`](https://developer.mozilla.org/en-US/docs/Web/CSS/::target-text)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/FragmentDirective>

GamepadPose
===========



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GamepadPose` interface of the [Gamepad API](gamepad_api) represents the pose of a [WebVR](webvr_api) controller at a given timestamp (which includes orientation, position, velocity, and acceleration information).

 This interface is accessible through the [`Gamepad.pose`](gamepad/pose) property.



Instance properties
-------------------


 
[`GamepadPose.hasOrientation`](gamepadpose/hasorientation) Read only   Experimental 
  Returns a boolean indicating whether the gamepad is capable of returning orientation information (`true`) or not (`false`).

  
[`GamepadPose.hasPosition`](gamepadpose/hasposition) Read only   Experimental 
  Returns a boolean indicating whether the gamepad is capable of returning position information (`true`) or not (`false`).

  
[`GamepadPose.position`](gamepadpose/position) Read only   Experimental 
  Returns the position of the [`Gamepad`](gamepad) as a 3D vector.

  
[`GamepadPose.linearVelocity`](gamepadpose/linearvelocity) Read only   Experimental 
  Returns the linear velocity of the [`Gamepad`](gamepad), in meters per second.

  
[`GamepadPose.linearAcceleration`](gamepadpose/linearacceleration) Read only   Experimental 
  Returns the linear acceleration of the [`Gamepad`](gamepad), in meters per second per second.

  
[`GamepadPose.orientation`](gamepadpose/orientation) Read only   Experimental 
  Returns the orientation of the [`Gamepad`](gamepad), as a quarternion value.

  
[`GamepadPose.angularVelocity`](gamepadpose/angularvelocity) Read only   Experimental 
  Returns the angular velocity of the [`Gamepad`](gamepad), in radians per second.

  
[`GamepadPose.angularAcceleration`](gamepadpose/angularacceleration) Read only   Experimental 
  Returns the angular acceleration of the [`Gamepad`](gamepad), in meters per second per second.

  
Examples
--------


TBD.


Specifications
--------------




| Specification |
| --- |
| [Gamepad Extensions # gamepadpose-interface](https://w3c.github.io/gamepad/extensions.html#gamepadpose-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GamepadPose` | No | 15–79 | 55 | No | No | No | No | No | 55 | No | No | No |
| `angularAcceleration` | No | 15–79 | 55 | No | No | No | No | No | 55 | No | No | No |
| `angularVelocity` | No | 15–79 | 55 | No | No | No | No | No | 55 | No | No | No |
| `hasOrientation` | No | 15–79 | 55 | No | No | No | No | No | 55 | No | No | No |
| `hasPosition` | No | 15–79 | 55 | No | No | No | No | No | 55 | No | No | No |
| `linearAcceleration` | No | 15–79 | 55 | No | No | No | No | No | 55 | No | No | No |
| `linearVelocity` | No | 15–79 | 55 | No | No | No | No | No | 55 | No | No | No |
| `orientation` | No | 15–79 | 55 | No | No | No | No | No | 55 | No | No | No |
| `position` | No | 15–79 | 55 | No | No | No | No | No | 55 | No | No | No |
| `secure_context_required` | No | No | 91 | No | No | No | No | No | 91 | No | No | No |


See also
--------


* [WebVR API](webvr_api)
* [Gamepad API](gamepad_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GamepadPose>

Geolocation
===========



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `Geolocation` interface represents an object able to obtain the position of the device programmatically. It gives Web content access to the location of the device. This allows a website or app to offer customized results based on the user's location.

 An object with this interface is obtained using the [`navigator.geolocation`](navigator/geolocation) property implemented by the [`Navigator`](navigator) object.

  **Note:** For security reasons, when a web page tries to access location information, the user is notified and asked to grant permission. Be aware that each browser has its own policies and methods for requesting this permission.

 

Instance properties
-------------------


*The `Geolocation` interface neither implements, nor inherits any property.*


Instance methods
----------------



*The `Geolocation` interface doesn't inherit any method.*

  
[`Geolocation.getCurrentPosition()`](geolocation/getcurrentposition) Secure context
  Determines the device's current location and gives back a [`GeolocationPosition`](geolocationposition) object with the data.

  
[`Geolocation.watchPosition()`](geolocation/watchposition) Secure context
  Returns a `long` value representing the newly established callback function to be invoked whenever the device location changes.

  
[`Geolocation.clearWatch()`](geolocation/clearwatch) Secure context
  Removes the particular handler previously installed using `watchPosition()`.

  

Specifications
--------------




| Specification |
| --- |
| [Geolocation API # geolocation\_interface](https://w3c.github.io/geolocation-api/#geolocation_interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Geolocation` | 5 | 12 | 3.5[GPSD](https://gpsd.gitlab.io/gpsd/index.html) (GPS daemon) support added in Firefox 3.6. WiFi-based location is provided by Google ([privacy](https://support.mozilla.org/en-US/kb/does-firefox-share-my-location-websites)) or a custom provider ([MLS instructions](https://wiki.mozilla.org/CloudServices/Location/Software)). | 9 | 10.6 | 5 | ≤37 | 18 | 4 | 11 | ≤3 | 1.0 |
| `clearWatch` | 5 | 12 | 3.5 | 9 | 10.6 | 5 | ≤37 | 18 | 4 | 11 | ≤3 | 1.0 |
| `getCurrentPosition` | 5 | 12 | 3.5 | 9 | 10.6 | 5 | ≤37 | 18 | 4 | 11 | ≤3 | 1.0 |
| `secure_context_required` | 50 | 79 | 55 | No | 37 | 10 | 51Secure context is only required for applications targeting Android Nougat (7) and higher. See [bug 603574](https://crbug.com/603574). | 50 | 55 | 37 | 10 | 5.0 |
| `watchPosition` | 5 | 12 | 3.5 | 9 | 10.6 | 5 | ≤37 | 18 | 4 | 11 | ≤3 | 1.0 |


See also
--------


* [Using geolocation](geolocation_api/using_the_geolocation_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Geolocation>

GeolocationCoordinates
======================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `GeolocationCoordinates` interface represents the position and altitude of the device on Earth, as well as the accuracy with which these properties are calculated.



Instance properties
-------------------



*The `GeolocationCoordinates` interface doesn't inherit any properties.*

  
[`GeolocationCoordinates.latitude`](geolocationcoordinates/latitude) Read only  Secure context
  Returns a `double` representing the position's latitude in decimal degrees.

  
[`GeolocationCoordinates.longitude`](geolocationcoordinates/longitude) Read only  Secure context
  Returns a `double` representing the position's longitude in decimal degrees.

  
[`GeolocationCoordinates.altitude`](geolocationcoordinates/altitude) Read only  Secure context
  Returns a `double` representing the position's altitude in meters, relative to sea level. This value can be `null` if the implementation cannot provide the data.

  
[`GeolocationCoordinates.accuracy`](geolocationcoordinates/accuracy) Read only  Secure context
  Returns a `double` representing the accuracy of the `latitude` and `longitude` properties, expressed in meters.

  
[`GeolocationCoordinates.altitudeAccuracy`](geolocationcoordinates/altitudeaccuracy) Read only  Secure context
  Returns a `double` representing the accuracy of the `altitude` expressed in meters. This value can be `null`.

  
[`GeolocationCoordinates.heading`](geolocationcoordinates/heading) Read only  Secure context
  Returns a `double` representing the direction towards which the device is facing. This value, specified in degrees, indicates how far off from heading true north the device is. `0` degrees represents true north, and the direction is determined clockwise (which means that east is `90` degrees and west is `270` degrees). If `speed` is `0`, `heading` is [`NaN`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN). If the device is unable to provide `heading` information, this value is `null`.

  
[`GeolocationCoordinates.speed`](geolocationcoordinates/speed) Read only  Secure context
  Returns a `double` representing the velocity of the device in meters per second. This value can be `null`.

  

Instance methods
----------------


*The `GeolocationCoordinates` interface neither implements, nor inherits any method.*


Specifications
--------------




| Specification |
| --- |
| [Geolocation API # coordinates\_interface](https://w3c.github.io/geolocation-api/#coordinates_interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GeolocationCoordinates` | 795–78 | 7912–79 | 723.5–71 | 9 | 1610.6–15 | 13.15–13.1 | 79≤37–78 | 7918–78 | 794–79 | 1611–14 | 13.4≤3–13.4 | 1.0 |
| `accuracy` | 5 | 12 | 3.5 | 9 | 1610.6–15 | 5 | ≤37 | 18 | 4 | 1611–14 | ≤3 | 1.0 |
| `altitude` | 5 | 12 | 3.5 | 9 | 1610.6–15 | 5 | ≤37 | 18 | 4 | 1611–14 | ≤3 | 1.0 |
| `altitudeAccuracy` | 5 | 12 | 3.5 | 9 | 1610.6–15 | 5 | ≤37 | 18 | 4 | 1611–14 | ≤3 | 1.0 |
| `heading` | 5 | 12 | 3.5 | 9 | 1610.6–15 | 5 | ≤37 | 18 | 4 | 1611–14 | ≤3 | 1.0 |
| `latitude` | 5 | 12 | 3.5 | 9 | 1610.6–15 | 5 | ≤37 | 18 | 4 | 1611–14 | ≤3 | 1.0 |
| `longitude` | 5 | 12 | 3.5 | 9 | 1610.6–15 | 5 | ≤37 | 18 | 4 | 1611–14 | ≤3 | 1.0 |
| `secure_context_required` | 47 | 79 | 55 | No | 34 | 10 | No | 47 | 55 | 34 | 10 | 5.0 |
| `speed` | 5 | 12 | 3.5 | 9 | 1610.6–15 | 5 | ≤37 | 18 | 4 | 1611–14 | ≤3 | 1.0 |


See also
--------


* [Using the Geolocation API](geolocation_api/using_the_geolocation_api)
* [`Geolocation`](geolocation)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GeolocationCoordinates>

GeolocationPosition
===================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `GeolocationPosition` interface represents the position of the concerned device at a given time. The position, represented by a [`GeolocationCoordinates`](geolocationcoordinates) object, comprehends the 2D position of the device, on a spheroid representing the Earth, but also its altitude and its speed.



Instance properties
-------------------



*The `GeolocationPosition` interface doesn't inherit any properties.*

  
[`GeolocationPosition.coords`](geolocationposition/coords) Read only  Secure context
  Returns a [`GeolocationCoordinates`](geolocationcoordinates) object defining the current location.

  
[`GeolocationPosition.timestamp`](geolocationposition/timestamp) Read only  Secure context
  Returns a timestamp, given as [Unix time](https://developer.mozilla.org/en-US/docs/Glossary/Unix_time) in milliseconds, representing the time at which the location was retrieved.

  

Instance methods
----------------


*The `GeolocationPosition` interface neither implements, nor inherits any methods.*


Specifications
--------------




| Specification |
| --- |
| [Geolocation API # position\_interface](https://w3c.github.io/geolocation-api/#position_interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GeolocationPosition` | 795–78 | 7912–79 | 723.5–71 | 9 | 16 | 13.15–13.1 | 79≤37–78 | 7918–78 | 794–79 | 16 | 13.4≤3–13.4 | 12.01.0–12.0 |
| `coords` | 5 | 12 | 3.5 | 9 | 16 | 5 | ≤37 | 18 | 4 | 16 | ≤3 | 1.0 |
| `secure_context_required` | 47 | ≤18 | 55 | No | 34 | 10 | 47 | 47 | 55 | 34 | 10 | 5.0 |
| `timestamp` | 5 | 12 | 3.5 | 9 | 16 | 5 | ≤37 | 18 | 4 | 16 | ≤3 | 1.0 |


See also
--------


* [Using the Geolocation API](geolocation_api/using_the_geolocation_api)
* [`Geolocation`](geolocation)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPosition>

GeolocationPositionError
========================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `GeolocationPositionError` interface represents the reason of an error occurring when using the geolocating device.



Instance properties
-------------------



*The `GeolocationPositionError` interface doesn't inherit any property.*

  
[`GeolocationPositionError.code`](geolocationpositionerror/code) Read only  Secure context
  Returns an `unsigned short` representing the error code. The following values are possible:

 

| Value | Associated constant | Description |
| --- | --- | --- |
| `1` | `PERMISSION_DENIED` | The acquisition of the geolocation information failed because the page didn't have the necessary permissions, for example because it is blocked by a [Permissions Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy) |
| `2` | `POSITION_UNAVAILABLE` | The acquisition of the geolocation failed because at least one internal source of position returned an internal error. |
| `3` | `TIMEOUT` | The time allowed to acquire the geolocation was reached before the information was obtained. |

  
[`GeolocationPositionError.message`](geolocationpositionerror/message) Read only  Secure context
  Returns a human-readable string describing the details of the error. Specifications note that this is primarily intended for debugging use and not to be shown directly in a user interface.

  

Instance methods
----------------


*The `GeolocationPositionError` interface neither implements nor inherits any method.*


Specifications
--------------




| Specification |
| --- |
| [Geolocation API # position\_error\_interface](https://w3c.github.io/geolocation-api/#position_error_interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GeolocationPositionError` | 795–78 | 7912–79 | 723.5–71 | 9 | 16 | 13.15 | 79≤37–78 | 7918–78 | 794–79 | 16 | 13.44.2 | 12.01.0–12.0 |
| `code` | 5 | 12 | 3.5 | 9 | 16 | 5 | ≤37 | 18 | 4 | 16 | 4.2 | 1.0 |
| `message` | 5 | 12 | 3.5 | 9 | 16 | 5 | ≤37 | 18 | 4 | 16 | 4.2 | 1.0 |
| `secure_context_required` | 47 | ≤18 | 55 | No | 34 | 10 | 47 | 47 | 55 | 34 | 10 | 5.0 |


See also
--------


* [Using the Geolocation API](geolocation_api/using_the_geolocation_api)
* [`Geolocation`](geolocation)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPositionError>

GestureEvent
============



**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The `GestureEvent` is a proprietary interface specific to WebKit which gives information regarding multi-touch gestures. Events using this interface include [`gesturestart`](element/gesturestart_event), [`gesturechange`](element/gesturechange_event), and [`gestureend`](element/gestureend_event).



Instance properties
-------------------



*This interface also inherits properties of its parents, [`UIEvent`](uievent) and [`Event`](event).*

  
`GestureEvent.rotation` Read only   Non-standard 
  Change in rotation (in degrees) since the event's beginning. Positive values indicate clockwise rotation; negative values indicate counterclockwise rotation. Initial value: `0.0`.

  
`GestureEvent.scale` Read only   Non-standard 
  Distance between two digits since the event's beginning. Expressed as a floating-point multiple of the initial distance between the digits at the beginning of the gesture. Values below 1.0 indicate an inward pinch (zoom out). Values above 1.0 indicate an outward unpinch (zoom in). Initial value: `1.0`.

  

Instance methods
----------------



*This interface also inherits methods of its parents, [`UIEvent`](uievent) and [`Event`](event).*

  
`GestureEvent.initGestureEvent()`  Non-standard 
  Initializes the value of an `GestureEvent`. If the event has already been dispatched, this method does nothing.

  

Gesture event types
-------------------


* [`gesturestart`](element/gesturestart_event)
* [`gesturechange`](element/gesturechange_event)
* [`gestureend`](element/gestureend_event)

Specifications
--------------


*Not part of any specification.* Apple has [a description at the Safari Developer Library](https://developer.apple.com/documentation/webkitjs/gestureevent).


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GestureEvent` | No | No | No | No | No | 9 | No | No | No | No | 2 | No |
| `altKey` | No | No | No | No | No | 9 | No | No | No | No | 9 | No |
| `clientX` | No | No | No | No | No | 9 | No | No | No | No | 2 | No |
| `clientY` | No | No | No | No | No | 9 | No | No | No | No | 2 | No |
| `ctrlKey` | No | No | No | No | No | 9 | No | No | No | No | 9 | No |
| `initGestureEvent` | No | No | No | No | No | 9 | No | No | No | No | 2 | No |
| `metaKey` | No | No | No | No | No | 9 | No | No | No | No | 9 | No |
| `rotation` | No | No | No | No | No | 9 | No | No | No | No | 2 | No |
| `scale` | No | No | No | No | No | 9 | No | No | No | No | 2 | No |
| `screenX` | No | No | No | No | No | 9 | No | No | No | No | 2 | No |
| `screenY` | No | No | No | No | No | 9 | No | No | No | No | 2 | No |
| `shiftKey` | No | No | No | No | No | 9 | No | No | No | No | 9 | No |
| `target` | No | No | No | No | No | 9 | No | No | No | No | 9 | No |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GestureEvent>

GPU
===



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPU` interface of the [WebGPU API](webgpu_api) is the starting point for using WebGPU. It can be used to return a [`GPUAdapter`](gpuadapter) from which you can request devices, configure features and limits, and more.

 The `GPU` object for the current context is accessed via the [`Navigator.gpu`](navigator/gpu) or [`WorkerNavigator.gpu`](workernavigator/gpu) properties.



Instance methods
----------------


 
[`requestAdapter()`](gpu/requestadapter)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that fulfills with a [`GPUAdapter`](gpuadapter) object instance. From this you can request a [`GPUDevice`](gpudevice), which is the primary interface for using WebGPU functionality.

  
[`getPreferredCanvasFormat()`](gpu/getpreferredcanvasformat)  Experimental 
  Returns the optimal canvas texture format for displaying 8-bit depth, standard dynamic range content on the current system.

  
Examples
--------


### Requesting an adapter and a device



```
async function init() {
  if (!navigator.gpu) {
    throw Error("WebGPU not supported.");
  }

  const adapter = await navigator.gpu.requestAdapter();
  if (!adapter) {
    throw Error("Couldn't request WebGPU adapter.");
  }

  const device = await adapter.requestDevice();

  //...
}

```

### Configuring a GPUCanvasContext with the optimal texture format



```
const canvas = document.querySelector("#gpuCanvas");
const context = canvas.getContext("webgpu");

context.configure({
  device: device,
  format: navigator.gpu.getPreferredCanvasFormat(),
  alphaMode: "premultiplied",
});

```

Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpu-interface](https://gpuweb.github.io/gpuweb/#gpu-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPU` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `getPreferredCanvasFormat` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `requestAdapter` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPU>

GPUAdapter
==========



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUAdapter` interface of the [WebGPU API](webgpu_api) represents a GPU adapter. From this you can request a [`GPUDevice`](gpudevice), adapter info, features, and limits.

 A `GPUAdapter` object is requested using the [`GPU.requestAdapter()`](gpu/requestadapter) method.



Instance properties
-------------------


 
[`features`](gpuadapter/features)  Experimental  Read only 
  A [`GPUSupportedFeatures`](gpusupportedfeatures) object that describes additional functionality supported by the adapter.

  
[`isFallbackAdapter`](gpuadapter/isfallbackadapter)  Experimental  Read only 
  A boolean value. Returns `true` if the adapter is a [fallback adapter](gpu/requestadapter#fallback_adapters), and `false` if not.

  
[`limits`](gpuadapter/limits)  Experimental  Read only 
  A [`GPUSupportedLimits`](gpusupportedlimits) object that describes the limits supported by the adapter.

  
Instance methods
----------------


 
[`requestAdapterInfo()`](gpuadapter/requestadapterinfo)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that fulfills with a [`GPUAdapterInfo`](gpuadapterinfo) object containing identifying information about an adapter.

  
[`requestDevice()`](gpuadapter/requestdevice)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that fulfills with a [`GPUDevice`](gpudevice) object, which is the primary interface for communicating with the GPU.

  
Examples
--------



```
async function init() {
  if (!navigator.gpu) {
    throw Error("WebGPU not supported.");
  }

  const adapter = await navigator.gpu.requestAdapter();
  if (!adapter) {
    throw Error("Couldn't request WebGPU adapter.");
  }

  const device = await adapter.requestDevice();

  //...
}

```

Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpu-adapter](https://gpuweb.github.io/gpuweb/#gpu-adapter) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUAdapter` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `features` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `isFallbackAdapter` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `limits` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `requestAdapterInfo` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `requestDevice` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUAdapter>

GPUAdapterInfo
==============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUAdapterInfo` interface of the [WebGPU API](webgpu_api) contains identifying information about a [`GPUAdapter`](gpuadapter).

 A `GPUAdapterInfo` object instance is requested using the [`GPUAdapter.requestAdapterInfo()`](gpuadapter/requestadapterinfo) method.



Instance properties
-------------------


 
[`architecture`](gpuadapterinfo/architecture)  Experimental  Read only 
  The name of the family or class of GPUs the adapter belongs to. Returns an empty string if it is not available.

  
[`description`](gpuadapterinfo/description)  Experimental  Read only 
  A human-readable string describing the adapter. Returns an empty string if it is not available.

  
[`device`](gpuadapterinfo/device)  Experimental  Read only 
  A vendor-specific identifier for the adapter. Returns an empty string if it is not available.

  
[`vendor`](gpuadapterinfo/vendor)  Experimental  Read only 
  The name of the adapter vendor. Returns an empty string if it is not available.

  
Examples
--------



```
async function init() {
  if (!navigator.gpu) {
    throw Error("WebGPU not supported.");
  }

  const adapter = await navigator.gpu.requestAdapter();
  if (!adapter) {
    throw Error("Couldn't request WebGPU adapter.");
  }

  const adapterInfo = await adapter.requestAdapterInfo();
  console.log(adapterInfo.architecture);
  console.log(adapterInfo.vendor);

  // ...
}

```

Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpu-adapterinfo](https://gpuweb.github.io/gpuweb/#gpu-adapterinfo) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUAdapterInfo` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `architecture` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `description` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `device` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `vendor` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUAdapterInfo>

GPUBindGroup
============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUBindGroup` interface of the [WebGPU API](webgpu_api) is based on a [`GPUBindGroupLayout`](gpubindgrouplayout) and defines a set of resources to be bound together in a group and how those resources are used in shader stages.

 A `GPUBindGroup` object instance is created using the [`GPUDevice.createBindGroup()`](gpudevice/createbindgroup) method.



Instance properties
-------------------


 
[`label`](gpubindgroup/label)  Experimental 
  A string providing a label that can be used to identify the object, for example in [`GPUError`](gpuerror) messages or console warnings.

  
Examples
--------


 **Note:** The [WebGPU samples](https://webgpu.github.io/webgpu-samples/) feature many more examples.

 
### Basic example



Our [basic compute demo](https://mdn.github.io/dom-examples/webgpu-compute-demo/) shows an example of creating a bind group layout and then using that as a template when creating a bind group.

 
```
// ...

const bindGroupLayout = device.createBindGroupLayout({
  entries: [
    {
      binding: 0,
      visibility: GPUShaderStage.COMPUTE,
      buffer: {
        type: "storage",
      },
    },
  ],
});

const bindGroup = device.createBindGroup({
  layout: bindGroupLayout,
  entries: [
    {
      binding: 0,
      resource: {
        buffer: output,
      },
    },
  ],
});

// ...

```


Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpubindgroup](https://gpuweb.github.io/gpuweb/#gpubindgroup) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUBindGroup` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `label` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUBindGroup>

GPUBindGroupLayout
==================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUBindGroupLayout` interface of the [WebGPU API](webgpu_api) defines the structure and purpose of related GPU resources such as buffers that will be used in a pipeline, and is used as a template when creating [`GPUBindGroup`](gpubindgroup)s.

 A `GPUBindGroupLayout` object instance is created using the [`GPUDevice.createBindGroupLayout()`](gpudevice/createbindgrouplayout) method.



Instance properties
-------------------


 
[`label`](gpubindgrouplayout/label)  Experimental 
  A string providing a label that can be used to identify the object, for example in [`GPUError`](gpuerror) messages or console warnings.

  
Examples
--------


 **Note:** The [WebGPU samples](https://webgpu.github.io/webgpu-samples/) feature many more examples.

 
### Basic example



Our [basic compute demo](https://mdn.github.io/dom-examples/webgpu-compute-demo/) shows an example of creating a bind group layout and then using that as a template when creating a bind group.

 
```
// ...

const bindGroupLayout = device.createBindGroupLayout({
  entries: [
    {
      binding: 0,
      visibility: GPUShaderStage.COMPUTE,
      buffer: {
        type: "storage",
      },
    },
  ],
});

const bindGroup = device.createBindGroup({
  layout: bindGroupLayout,
  entries: [
    {
      binding: 0,
      resource: {
        buffer: output,
      },
    },
  ],
});

// ...

```


Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpubindgrouplayout](https://gpuweb.github.io/gpuweb/#gpubindgrouplayout) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUBindGroupLayout` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `label` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUBindGroupLayout>

GPUBuffer
=========



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUBuffer` interface of the [WebGPU API](webgpu_api) represents a block of memory that can be used to store raw data to use in GPU operations.

 A `GPUBuffer` object instance is created using the [`GPUDevice.createBuffer()`](gpudevice/createbuffer) method.



Instance properties
-------------------


 
[`label`](gpubuffer/label)  Experimental 
   A string providing a label that can be used to identify the object, for example in [`GPUError`](gpuerror) messages or console warnings. 

  
[`mapState`](gpubuffer/mapstate)  Experimental  Read only 
  An enumerated value representing the mapped state of the `GPUBuffer`.

  
[`size`](gpubuffer/size)  Experimental  Read only 
  A number representing the length of the `GPUBuffer`'s memory allocation, in bytes.

  
[`usage`](gpubuffer/usage)  Experimental  Read only 
  The [bitwise flags](https://developer.mozilla.org/en-US/docs/Glossary/Bitwise_flags) representing the allowed usages of the `GPUBuffer`.

  
Instance methods
----------------


 
[`destroy()`](gpubuffer/destroy)  Experimental 
  Destroys the `GPUBuffer`.

  
[`getMappedRange()`](gpubuffer/getmappedrange)  Experimental 
  Returns an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing the mapped contents of the `GPUBuffer` in the specified range.

  
[`mapAsync()`](gpubuffer/mapasync)  Experimental 
  Maps the specified range of the `GPUBuffer`. Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves when the `GPUBuffer`'s content is ready to be accessed with [`GPUBuffer.getMappedRange()`](gpubuffer/getmappedrange).

  
[`unmap()`](gpubuffer/unmap)  Experimental 
  Unmaps the mapped range of the `GPUBuffer`, making its contents available for use by the GPU again.

  
Examples
--------



In our [basic compute demo](https://mdn.github.io/dom-examples/webgpu-compute-demo/), we create an output buffer to read GPU calculations to, and a staging buffer to be mapped for JavaScript access.

 
```
const output = device.createBuffer({
  size: BUFFER\_SIZE,
  usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY\_SRC,
});

const stagingBuffer = device.createBuffer({
  size: BUFFER\_SIZE,
  usage: GPUBufferUsage.MAP\_READ | GPUBufferUsage.COPY\_DST,
});

```
 Later on, once the `stagingBuffer` contains the results of the GPU computation, a combination of `GPUBuffer` methods are used to read the data back to JavaScript so that it can then be logged to the console:

 * [`GPUBuffer.mapAsync()`](gpubuffer/mapasync) is used to map the `GPUBuffer` for reading.
* [`GPUBuffer.getMappedRange()`](gpubuffer/getmappedrange) is used to return an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing the `GPUBuffer`'s contents.
* [`GPUBuffer.unmap()`](gpubuffer/unmap) is used to unmap the `GPUBuffer` again, once we have read the content into JavaScript as needed.

 
```
// map staging buffer to read results back to JS
await stagingBuffer.mapAsync(
  GPUMapMode.READ,
  0, // Offset
  BUFFER\_SIZE // Length
);

const copyArrayBuffer = stagingBuffer.getMappedRange(0, BUFFER\_SIZE);
const data = copyArrayBuffer.slice();
stagingBuffer.unmap();
console.log(new Float32Array(data));

```


Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpubuffer](https://gpuweb.github.io/gpuweb/#gpubuffer) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUBuffer` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `destroy` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `getMappedRange` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `label` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `mapAsync` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `mapState` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `size` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `unmap` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `usage` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUBuffer>

GPUComputePassEncoder
=====================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUComputePassEncoder` interface of the [WebGPU API](webgpu_api) encodes commands related to controlling the compute shader stage, as issued by a [`GPUComputePipeline`](gpucomputepipeline). It forms part of the overall encoding activity of a [`GPUCommandEncoder`](gpucommandencoder).

 A compute pipeline contains a single compute stage in which a compute shader takes general data, processes it in parallel across a specified number of workgroups, then returns the result in one or more buffers.

 A `GPUComputePassEncoder` object instance is created via the [`GPUCommandEncoder.beginComputePass()`](gpucommandencoder/begincomputepass) property.



Instance properties
-------------------


 
[`label`](gpucomputepassencoder/label)  Experimental 
  A string providing a label that can be used to identify the object, for example in [`GPUError`](gpuerror) messages or console warnings.

  
Instance methods
----------------


 
[`dispatchWorkgroups()`](gpucomputepassencoder/dispatchworkgroups)  Experimental 
  Dispatches a specific grid of workgroups to perform the work being done by the current [`GPUComputePipeline`](gpucomputepipeline).

  
[`dispatchWorkgroupsIndirect()`](gpucomputepassencoder/dispatchworkgroupsindirect)  Experimental 
  Dispatches a grid of workgroups, defined by the parameters of a [`GPUBuffer`](gpubuffer), to perform the work being done by the current [`GPUComputePipeline`](gpucomputepipeline).

  
[`end()`](gpucomputepassencoder/end)  Experimental 
  Completes recording of the current compute pass command sequence.

  
[`insertDebugMarker()`](gpucomputepassencoder/insertdebugmarker)  Experimental 
  Marks a specific point in a series of encoded commands with a label.

  
[`popDebugGroup()`](gpucomputepassencoder/popdebuggroup)  Experimental 
  Ends a debug group, which is begun with a [`pushDebugGroup()`](gpucomputepassencoder/pushdebuggroup) call.

  
[`pushDebugGroup()`](gpucomputepassencoder/pushdebuggroup)  Experimental 
  Begins a debug group, which is marked with a specified label, and will contain all subsequent encoded commands up until a [`popDebugGroup()`](gpucomputepassencoder/popdebuggroup) method is invoked.

  
[`setBindGroup()`](gpucomputepassencoder/setbindgroup)  Experimental 
  Sets the [`GPUBindGroup`](gpubindgroup) to use for subsequent compute commands, for a given index.

  
[`setPipeline()`](gpucomputepassencoder/setpipeline)  Experimental 
  Sets the [`GPUComputePipeline`](gpucomputepipeline) to use for this compute pass.

  
Examples
--------



In our [basic compute demo](https://mdn.github.io/dom-examples/webgpu-compute-demo/), several commands are recorded via a [`GPUCommandEncoder`](gpucommandencoder). Most of these commands originate from the `GPUComputePassEncoder` created via [`GPUCommandEncoder.beginComputePass()`](gpucommandencoder/begincomputepass).

 
```
// ...

// Create GPUCommandEncoder to encode commands to issue to the GPU
const commandEncoder = device.createCommandEncoder();

// Create GPUComputePassEncoder to initiate compute pass
const passEncoder = commandEncoder.beginComputePass();

// Issue commands
passEncoder.setPipeline(computePipeline);
passEncoder.setBindGroup(0, bindGroup);
passEncoder.dispatchWorkgroups(Math.ceil(BUFFER\_SIZE / 64));

// End the compute pass
passEncoder.end();

// Copy output buffer to staging buffer
commandEncoder.copyBufferToBuffer(
  output,
  0, // Source offset
  stagingBuffer,
  0, // Destination offset
  BUFFER\_SIZE
);

// End frame by passing array of command buffers to command queue for execution
device.queue.submit([commandEncoder.finish()]);

// ...

```


Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpucomputepassencoder](https://gpuweb.github.io/gpuweb/#gpucomputepassencoder) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUComputePassEncoder` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `dispatchWorkgroups` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `dispatchWorkgroupsIndirect` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `end` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `insertDebugMarker` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `label` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `popDebugGroup` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `pushDebugGroup` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `setBindGroup` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `setPipeline` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `writeTimestamp` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUComputePassEncoder>

GPUCanvasContext
================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUCanvasContext` interface of the [WebGPU API](webgpu_api) represents the WebGPU rendering context of a [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element, returned via an [`HTMLCanvasElement.getContext()`](htmlcanvaselement/getcontext) call with a `contextType` of `"webgpu"`.



Instance properties
-------------------


 
[`canvas`](gpucanvascontext/canvas)  Experimental  Read only 
  Returns a reference to the canvas that the context was created from.

  
Instance methods
----------------


 
[`configure()`](gpucanvascontext/configure)  Experimental 
  Configures the context to use for rendering with a given [`GPUDevice`](gpudevice) and clears the canvas to transparent black.

  
[`getCurrentTexture()`](gpucanvascontext/getcurrenttexture)  Experimental 
  Returns the next [`GPUTexture`](gputexture) to be composited to the document by the canvas context.

  
[`unconfigure()`](gpucanvascontext/unconfigure)  Experimental 
  Removes any previously-set context configuration, and destroys any textures produced while the canvas context was configured.

  
Examples
--------



```
const canvas = document.querySelector("#gpuCanvas");
const context = canvas.getContext("webgpu");

context.configure({
  device: device,
  format: navigator.gpu.getPreferredCanvasFormat(),
  alphaMode: "premultiplied",
});

```

Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpucanvascontext](https://gpuweb.github.io/gpuweb/#gpucanvascontext) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUCanvasContext` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `canvas` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `configure` | 113["Currently supported on ChromeOS, macOS, and Windows only.", "The `rgba8unorm` format is currently not supported on macOS. See [bug 1298618](https://crbug.com/1298618)."] | 113["Currently supported on EdgeOS, macOS, and Windows only.", "The `rgba8unorm` format is currently not supported on macOS. See [bug 1298618](https://crbug.com/1298618)."] | previewCurrently supported on Linux and Windows only. | No | No["Currently supported on OperaOS, macOS, and Windows only.", "The `rgba8unorm` format is currently not supported on macOS. See [bug 1298618](https://crbug.com/1298618)."] | No | No | No | No | No | No | No |
| `getCurrentTexture` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `unconfigure` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUCanvasContext>

GPUCommandBuffer
================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUCommandBuffer` interface of the [WebGPU API](webgpu_api) represents a pre-recorded list of GPU commands that can be submitted to a [`GPUQueue`](gpuqueue) for execution.

 A `GPUCommandBuffer` is created via the [`GPUCommandEncoder.finish()`](gpucommandencoder/finish) method; the GPU commands recorded within are submitted for execution by passing the `GPUCommandBuffer` into the parameter of a [`GPUQueue.submit()`](gpuqueue/submit) call.

  **Note:** Once a `GPUCommandBuffer` object has been submitted, it cannot be used again.

 

Instance properties
-------------------


 
[`label`](gpucommandbuffer/label)  Experimental 
  A string providing a label that can be used to identify the object, for example in [`GPUError`](gpuerror) messages or console warnings.

  
Examples
--------




```
// ...

const commandBuffer = commandEncoder.finish();
device.queue.submit([commandBuffer]);

```
  **Note:** Study the [WebGPU samples](https://webgpu.github.io/webgpu-samples/) to find complete examples.

 

Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpucommandbuffer](https://gpuweb.github.io/gpuweb/#gpucommandbuffer) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUCommandBuffer` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `label` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUCommandBuffer>

GPUCommandEncoder
=================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUCommandEncoder` interface of the [WebGPU API](webgpu_api) represents a command encoder, used to encode commands to be issued to the GPU.

 A `GPUCommandEncoder` object instance is created via the [`GPUDevice.createCommandEncoder()`](gpudevice/createcommandencoder) property.



Instance properties
-------------------


 
[`label`](gpucommandencoder/label)  Experimental 
  A string providing a label that can be used to identify the object, for example in [`GPUError`](gpuerror) messages or console warnings.

  
Instance methods
----------------


 
[`beginComputePass()`](gpucommandencoder/begincomputepass)  Experimental 
  Starts encoding a compute pass, returning a [`GPUComputePassEncoder`](gpucomputepassencoder) that can be used to control computation.

  
[`beginRenderPass()`](gpucommandencoder/beginrenderpass)  Experimental 
  Starts encoding a render pass, returning a [`GPURenderPassEncoder`](gpurenderpassencoder) that can be used to control rendering.

  
[`clearBuffer()`](gpucommandencoder/clearbuffer)  Experimental 
  Encodes a command that fills a region of a [`GPUBuffer`](gpubuffer) with zeroes.

  
[`copyBufferToBuffer()`](gpucommandencoder/copybuffertobuffer)  Experimental 
  Encodes a command that copies data from one [`GPUBuffer`](gpubuffer) to another.

  
[`copyBufferToTexture()`](gpucommandencoder/copybuffertotexture)  Experimental 
  Encodes a command that copies data from a [`GPUBuffer`](gpubuffer) to a [`GPUTexture`](gputexture).

  
[`copyTextureToBuffer()`](gpucommandencoder/copytexturetobuffer)  Experimental 
  Encodes a command that copies data from a [`GPUTexture`](gputexture) to a [`GPUBuffer`](gpubuffer).

  
[`copyTextureToTexture()`](gpucommandencoder/copytexturetotexture)  Experimental 
  Encodes a command that copies data from one [`GPUTexture`](gputexture) to another.

  
[`finish()`](gpucommandencoder/finish)  Experimental 
  Completes recording of the command sequence encoded on this `GPUCommandEncoder`, returning a corresponding [`GPUCommandBuffer`](gpucommandbuffer).

  
[`insertDebugMarker()`](gpucommandencoder/insertdebugmarker)  Experimental 
  Marks a specific point in a series of encoded commands with a label.

  
[`popDebugGroup()`](gpucommandencoder/popdebuggroup)  Experimental 
  Ends a debug group, which is begun with a [`pushDebugGroup()`](gpucommandencoder/pushdebuggroup) call.

  
[`pushDebugGroup()`](gpucommandencoder/pushdebuggroup)  Experimental 
  Begins a debug group, which is marked with a specified label, and will contain all subsequent encoded commands up until a [`popDebugGroup()`](gpucommandencoder/popdebuggroup) method is invoked.

  
[`resolveQuerySet()`](gpucommandencoder/resolvequeryset)  Experimental 
  Encodes a command that resolves a [`GPUQuerySet`](gpuqueryset), copying the results into a specified [`GPUBuffer`](gpubuffer).

  
[`writeTimestamp()`](gpucommandencoder/writetimestamp)  Experimental 
  Encodes a command that writes a timestamp into a [`GPUQuerySet`](gpuqueryset) once the previous commands recorded into the same queued [`GPUCommandBuffer`](gpucommandbuffer) have been executed by the GPU.

  
Examples
--------



In our [basic render demo](https://mdn.github.io/dom-examples/webgpu-render-demo/), several commands are recorded via a [`GPUCommandEncoder`](gpucommandencoder):

 
```
// ...

// Create GPUCommandEncoder
const commandEncoder = device.createCommandEncoder();

// Create GPURenderPassDescriptor to tell WebGPU which texture to draw into, then initiate render pass

const renderPassDescriptor = {
  colorAttachments: [
    {
      clearValue: clearColor,
      loadOp: "clear",
      storeOp: "store",
      view: context.getCurrentTexture().createView(),
    },
  ],
};

const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);

// Draw a triangle

passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);

// End the render pass

passEncoder.end();

// ...

```
 The commands encoded by the [`GPUCommandEncoder`](gpucommandencoder) are recoded into a [`GPUCommandBuffer`](gpucommandbuffer) using the [`GPUCommandEncoder.finish()`](gpucommandencoder/finish) method. The command buffer is then passed into the queue via a [`submit()`](gpuqueue/submit) call, ready to be processed by the GPU.

 
```
device.queue.submit([commandEncoder.finish()]);

```
  **Note:** Study the [WebGPU samples](https://webgpu.github.io/webgpu-samples/) to find more command encoding examples.

 

Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpucommandencoder](https://gpuweb.github.io/gpuweb/#gpucommandencoder) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUCommandEncoder` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `beginComputePass` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `beginRenderPass` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `clearBuffer` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `copyBufferToBuffer` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `copyBufferToTexture` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `copyTextureToBuffer` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `copyTextureToTexture` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `finish` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `insertDebugMarker` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `label` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `popDebugGroup` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `pushDebugGroup` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `resolveQuerySet` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `writeTimestamp` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUCommandEncoder>

GPUCompilationInfo
==================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUCompilationInfo` interface of the [WebGPU API](webgpu_api) represents an array of [`GPUCompilationMessage`](gpucompilationmessage) objects generated by the GPU shader module compiler to help diagnose problems with shader code.

 `GPUCompilationInfo` is accessed via [`GPUShaderModule.getCompilationInfo()`](gpushadermodule/getcompilationinfo).



Instance properties
-------------------


 
[`messages`](gpucompilationinfo/messages)  Experimental  Read only 
  An array of [`GPUCompilationMessage`](gpucompilationmessage) objects, each one containing the details of an individual shader compilation message. Messages can be informational, warnings, or errors.

  
Examples
--------



In the example below, we have deliberately left a parenthesis out of a function declaration in our shader code:

 
```
const shaders = `
struct VertexOut {
 @builtin(position) position : vec4f,
 @location(0) color : vec4f
}

@vertex
fn vertex\_main(@location(0) position: vec4f,
 @location(1) color: vec4f -> VertexOut
{
 var output : VertexOut;
 output.position = position;
 output.color = color;
 return output;
}

@fragment
fn fragment\_main(fragData: VertexOut) -> @location(0) vec4f
{
 return fragData.color;
}
`;

```
 When we compile the shader module, we use `getCompilationInfo()` to grab some information about the resulting error:

 
```
async function init() {
  // ...

  const shaderModule = device.createShaderModule({
    code: shaders,
  });

  const shaderInfo = await shaderModule.getCompilationInfo();
  const firstMessage = shaderInfo.messages[0];

  console.log(firstMessage.lineNum); // 9
  console.log(firstMessage.message); // "expected ')' for function declaration"
  console.log(firstMessage.type); // "error"
  // ...
}

```


Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpucompilationinfo](https://gpuweb.github.io/gpuweb/#gpucompilationinfo) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUCompilationInfo` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `messages` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUCompilationInfo>

GPUCompilationMessage
=====================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUCompilationMessage` interface of the [WebGPU API](webgpu_api) represents a single informational, warning, or error message generated by the GPU shader module compiler.

 An array of `GPUCompilationMessage` objects is available in the `messages` property of the [`GPUCompilationInfo`](gpucompilationinfo) object accessed via [`GPUShaderModule.getCompilationInfo()`](gpushadermodule/getcompilationinfo).



Instance properties
-------------------


 
[`length`](gpucompilationmessage/length)  Experimental  Read only 
  A number representing the length of the substring that the message corresponds to.

  
[`lineNum`](gpucompilationmessage/linenum)  Experimental  Read only 
  A number representing the line number in the shader code that the message corresponds to.

  
[`linePos`](gpucompilationmessage/linepos)  Experimental  Read only 
  A number representing the position in the code line that the message corresponds to. This could be an exact point, or the start of the relevant substring.

  
[`message`](gpucompilationmessage/message)  Experimental  Read only 
  A string representing human-readable message text.

  
[`offset`](gpucompilationmessage/offset)  Experimental  Read only 
  A number representing the offset from the start of the shader code to the exact point, or the start of the relevant substring, that the message corresponds to.

  
[`type`](gpucompilationmessage/type)  Experimental  Read only 
  An enumerated value representing the type of the message — `"error"`, `"info"`, or `"warning"`.

  
Examples
--------


See the main [`GPUCompilationInfo` page](gpucompilationinfo#examples) for an example.


Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpucompilationmessage](https://gpuweb.github.io/gpuweb/#gpucompilationmessage) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUCompilationMessage` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `length` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `lineNum` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `linePos` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `message` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `offset` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `type` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUCompilationMessage>

GPUComputePipeline
==================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUComputePipeline` interface of the [WebGPU API](webgpu_api) represents a pipeline that controls the compute shader stage and can be used in a [`GPUComputePassEncoder`](gpucomputepassencoder).

 A `GPUComputePipeline` object instance can be created using the [`GPUDevice.createComputePipeline()`](gpudevice/createcomputepipeline) or [`GPUDevice.createComputePipelineAsync()`](gpudevice/createcomputepipelineasync) methods.



Instance properties
-------------------


 
[`label`](gpucomputepipeline/label)  Experimental 
  A string providing a label that can be used to identify the object, for example in [`GPUError`](gpuerror) messages or console warnings.

  
Instance methods
----------------


 
[`getBindGroupLayout()`](gpucomputepipeline/getbindgrouplayout)  Experimental 
  Returns the pipeline's [`GPUBindGroupLayout`](gpubindgrouplayout) object with the given index (i.e. included in the originating [`GPUDevice.createComputePipeline()`](gpudevice/createcomputepipeline) or [`GPUDevice.createComputePipelineAsync()`](gpudevice/createcomputepipelineasync) call's pipeline layout).

  
Examples
--------


 **Note:** The [WebGPU samples](https://webgpu.github.io/webgpu-samples/) feature many more examples.

 
### Basic example



Our [basic compute demo](https://mdn.github.io/dom-examples/webgpu-compute-demo/) shows a process of:

 * Creating a bind group layout with [`GPUDevice.createBindGroupLayout()`](gpudevice/createbindgrouplayout).
* Feeding the `bindGroupLayout` into [`GPUDevice.createPipelineLayout()`](gpudevice/createpipelinelayout) to create a [`GPUPipelineLayout`](gpupipelinelayout).
* Using that value immediately in a `createComputePipeline()` call to create a [`GPUComputePipeline`](gpucomputepipeline).

 
```
// ...

const bindGroupLayout = device.createBindGroupLayout({
  entries: [
    {
      binding: 0,
      visibility: GPUShaderStage.COMPUTE,
      buffer: {
        type: "storage",
      },
    },
  ],
});

const computePipeline = device.createComputePipeline({
  layout: device.createPipelineLayout({
    bindGroupLayouts: [bindGroupLayout],
  }),
  compute: {
    module: shaderModule,
    entryPoint: "main",
  },
});

// ...

```


Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpucomputepipeline](https://gpuweb.github.io/gpuweb/#gpucomputepipeline) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUComputePipeline` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `getBindGroupLayout` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `label` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUComputePipeline>

GPUError
========



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUError` interface of the [WebGPU API](webgpu_api) is the base interface for errors surfaced by [`GPUDevice.popErrorScope`](gpudevice/poperrorscope) and the [`uncapturederror`](gpudevice/uncapturederror_event) event.



Instance properties
-------------------


 
[`message`](gpuerror/message)  Experimental  Read only 
  A string providing a human-readable message that explains why the error ocurred.

  
Examples
--------



For usage examples of error objects based on `GPUError`, see:

 * [`GPUDevice.popErrorScope`](gpudevice/poperrorscope#examples)
* [The `GPUDevice uncapturederror` event](gpudevice/uncapturederror_event#examples)
* [`GPUInternalError`](gpuinternalerror), [`GPUOutOfMemoryError`](gpuoutofmemoryerror), and [`GPUValidationError`](gpuvalidationerror)



Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpuerror](https://gpuweb.github.io/gpuweb/#gpuerror) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUError` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `message` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)
* [WebGPU Error Handling best practices](https://toji.dev/webgpu-best-practices/error-handling)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUError>

GPUInternalError
================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUInternalError` interface of the [WebGPU API](webgpu_api) describes an application error indicating that an operation did not pass the WebGPU API's validation constraints.

 It represents one of the types of errors surfaced by [`GPUDevice.popErrorScope`](gpudevice/poperrorscope) and the [`uncapturederror`](gpudevice/uncapturederror_event) event.

 Internal errors occur when something happens in the WebGPU implementation that wasn't caught by validation and wasn't clearly identifiable as an out-of-memory error. It generally means that an operation your code performed hit a system limit in a way that was difficult to express with WebGPU's [supported limits](gpusupportedlimits). The same operation might succeed on a different device. These can only be raised by pipeline creation, usually if the shader is too complex for the device.


 GPUError GPUInternalError

Constructor
-----------


 
[`GPUInternalError()`](gpuinternalerror/gpuinternalerror)  Experimental 
  Creates a new `GPUInternalError` object instance.

  
Instance properties
-------------------



The `message` property is inherited from its parent, [`GPUError`](gpuerror):

  
[`message`](gpuerror/message)  Experimental  Read only 
  A string providing a human-readable message that explains why the error ocurred.

  

Examples
--------



The following example uses an error scope to capture a suspected validation error, logging it to the console.

 
```
device.pushErrorScope("internal");

const module = device.createShaderModule({
  code: shader, // REALLY complex shader
});

device.popErrorScope().then((error) => {
  if (error) {
    // error is a GPUInternalError object instance
    module = null;
    console.error(`An error occurred while creating shader: ${error.message}`);
  }
});

```


Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpuinternalerror](https://gpuweb.github.io/gpuweb/#gpuinternalerror) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUInternalError` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `GPUInternalError` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)
* [WebGPU Error Handling best practices](https://toji.dev/webgpu-best-practices/error-handling)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUInternalError>

GPUOutOfMemoryError
===================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUOutOfMemoryError` interface of the [WebGPU API](webgpu_api) describes an out-of-memory (oom) error indicating that there was not enough free memory to complete the requested operation.

 It represents one of the types of errors surfaced by [`GPUDevice.popErrorScope`](gpudevice/poperrorscope) and the [`uncapturederror`](gpudevice/uncapturederror_event) event.

 Out-of-memory errors should be relatively rare in a well-behaved app but are less predictable than [`GPUValidationError`](gpuvalidationerror)s. This is because they are dependent on the device your app is running on as well as other apps that are using GPU resources at the time.


 GPUError GPUOutOfMemoryError

Constructor
-----------


 
[`GPUOutOfMemoryError()`](gpuoutofmemoryerror/gpuoutofmemoryerror)  Experimental 
  Creates a new `GPUOutOfMemoryError` object instance.

  
Instance properties
-------------------



The `message` property is inherited from its parent, [`GPUError`](gpuerror):

  
[`message`](gpuerror/message)  Experimental  Read only 
  A string providing a human-readable message that explains why the error ocurred.

  

Examples
--------



The following example uses an error scope to capture an out-of-memory error, logging it to the console.

 
```
device.pushErrorScope("out-of-memory");

let buffer = device.createBuffer({
  size: 100\_000\_000\_000, // 100GB; far too big
  usage: GPUBufferUsage.COPY\_SRC | GPUBufferUsage.MAP\_WRITE,
});

device.popErrorScope().then((error) => {
  if (error) {
    // error is a GPUOutOfMemoryError object instance
    buffer = null;
    console.error(`Out of memory, buffer too large. Error: ${error.message}`);
  }
});

```


Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpuoutofmemoryerror](https://gpuweb.github.io/gpuweb/#gpuoutofmemoryerror) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUOutOfMemoryError` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `GPUOutOfMemoryError` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)
* [WebGPU Error Handling best practices](https://toji.dev/webgpu-best-practices/error-handling)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUOutOfMemoryError>

GPUPipelineError
================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUPipelineError` interface of the [WebGPU API](webgpu_api) describes a pipeline failure. This is the value received when a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) returned by a [`GPUDevice.createComputePipelineAsync()`](gpudevice/createcomputepipelineasync) or [`GPUDevice.createRenderPipelineAsync()`](gpudevice/createrenderpipelineasync) call rejects.


 DOMException GPUPipelineError

Constructor
-----------


 
[`GPUPipelineError()`](gpupipelineerror/gpupipelineerror)  Experimental 
  Creates a new `GPUPipelineError` object instance.

  
Instance properties
-------------------



*Inherits properties from its parent, [`DOMException`](domexception).*

  
[`reason`](gpupipelineerror/reason)  Experimental  Read only 
  An enumerated value that defines the reason the pipeline creation failed in a machine-readable way.

  

Examples
--------



In the following snippet we are attempting to create a [`GPUComputePipeline`](gpucomputepipeline) using [`GPUDevice.createComputePipelineAsync()`](gpudevice/createcomputepipelineasync). However, we have misspelt our compute pipeline `entryPoint` as `"maijn"` (it should be `"main"`), therefore pipeline creation fails, and our `catch` block prints the resulting reason and error message to the console.

 
```
// ...

let computePipeline;

try {
  computePipeline = await device.createComputePipelineAsync({
    layout: device.createPipelineLayout({
      bindGroupLayouts: [bindGroupLayout],
    }),
    compute: {
      module: shaderModule,
      entryPoint: "maijn",
    },
  });
} catch (error) {
  // error is a GPUPipelineError object instance
  console.error(error.reason);
  console.error(`Pipeline creation failed: ${error.message}`);
}

// ...

```
 In this case, the given `reason` is `"Validation"`, and the `message` is `"Entry point "maijn" doesn't exist in the shader module [ShaderModule]."`



Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpupipelineerror](https://gpuweb.github.io/gpuweb/#gpupipelineerror) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUPipelineError` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `GPUPipelineError` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `reason` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)
* [WebGPU Error Handling best practices](https://toji.dev/webgpu-best-practices/error-handling)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUPipelineError>

GPUPipelineLayout
=================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUPipelineLayout` interface of the [WebGPU API](webgpu_api) defines the [`GPUBindGroupLayout`](gpubindgrouplayout)s used by a pipeline. [`GPUBindGroup`](gpubindgroup)s used with the pipeline during command encoding must have compatible [`GPUBindGroupLayout`](gpubindgrouplayout)s.

 A `GPUPipelineLayout` object instance is created using the [`GPUDevice.createPipelineLayout()`](gpudevice/createpipelinelayout) method.



Instance properties
-------------------


 
[`label`](gpupipelinelayout/label)  Experimental 
  A string providing a label that can be used to identify the object, for example in [`GPUError`](gpuerror) messages or console warnings.

  
Examples
--------


 **Note:** The [WebGPU samples](https://webgpu.github.io/webgpu-samples/) feature many more examples.

 
### Basic pipeline layout example



The following snippet:

 * Creates a [`GPUBindGroupLayout`](gpubindgrouplayout) that describes a binding with a buffer, a texture, and a sampler.
* Creates a [`GPUPipelineLayout`](gpupipelinelayout) based on the [`GPUBindGroupLayout`](gpubindgrouplayout).

 
```
// ...

const bindGroupLayout = device.createBindGroupLayout({
  entries: [
    {
      binding: 0,
      visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
      buffer: {},
    },
    {
      binding: 1,
      visibility: GPUShaderStage.FRAGMENT,
      texture: {},
    },
    {
      binding: 2,
      visibility: GPUShaderStage.FRAGMENT,
      sampler: {},
    },
  ],
});

const pipelineLayout = device.createPipelineLayout({
  bindGroupLayouts: [bindGroupLayout],
});

// ...

```


Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpupipelinelayout](https://gpuweb.github.io/gpuweb/#gpupipelinelayout) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUPipelineLayout` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `label` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUPipelineLayout>

GPUQueue
========



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUQueue` interface of the [WebGPU API](webgpu_api) controls execution of encoded commands on the GPU.

 A device's primary queue is accessed via the [`GPUDevice.queue`](gpudevice/queue) property.



Instance properties
-------------------


 
[`label`](gpuqueue/label)  Experimental 
  A string providing a label that can be used to identify the object, for example in [`GPUError`](gpuerror) messages or console warnings.

  
Instance methods
----------------


 
[`copyExternalImageToTexture()`](gpuqueue/copyexternalimagetotexture)  Experimental 
  Copies a snapshot taken from a source image, video, or canvas into a given [`GPUTexture`](gputexture).

  
[`onSubmittedWorkDone()`](gpuqueue/onsubmittedworkdone)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves when all the work submitted to the GPU via this `GPUQueue` at the point the method is called has been processed.

  
[`submit()`](gpuqueue/submit)  Experimental 
  Schedules the execution of command buffers represented by one or more [`GPUCommandBuffer`](gpucommandbuffer) objects by the GPU.

  
[`writeBuffer()`](gpuqueue/writebuffer)  Experimental 
  Writes a provided data source into a given [`GPUBuffer`](gpubuffer).

  
[`writeTexture()`](gpuqueue/writetexture)  Experimental 
  Writes a provided data source into a given [`GPUTexture`](gputexture).

  
Examples
--------



In our [basic render demo](https://mdn.github.io/dom-examples/webgpu-render-demo/), we define some vertex data in a [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) that we'll use to draw a triangle:

 
```
const vertices = new Float32Array([
  0.0, 0.6, 0, 1, 1, 0, 0, 1, -0.5, -0.6, 0, 1, 0, 1, 0, 1, 0.5, -0.6, 0, 1, 0,
  0, 1, 1,
]);

```
 To use this data in a render pipeline, we need to put it into a [`GPUBuffer`](gpubuffer). First we'll create the buffer:

 
```
const vertexBuffer = device.createBuffer({
  size: vertices.byteLength, // make it big enough to store vertices in
  usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY\_DST,
});

```
 To get the data into the buffer we can use the [`writeBuffer()`](gpuqueue/writebuffer) function, which lets the user agent determine most efficient way to copy the data over:

 
```
device.queue.writeBuffer(vertexBuffer, 0, vertices, 0, vertices.length);

```
 Later on, a set of commands is encoded into a [`GPUCommandBuffer`](gpucommandbuffer) using the [`GPUCommandEncoder.finish()`](gpucommandencoder/finish) method. The command buffer is then passed into the queue via a [`submit()`](gpuqueue/submit) call, ready to be processed by the GPU.

 
```
device.queue.submit([commandEncoder.finish()]);

```
  **Note:** Study the [WebGPU samples](https://webgpu.github.io/webgpu-samples/) to find more queue examples.

 

Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpu-queue](https://gpuweb.github.io/gpuweb/#gpu-queue) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUQueue` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `copyExternalImageToTexture` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `label` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `onSubmittedWorkDone` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `submit` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `writeBuffer` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `writeTexture` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUQueue>

GPUDevice
=========



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUDevice` interface of the [WebGPU API](webgpu_api) represents a logical GPU device. This is the main interface through which the majority of WebGPU functionality is accessed.

 A `GPUDevice` object is requested using the [`GPUAdapter.requestDevice()`](gpuadapter/requestdevice) method.


 EventTarget GPUDevice

Instance properties
-------------------



*Inherits properties from its parent, [`EventTarget`](eventtarget).*

  
[`features`](gpudevice/features)  Experimental  Read only 
  A [`GPUSupportedFeatures`](gpusupportedfeatures) object that describes additional functionality supported by the device.

  
[`label`](gpudevice/label)  Experimental 
  A string providing a label that can be used to identify the object, for example in [`GPUError`](gpuerror) messages or console warnings.

  
[`limits`](gpudevice/limits)  Experimental  Read only 
  A [`GPUSupportedLimits`](gpusupportedlimits) object that describes the limits supported by the device.

  
[`lost`](gpudevice/lost)  Experimental  Read only 
  Contains a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that remains pending throughout the device's lifetime and resolves with a [`GPUDeviceLostInfo`](gpudevicelostinfo) object when the device is lost.

  
[`queue`](gpudevice/queue)  Experimental  Read only 
  Returns the primary [`GPUQueue`](gpuqueue) for the device.

  

Instance methods
----------------



*Inherits methods from its parent, [`EventTarget`](eventtarget).*

  
[`createBindGroup()`](gpudevice/createbindgroup)  Experimental 
  Creates a [`GPUBindGroup`](gpubindgroup) based on a [`GPUBindGroupLayout`](gpubindgrouplayout) that defines a set of resources to be bound together in a group and how those resources are used in shader stages.

  
[`createBindGroupLayout()`](gpudevice/createbindgrouplayout)  Experimental 
  Creates a [`GPUBindGroupLayout`](gpubindgrouplayout) that defines the structure and purpose of related GPU resources such as buffers that will be used in a pipeline, and is used as a template when creating [`GPUBindGroup`](gpubindgroup)s.

  
[`createBuffer()`](gpudevice/createbuffer)  Experimental 
  Creates a [`GPUBuffer`](gpubuffer) in which to store raw data to use in GPU operations.

  
[`createCommandEncoder()`](gpudevice/createcommandencoder)  Experimental 
  Creates a [`GPUCommandEncoder`](gpucommandencoder), which is used to encode commands to be issued to the GPU.

  
[`createComputePipeline()`](gpudevice/createcomputepipeline)  Experimental 
  Creates a [`GPUComputePipeline`](gpucomputepipeline) that can control the compute shader stage and be used in a [`GPUComputePassEncoder`](gpucomputepassencoder).

  
[`createComputePipelineAsync()`](gpudevice/createcomputepipelineasync)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that fulfills with a [`GPUComputePipeline`](gpucomputepipeline), which can control the compute shader stage and be used in a [`GPUComputePassEncoder`](gpucomputepassencoder), once the pipeline can be used without any stalling.

  
[`createPipelineLayout()`](gpudevice/createpipelinelayout)  Experimental 
  Creates a [`GPUPipelineLayout`](gpupipelinelayout) that defines the [`GPUBindGroupLayout`](gpubindgrouplayout)s used by a pipeline. [`GPUBindGroup`](gpubindgroup)s used with the pipeline during command encoding must have compatible [`GPUBindGroupLayout`](gpubindgrouplayout)s.

  
[`createQuerySet()`](gpudevice/createqueryset)  Experimental 
  Creates a [`GPUQuerySet`](gpuqueryset) that can be used to record the results of queries on passes, such as occlusion or timestamp queries.

  
[`createRenderBundleEncoder()`](gpudevice/createrenderbundleencoder)  Experimental 
  Creates a [`GPURenderBundleEncoder`](gpurenderbundleencoder) that can be used to pre-record bundles of commands. These can be reused in [`GPURenderPassEncoder`](gpurenderpassencoder)s via the [`executeBundles()`](gpurenderpassencoder/executebundles) method, as many times as required.

  
[`createRenderPipeline()`](gpudevice/createrenderpipeline)  Experimental 
  Creates a [`GPURenderPipeline`](gpurenderpipeline) that can control the vertex and fragment shader stages and be used in a [`GPURenderPassEncoder`](gpurenderpassencoder) or [`GPURenderBundleEncoder`](gpurenderbundleencoder).

  
[`createRenderPipelineAsync()`](gpudevice/createrenderpipelineasync)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that fulfills with a [`GPURenderPipeline`](gpurenderpipeline), which can control the vertex and fragment shader stages and be used in a [`GPURenderPassEncoder`](gpurenderpassencoder) or [`GPURenderBundleEncoder`](gpurenderbundleencoder), once the pipeline can be used without any stalling.

  
[`createSampler()`](gpudevice/createsampler)  Experimental 
  Creates a [`GPUSampler`](gpusampler), which controls how shaders transform and filter texture resource data.

  
[`createShaderModule()`](gpudevice/createshadermodule)  Experimental 
  Creates a [`GPUShaderModule`](gpushadermodule) from a string of WGSL source code.

  
[`createTexture()`](gpudevice/createtexture)  Experimental 
  Creates a [`GPUTexture`](gputexture) in which to store texture data to use in GPU rendering operations.

  
[`destroy()`](gpudevice/destroy)  Experimental 
  Destroys the device, preventing further operations on it.

  
[`importExternalTexture()`](gpudevice/importexternaltexture)  Experimental 
  Takes an [`HTMLVideoElement`](htmlvideoelement) as an input and returns a [`GPUExternalTexture`](gpuexternaltexture) wrapper object containing a snapshot of the video that can be used in GPU rendering operations.

  
[`popErrorScope()`](gpudevice/poperrorscope)  Experimental 
  Pops an existing GPU error scope from the error scope stack and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to an object ([`GPUInternalError`](gpuinternalerror), [`GPUOutOfMemoryError`](gpuoutofmemoryerror), or [`GPUValidationError`](gpuvalidationerror)) describing the first error captured in the scope, or `null` if no error occurred.

  
[`pushErrorScope()`](gpudevice/pusherrorscope)  Experimental 
  Pushes a new GPU error scope onto the device's error scope stack, allowing you to capture errors of a particular type.

  

Events
------


 
[`uncapturederror`](gpudevice/uncapturederror_event)  Experimental 
  Fired when an error is thrown that has not been observed by a GPU error scope, to provide a way to report unexpected errors. Known error cases should be handled using [`pushErrorScope()`](gpudevice/pusherrorscope) and [`popErrorScope()`](gpudevice/poperrorscope).

  
Examples
--------




```
async function init() {
  if (!navigator.gpu) {
    throw Error("WebGPU not supported.");
  }

  const adapter = await navigator.gpu.requestAdapter();
  if (!adapter) {
    throw Error("Couldn't request WebGPU adapter.");
  }

  const device = await adapter.requestDevice();

  const shaderModule = device.createShaderModule({
    code: shaders,
  });

  //...
}

```
 See the individual member pages listed above and the following demo sites for a lot more examples of `GPUDevice` usage:

 * [Basic compute demo](https://mdn.github.io/dom-examples/webgpu-compute-demo/)
* [Basic render demo](https://mdn.github.io/dom-examples/webgpu-render-demo/)
* [WebGPU samples](https://webgpu.github.io/webgpu-samples/)



Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpudevice](https://gpuweb.github.io/gpuweb/#gpudevice) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUDevice` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `createBindGroup` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `createBindGroupLayout` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `createBuffer` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `createCommandEncoder` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `createComputePipeline` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `createComputePipelineAsync` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `createPipelineLayout` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `createQuerySet` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `createRenderBundleEncoder` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `createRenderPipeline` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `createRenderPipelineAsync` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `createSampler` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `createShaderModule` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `createTexture` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `destroy` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `features` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `importExternalTexture` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `label` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `limits` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `lost` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `popErrorScope` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `pushErrorScope` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `queue` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `uncapturederror_event` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUDevice>

GPUDeviceLostInfo
=================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUDeviceLostInfo` interface of the [WebGPU API](webgpu_api) represents the object returned when the [`GPUDevice.lost`](gpudevice/lost) [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) resolves. This provides information as to why a device has been lost.

 See the [`GPUDevice.lost`](gpudevice/lost) page for more information about "lost" state.



Instance properties
-------------------


 
[`message`](gpudevicelostinfo/message)  Experimental  Read only 
  A string providing a human-readable message that explains why the device was lost.

  
[`reason`](gpudevicelostinfo/reason)  Experimental  Read only 
  An enumerated value that defines the reason the device was lost in a machine-readable way.

  
Examples
--------



```
async function init() {
  if (!navigator.gpu) {
    throw Error("WebGPU not supported.");
  }
  const adapter = await navigator.gpu.requestAdapter();
  if (!adapter) {
    throw Error("Couldn't request WebGPU adapter.");
  }

  // Create a GPUDevice
  let device = await adapter.requestDevice(descriptor);

  // Use lost to handle lost devices
  device.lost.then((info) => {
    console.error(`WebGPU device was lost: ${info.message}`);
    device = null;
    if (info.reason !== "destroyed") {
      init();
    }
  });
  // ...
}

```

Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpudevicelostinfo](https://gpuweb.github.io/gpuweb/#gpudevicelostinfo) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUDeviceLostInfo` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `message` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `reason` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUDeviceLostInfo>

GPUExternalTexture
==================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUExternalTexture` interface of the [WebGPU API](webgpu_api) represents a wrapper object containing an [`HTMLVideoElement`](htmlvideoelement) snapshot that can be used as a texture in GPU rendering operations.

 A `GPUExternalTexture` object instance is created using [`GPUDevice.importExternalTexture()`](gpudevice/importexternaltexture).



Instance properties
-------------------


 
[`label`](gpuexternaltexture/label)  Experimental 
  A string providing a label that can be used to identify the object, for example in [`GPUError`](gpuerror) messages or console warnings.

  
Examples
--------



In the WebGPU samples [Video Uploading sample](https://webgpu.github.io/webgpu-samples/samples/videoUploading), a `GPUExternalTexture` object (created via a [`GPUDevice.importExternalTexture()`](gpudevice/importexternaltexture) call) is used as the value of a bind group entry `resource`, specified when creating a [`GPUBindGroup`](gpubindgroup) via a [`GPUDevice.createBindGroup()`](gpudevice/createbindgroup) call:

 
```
//...
const uniformBindGroup = device.createBindGroup({
  layout: pipeline.getBindGroupLayout(0),
  entries: [
    {
      binding: 1,
      resource: sampler,
    },
    {
      binding: 2,
      resource: device.importExternalTexture({
        source: video,
      }),
    },
  ],
});
//...

```


Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpuexternaltexture](https://gpuweb.github.io/gpuweb/#gpuexternaltexture) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUExternalTexture` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `label` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUExternalTexture>

GPUQuerySet
===========



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUQuerySet` interface of the [WebGPU API](webgpu_api) is used to record the results of queries on passes, such as occlusion or timestamp queries.

 * Occlusion queries are available on render passes to query whether any fragment samples pass all the per-fragment tests for a set of drawing commands (including scissor, sample mask, alpha to coverage, stencil, and depth tests). To run an occlusion query, an appropriate `GPUQuerySet` must be provided as the value of the `occlusionQuerySet` descriptor property when invoking [`GPUCommandEncoder.beginRenderPass()`](gpucommandencoder/beginrenderpass) to run a render pass.
* Timestamp queries allow applications to write timestamps to a `GPUQuerySet`. To run a timestamp query, appropriate `GPUQuerySet`s must be provided inside the value of the `timestampWrites` descriptor property when invoking [`GPUCommandEncoder.beginRenderPass()`](gpucommandencoder/beginrenderpass) to run a render pass, or [`GPUCommandEncoder.beginComputePass()`](gpucommandencoder/begincomputepass) to run a compute pass. Alternatively, you can run a single timestamp query at any time by invoking [`GPUCommandEncoder.writeTimeStamp()`](gpucommandencoder/writetimestamp) with an appropriate `GPUQuerySet` as a parameter.

  **Note:** To use timestamp queries, the `timestamp-query` [feature](gpusupportedfeatures) must be enabled in the [`GPUDevice`](gpudevice).

  A `GPUQuerySet` object instance is created using the [`GPUDevice.createQuerySet()`](gpudevice/createqueryset) method.



Instance properties
-------------------


 
[`count`](gpuqueryset/count)  Experimental  Read only 
  A number specifying the number of queries managed by the `GPUQuerySet`.

  
[`label`](gpuqueryset/label)  Experimental 
  A string providing a label that can be used to identify the object, for example in [`GPUError`](gpuerror) messages or console warnings.

  
[`type`](gpuqueryset/type)  Experimental  Read only 
  An enumerated value specifying the type of queries managed by the `GPUQuerySet`.

  
Instance methods
----------------


 
[`destroy()`](gpuqueryset/destroy)  Experimental 
  Destroys the `GPUQuerySet`.

  
Examples
--------



The following snippet creates a `GPUQuerySet` that holds 32 occlusion query results, and then returns the `type` and `count`:

 
```
const querySet = device.createQuerySet({
  type: "occlusion",
  count: 32,
});

console.log(querySet.count); // 32
console.log(querySet.type); // "occlusion"

```


Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpuqueryset](https://gpuweb.github.io/gpuweb/#gpuqueryset) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUQuerySet` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `count` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `destroy` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `label` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `type` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUQuerySet>

GPURenderBundleEncoder
======================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPURenderBundleEncoder` interface of the [WebGPU API](webgpu_api) is used to pre-record bundles of commands.

 The command bundles are encoded by calling the methods of `GPURenderBundleEncoder`; once the desired commands have been encoded, they are recorded into a [`GPURenderBundle`](gpurenderbundle) object instance using the [`GPURenderBundleEncoder.finish()`](gpurenderbundleencoder/finish) method. These render bundles can then be reused across multiple render passes by passing the `GPURenderBundle` objects into [`GPURenderPassEncoder.executeBundles()`](gpurenderpassencoder/executebundles) calls.

 In effect, this is like a partial render pass — `GPURenderBundleEncoder`s have all the same functionality available as [`GPURenderPassEncoder`](gpurenderpassencoder)s, except that they can't begin and end occlusion queries, and can't set the scissor rect, viewport, blend constant, and stencil reference. The `GPURenderBundle` will inherit all these values from the [`GPURenderPassEncoder`](gpurenderpassencoder) that executes it.

  **Note:** Currently set vertex buffers, index buffers, bind groups, and pipeline are all cleared prior to executing a render bundle, and once the render bundle has finished executing.

  Reusing pre-recoded commands can significantly improve app performance in situations where JavaScript draw call overhead is a bottleneck. Render bundles are most effective in situations where a batch of objects will be drawn the same way across multiple views or frames, with the only differences being the buffer content being used (such as updated matrix uniforms). A good example is VR rendering. Recording the rendering as a render bundle and then tweaking the view matrix and replaying it for each eye is a more efficient way to issue draw calls for both renderings of the scene.

 A `GPURenderBundleEncoder` object instance is created via the [`GPUDevice.createRenderBundleEncoder()`](gpudevice/createrenderbundleencoder) property.

  **Note:** The methods of `GPURenderBundleEncoder` are functionally identical to their equivalents available on [`GPURenderPassEncoder`](gpurenderpassencoder), except for [`GPURenderBundleEncoder.finish()`](gpurenderbundleencoder/finish), which is similar in purpose to [`GPUCommandEncoder.finish()`](gpucommandencoder/finish).

 

Instance properties
-------------------


 
[`label`](gpurenderbundleencoder/label)  Experimental 
  A string providing a label that can be used to identify the object, for example in [`GPUError`](gpuerror) messages or console warnings.

  
Instance methods
----------------


 
[`draw()`](gpurenderbundleencoder/draw)  Experimental 
  Draw primitives based on the vertex buffers provided by [`setVertexBuffer()`](gpurenderbundleencoder/setvertexbuffer).

  
[`drawIndexed()`](gpurenderbundleencoder/drawindexed)  Experimental 
  Draw indexed primitives based on the vertex and index buffers provided by [`setVertexBuffer()`](gpurenderbundleencoder/setvertexbuffer) and [`setIndexBuffer()`](gpurenderbundleencoder/setindexbuffer)

  
[`drawIndirect()`](gpurenderbundleencoder/drawindirect)  Experimental 
  Draw primitives using parameters read from a [`GPUBuffer`](gpubuffer).

  
[`drawIndexedIndirect()`](gpurenderbundleencoder/drawindexedindirect)  Experimental 
  Draw indexed primitives using parameters read from a [`GPUBuffer`](gpubuffer).

  
[`finish()`](gpurenderbundleencoder/finish)  Experimental 
  Completes recording of the current render pass command sequence.

  
[`insertDebugMarker()`](gpurenderbundleencoder/insertdebugmarker)  Experimental 
  Marks a specific point in a series of encoded commands with a label.

  
[`popDebugGroup()`](gpurenderbundleencoder/popdebuggroup)  Experimental 
  Ends a debug group, which is begun with a [`pushDebugGroup()`](gpurenderbundleencoder/pushdebuggroup) call.

  
[`pushDebugGroup()`](gpurenderbundleencoder/pushdebuggroup)  Experimental 
  Begins a debug group, which is marked with a specified label, and will contain all subsequent encoded commands up until a [`popDebugGroup()`](gpurenderbundleencoder/popdebuggroup) method is invoked.

  
[`setBindGroup()`](gpurenderbundleencoder/setbindgroup)  Experimental 
  Sets the [`GPUBindGroup`](gpubindgroup) to use for subsequent render bundle commands, for a given index.

  
[`setIndexBuffer()`](gpurenderbundleencoder/setindexbuffer)  Experimental 
  Sets the current [`GPUBuffer`](gpubuffer) that will provide index data for subsequent drawing commands.

  
[`setPipeline()`](gpurenderbundleencoder/setpipeline)  Experimental 
  Sets the [`GPURenderPipeline`](gpurenderpipeline) to use for this render bundle.

  
[`setVertexBuffer()`](gpurenderbundleencoder/setvertexbuffer)  Experimental 
  Sets the current [`GPUBuffer`](gpubuffer) that will provide vertex data for subsequent drawing commands.

  
Examples
--------



In the WebGPU Samples [Animometer example](https://webgpu.github.io/webgpu-samples/samples/animometer), a lot of like operations are done on many different objects simultaneously. A bundle of commands is encoded using the following function:

 
```
function recordRenderPass(
  passEncoder: GPURenderBundleEncoder | GPURenderPassEncoder
) {
  if (settings.dynamicOffsets) {
    passEncoder.setPipeline(dynamicPipeline);
  } else {
    passEncoder.setPipeline(pipeline);
  }
  passEncoder.setVertexBuffer(0, vertexBuffer);
  passEncoder.setBindGroup(0, timeBindGroup);
  const dynamicOffsets = [0];
  for (let i = 0; i < numTriangles; ++i) {
    if (settings.dynamicOffsets) {
      dynamicOffsets[0] = i \* alignedUniformBytes;
      passEncoder.setBindGroup(1, dynamicBindGroup, dynamicOffsets);
    } else {
      passEncoder.setBindGroup(1, bindGroups[i]);
    }
    passEncoder.draw(3, 1, 0, 0);
  }
}

```
 Later on, a `GPURenderBundleEncoder` is created, the function is invoked, and the command bundle is recorded into a [`GPURenderBundle`](gpurenderbundle) using [`GPURenderBundleEncoder.finish()`](gpurenderbundleencoder/finish):

 
```
const renderBundleEncoder = device.createRenderBundleEncoder({
  colorFormats: [presentationFormat],
});
recordRenderPass(renderBundleEncoder);
const renderBundle = renderBundleEncoder.finish();

```
 [`GPURenderPassEncoder.executeBundles()`](gpurenderpassencoder/executebundles) is then used to reuse the work across multiple render passes to improve performance. Study the example code listing for the full context.

 
```
// ...

return function doDraw(timestamp) {
  if (startTime === undefined) {
    startTime = timestamp;
  }
  uniformTime[0] = (timestamp - startTime) / 1000;
  device.queue.writeBuffer(uniformBuffer, timeOffset, uniformTime.buffer);

  renderPassDescriptor.colorAttachments[0].view = context
    .getCurrentTexture()
    .createView();

  const commandEncoder = device.createCommandEncoder();
  const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);

  if (settings.renderBundles) {
    passEncoder.executeBundles([renderBundle]);
  } else {
    recordRenderPass(passEncoder);
  }

  passEncoder.end();
  device.queue.submit([commandEncoder.finish()]);
};

// ...

```


Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpurenderbundle](https://gpuweb.github.io/gpuweb/#gpurenderbundle) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPURenderBundleEncoder` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `draw` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `drawIndexed` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `drawIndexedIndirect` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `drawIndirect` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `finish` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `insertDebugMarker` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `label` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `popDebugGroup` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `pushDebugGroup` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `setBindGroup` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `setIndexBuffer` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `setPipeline` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `setVertexBuffer` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPURenderBundleEncoder>

GPURenderPassEncoder
====================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPURenderPassEncoder` interface of the [WebGPU API](webgpu_api) encodes commands related to controlling the vertex and fragment shader stages, as issued by a [`GPURenderPipeline`](gpurenderpipeline). It forms part of the overall encoding activity of a [`GPUCommandEncoder`](gpucommandencoder).

 A render pipeline renders graphics to [`GPUTexture`](gputexture) attachments, typically intended for display in a [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element, but it could also render to textures used for other purposes that never appear onscreen. It has two main stages:

 * A vertex stage, in which a vertex shader takes positioning data fed into the GPU and uses it to position a series of vertices in 3D space by applying specified effects like rotation, translation, or perspective. The vertices are then assembled into primitives such as triangles (the basic building block of rendered graphics) and rasterized by the GPU to figure out what pixels each one should cover on the drawing canvas.
* A fragment stage, in which a fragment shader computes the color for each pixel covered by the primitives produced by the vertex shader. These computations frequently use inputs such as images (in the form of textures) that provide surface details and the position and color of virtual lights.

 A `GPUComputePassEncoder` object instance is created via the [`GPUCommandEncoder.beginComputePass()`](gpucommandencoder/begincomputepass) property.



Instance properties
-------------------


 
[`label`](gpurenderpassencoder/label)  Experimental 
  A string providing a label that can be used to identify the object, for example in [`GPUError`](gpuerror) messages or console warnings.

  
Instance methods
----------------


 
[`beginOcclusionQuery()`](gpurenderpassencoder/beginocclusionquery)  Experimental 
  Begins an occlusion query at the specified index of the relevant [`GPUQuerySet`](gpuqueryset) (provided as the value of the `occlusionQuerySet` descriptor property when invoking [`GPUCommandEncoder.beginRenderPass()`](gpucommandencoder/beginrenderpass) to run the render pass).

  
[`draw()`](gpurenderpassencoder/draw)  Experimental 
  Draw primitives based on the vertex buffers provided by [`setVertexBuffer()`](gpurenderpassencoder/setvertexbuffer).

  
[`drawIndexed()`](gpurenderpassencoder/drawindexed)  Experimental 
  Draw indexed primitives based on the vertex and index buffers provided by [`setVertexBuffer()`](gpurenderpassencoder/setvertexbuffer) and [`setIndexBuffer()`](gpurenderpassencoder/setindexbuffer)

  
[`drawIndirect()`](gpurenderpassencoder/drawindirect)  Experimental 
  Draw primitives using parameters read from a [`GPUBuffer`](gpubuffer).

  
[`drawIndexedIndirect()`](gpurenderpassencoder/drawindexedindirect)  Experimental 
  Draw indexed primitives using parameters read from a [`GPUBuffer`](gpubuffer).

  
[`end()`](gpurenderpassencoder/end)  Experimental 
  Completes recording of the current render pass command sequence.

  
[`endOcclusionQuery()`](gpurenderpassencoder/endocclusionquery)  Experimental 
  Ends an active occlusion query previously started with [`beginOcclusionQuery()`](gpurenderpassencoder/beginocclusionquery).

  
[`executeBundles()`](gpurenderpassencoder/executebundles)  Experimental 
  Executes commands previously recorded into the referenced [`GPURenderBundle`](gpurenderbundle)s, as part of this render pass.

  
[`insertDebugMarker()`](gpurenderpassencoder/insertdebugmarker)  Experimental 
  Marks a specific point in a series of encoded commands with a label.

  
[`popDebugGroup()`](gpurenderpassencoder/popdebuggroup)  Experimental 
  Ends a debug group, which is begun with a [`pushDebugGroup()`](gpurenderpassencoder/pushdebuggroup) call.

  
[`pushDebugGroup()`](gpurenderpassencoder/pushdebuggroup)  Experimental 
  Begins a debug group, which is marked with a specified label, and will contain all subsequent encoded commands up until a [`popDebugGroup()`](gpurenderpassencoder/popdebuggroup) method is invoked.

  
[`setBindGroup()`](gpurenderpassencoder/setbindgroup)  Experimental 
  Sets the [`GPUBindGroup`](gpubindgroup) to use for subsequent render commands, for a given index.

  
[`setBlendConstant()`](gpurenderpassencoder/setblendconstant)  Experimental 
  Sets the constant blend color and alpha values used with `"constant"` and `"one-minus-constant"` blend factors (as set in the descriptor of the [`GPUDevice.createRenderPipeline()`](gpudevice/createrenderpipeline) method, in the `blend` property).

  
[`setIndexBuffer()`](gpurenderpassencoder/setindexbuffer)  Experimental 
  Sets the current [`GPUBuffer`](gpubuffer) that will provide index data for subsequent drawing commands.

  
[`setPipeline()`](gpurenderpassencoder/setpipeline)  Experimental 
  Sets the [`GPURenderPipeline`](gpurenderpipeline) to use for this render pass.

  
[`setScissorRect()`](gpurenderpassencoder/setscissorrect)  Experimental 
  Sets the scissor rectangle used during the rasterization stage. After transformation into viewport coordinates any fragments that fall outside the scissor rectangle will be discarded.

  
[`setStencilReference()`](gpurenderpassencoder/setstencilreference)  Experimental 
  Sets the stencil reference value using during stencil tests with the `"replace"` stencil operation (as set in the descriptor of the [`GPUDevice.createRenderPipeline()`](gpudevice/createrenderpipeline) method, in the properties defining the various stencil operations).

  
[`setVertexBuffer()`](gpurenderpassencoder/setvertexbuffer)  Experimental 
  Sets the current [`GPUBuffer`](gpubuffer) that will provide vertex data for subsequent drawing commands.

  
[`setViewport()`](gpurenderpassencoder/setviewport)  Experimental 
  Sets the viewport used during the rasterization stage to linearly map from normalized device coordinates to viewport coordinates.

  
Examples
--------



In our [basic render demo](https://mdn.github.io/dom-examples/webgpu-render-demo/), several commands are recorded via a [`GPUCommandEncoder`](gpucommandencoder). Most of these commands originate from the `GPURenderPassEncoder` created via [`GPUCommandEncoder.beginRenderPass()`](gpucommandencoder/beginrenderpass).

 
```
// ...

const renderPipeline = device.createRenderPipeline(pipelineDescriptor);

// Create GPUCommandEncoder to issue commands to the GPU
// Note: render pass descriptor, command encoder, etc. are destroyed after use, fresh one needed for each frame.
const commandEncoder = device.createCommandEncoder();

// Create GPURenderPassDescriptor to tell WebGPU which texture to draw into, then initiate render pass
const renderPassDescriptor = {
  colorAttachments: [
    {
      clearValue: clearColor,
      loadOp: "clear",
      storeOp: "store",
      view: context.getCurrentTexture().createView(),
    },
  ],
};

const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);

// Draw the triangle
passEncoder.setPipeline(renderPipeline);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.draw(3);

// End the render pass
passEncoder.end();

// End frame by passing array of command buffers to command queue for execution
device.queue.submit([commandEncoder.finish()]);

// ...

```


Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpurenderpassencoder](https://gpuweb.github.io/gpuweb/#gpurenderpassencoder) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPURenderPassEncoder` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `beginOcclusionQuery` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `draw` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `drawIndexed` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `drawIndexedIndirect` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `drawIndirect` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `end` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `endOcclusionQuery` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `executeBundles` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `insertDebugMarker` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `label` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `popDebugGroup` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `pushDebugGroup` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `setBindGroup` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `setBlendConstant` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `setIndexBuffer` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `setPipeline` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `setScissorRect` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `setStencilReference` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `setVertexBuffer` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `setViewport` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `writeTimestamp` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPURenderPassEncoder>

GPURenderPipeline
=================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPURenderPipeline` interface of the [WebGPU API](webgpu_api) represents a pipeline that controls the vertex and fragment shader stages and can be used in a [`GPURenderPassEncoder`](gpurenderpassencoder) or [`GPURenderBundleEncoder`](gpurenderbundleencoder).

 A `GPURenderPipeline` object instance can be created using the [`GPUDevice.createRenderPipeline()`](gpudevice/createrenderpipeline) or [`GPUDevice.createRenderPipelineAsync()`](gpudevice/createrenderpipelineasync) methods.



Instance properties
-------------------


 
[`label`](gpurenderpipeline/label)  Experimental 
  A string providing a label that can be used to identify the object, for example in [`GPUError`](gpuerror) messages or console warnings.

  
Instance methods
----------------


 
[`getBindGroupLayout()`](gpurenderpipeline/getbindgrouplayout)  Experimental 
  Returns the pipeline's [`GPUBindGroupLayout`](gpubindgrouplayout) object with the given index (i.e. included in the originating [`GPUDevice.createRenderPipeline()`](gpudevice/createrenderpipeline) or [`GPUDevice.createRenderPipelineAsync()`](gpudevice/createrenderpipelineasync) call's pipeline layout).

  
Examples
--------


 **Note:** The [WebGPU samples](https://webgpu.github.io/webgpu-samples/) feature many more examples.

 
### Basic example



Our [basic render demo](https://mdn.github.io/dom-examples/webgpu-render-demo/) provides a simple example of the construction of a valid render pipeline descriptor object, which is then used to create a `GPURenderPipeline` via a `createRenderPipeline()` call.

 
```
// ...

const vertexBuffers = [
  {
    attributes: [
      {
        shaderLocation: 0, // position
        offset: 0,
        format: "float32x4",
      },
      {
        shaderLocation: 1, // color
        offset: 16,
        format: "float32x4",
      },
    ],
    arrayStride: 32,
    stepMode: "vertex",
  },
];

const pipelineDescriptor = {
  vertex: {
    module: shaderModule,
    entryPoint: "vertex\_main",
    buffers: vertexBuffers,
  },
  fragment: {
    module: shaderModule,
    entryPoint: "fragment\_main",
    targets: [
      {
        format: navigator.gpu.getPreferredCanvasFormat(),
      },
    ],
  },
  primitive: {
    topology: "triangle-list",
  },
  layout: "auto",
};

const renderPipeline = device.createRenderPipeline(pipelineDescriptor);

// ...

```


Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpurenderpipeline](https://gpuweb.github.io/gpuweb/#gpurenderpipeline) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPURenderPipeline` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `getBindGroupLayout` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `label` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPURenderPipeline>

GPURenderBundle
===============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPURenderBundle` interface of the [WebGPU API](webgpu_api) represents a container for pre-recorded bundles of commands.

 The command bundles are encoded using a [`GPURenderBundleEncoder`](gpurenderbundleencoder); once the desired commands have been encoded, they are recorded into a `GPURenderBundle` object instance using the [`GPURenderBundleEncoder.finish()`](gpurenderbundleencoder/finish) method.

 These command bundles can then be reused across multiple render passes by passing the `GPURenderBundle` objects into [`GPURenderPassEncoder.executeBundles()`](gpurenderpassencoder/executebundles) calls. Reusing pre-recoded commands can significantly improve app performance in situations where JavaScript draw call overhead is a bottleneck. Render bundles are most effective in situations where a batch of objects will be drawn the same way across multiple views or frames, with the only differences being the buffer content being used (such as updated matrix uniforms).

 A good example is VR rendering. Recording the rendering as a render bundle and then tweaking the view matrix and replaying it for each eye is a more efficient way to issue draw calls for both renderings of the scene.



Instance properties
-------------------


 
[`label`](gpucomputepassencoder/label)  Experimental 
  A string providing a label that can be used to identify the object, for example in [`GPUError`](gpuerror) messages or console warnings.

  
Examples
--------



In the WebGPU Samples [Animometer example](https://webgpu.github.io/webgpu-samples/samples/animometer), a lot of like operations are done on many different objects simultaneously. A render bundle is encoded using the following function:

 
```
function recordRenderPass(
  passEncoder: GPURenderBundleEncoder | GPURenderPassEncoder
) {
  if (settings.dynamicOffsets) {
    passEncoder.setPipeline(dynamicPipeline);
  } else {
    passEncoder.setPipeline(pipeline);
  }
  passEncoder.setVertexBuffer(0, vertexBuffer);
  passEncoder.setBindGroup(0, timeBindGroup);
  const dynamicOffsets = [0];
  for (let i = 0; i < numTriangles; ++i) {
    if (settings.dynamicOffsets) {
      dynamicOffsets[0] = i \* alignedUniformBytes;
      passEncoder.setBindGroup(1, dynamicBindGroup, dynamicOffsets);
    } else {
      passEncoder.setBindGroup(1, bindGroups[i]);
    }
    passEncoder.draw(3, 1, 0, 0);
  }
}

```
 Later on, a [`GPURenderBundleEncoder`](gpurenderbundleencoder) is created, the function is invoked, and the render bundle is recorded using [`GPURenderBundleEncoder.finish()`](gpurenderbundleencoder/finish):

 
```
const renderBundleEncoder = device.createRenderBundleEncoder({
  colorFormats: [presentationFormat],
});
recordRenderPass(renderBundleEncoder);
const renderBundle = renderBundleEncoder.finish();

```
 [`GPURenderPassEncoder.executeBundles()`](gpurenderpassencoder/executebundles) is then used to reuse the work across multiple render passes to improve performance. Study the example code listing for the full context.

 
```
// ...

return function doDraw(timestamp) {
  if (startTime === undefined) {
    startTime = timestamp;
  }
  uniformTime[0] = (timestamp - startTime) / 1000;
  device.queue.writeBuffer(uniformBuffer, timeOffset, uniformTime.buffer);

  renderPassDescriptor.colorAttachments[0].view = context
    .getCurrentTexture()
    .createView();

  const commandEncoder = device.createCommandEncoder();
  const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);

  if (settings.renderBundles) {
    passEncoder.executeBundles([renderBundle]);
  } else {
    recordRenderPass(passEncoder);
  }

  passEncoder.end();
  device.queue.submit([commandEncoder.finish()]);
};

// ...

```


Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpurenderbundle](https://gpuweb.github.io/gpuweb/#gpurenderbundle) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPURenderBundle` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `label` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPURenderBundle>

GPUSampler
==========



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUSampler` interface of the [WebGPU API](webgpu_api) represents an object that can control how shaders transform and filter texture resource data.

 A `GPUSampler` object instance is created using the [`GPUDevice.createSampler()`](gpudevice/createsampler) method.



Instance properties
-------------------


 
[`label`](gpusampler/label)  Experimental 
  A string providing a label that can be used to identify the object, for example in [`GPUError`](gpuerror) messages or console warnings.

  
Examples
--------



The following snippet creates a `GPUSampler` that does trilinear filtering and repeats texture coordinates:

 
```
// ...
const sampler = device.createSampler({
  addressModeU: "repeat",
  addressModeV: "repeat",
  magFilter: "linear",
  minFilter: "linear",
  mipmapFilter: "linear",
});

```
 The WebGPU samples [Shadow Mapping sample](https://webgpu.github.io/webgpu-samples/samples/shadowMapping) uses comparison samplers to sample from a depth texture to render shadows.



Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpusampler](https://gpuweb.github.io/gpuweb/#gpusampler) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUSampler` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `label` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUSampler>

GPUShaderModule
===============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUShaderModule` interface of the [WebGPU API](webgpu_api) represents an internal shader module object, a container for [WGSL](https://gpuweb.github.io/gpuweb/wgsl/) shader code that can be submitted to the GPU for execution by a pipeline.

 A `GPUShaderModule` object instance is created using [`GPUDevice.createShaderModule()`](gpudevice/createshadermodule).



Instance properties
-------------------


 
[`label`](gpushadermodule/label)  Experimental 
  A string providing a label that can be used to identify the object, for example in [`GPUError`](gpuerror) messages or console warnings.

  
Instance methods
----------------


 
[`getCompilationInfo()`](gpushadermodule/getcompilationinfo)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that fulfills with a [`GPUCompilationInfo`](gpucompilationinfo) object containing messages generated during the `GPUShaderModule`'s compilation.

  
Examples
--------



In our [basic render demo](https://mdn.github.io/dom-examples/webgpu-render-demo/), our shader module is created using the following code:

 
```
const shaders = `
struct VertexOut {
 @builtin(position) position : vec4f,
 @location(0) color : vec4f
}

@vertex
fn vertex\_main(@location(0) position: vec4f,
 @location(1) color: vec4f) -> VertexOut
{
 var output : VertexOut;
 output.position = position;
 output.color = color;
 return output;
}

@fragment
fn fragment\_main(fragData: VertexOut) -> @location(0) vec4f
{
 return fragData.color;
}
`;

async function init() {
  if (!navigator.gpu) {
    throw Error("WebGPU not supported.");
  }

  const adapter = await navigator.gpu.requestAdapter();

  if (!adapter) {
    throw Error("Couldn't request WebGPU adapter.");
  }

  let device = await adapter.requestDevice();

  // ...
  // later on

  const shaderModule = device.createShaderModule({
    code: shaders,
  });

  // ...
}

```


Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpushadermodule](https://gpuweb.github.io/gpuweb/#gpushadermodule) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUShaderModule` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `getCompilationInfo` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `label` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUShaderModule>

GPUSupportedFeatures
====================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUSupportedFeatures` interface of the [WebGPU API](webgpu_api) is a [setlike](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) object that describes additional functionality supported by a [`GPUAdapter`](gpuadapter).

 The `GPUSupportedFeatures` object for the current adapter is accessed via the [`GPUAdapter.features`](gpuadapter/features) property.

 You should note that not all features will be available to WebGPU in all browsers that support it, even if the features are supported by the underlying hardware. This could be due to constraints in the underlying system, browser, or adapter. For example:

 * The underlying system might not be able to guarantee exposure of a feature in a way that is compatible with a certain browser.
* The browser vendor might not have found a secure way to implement support for that feature, or might just not have gotten round to it yet.

 If you are hoping to take advantage of a specific additional feature in a WebGPU app, thorough testing is advised.



Available features
------------------


We have not listed the exact set of additional features available to be used in WebGPU, as it will vary between implementations and physical devices, and will change over time. For a list, refer to the [Feature Index](https://gpuweb.github.io/gpuweb/#feature-index) in the specification.


Instance properties
-------------------



The following properties are available to all read-only [setlike](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) objects (the below links are to the [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) global object reference pages).

  [`size`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/size)  Returns the number of values in the set.

  

Instance methods
----------------



The following methods are available to all read-only [setlike](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) objects (the below links are to the [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) global object reference pages).

  [`has()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/has)  Returns a boolean asserting whether an element is present with the given value in the set or not.

  [`values()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/values)  Returns a new iterator object that yields the **values** for each element in the set in insertion order.

  [`keys()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/keys)  An alias for [`values()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/values).

  [`entries()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/entries)  Returns a new iterator object that contains `[value, value]` for each element in the set, in insertion order.

  [`forEach()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/forEach)  Calls a provided callback function once for each value present in the set, in insertion order.

  

Examples
--------



```
async function init() {
  if (!navigator.gpu) {
    throw Error("WebGPU not supported.");
  }

  const adapter = await navigator.gpu.requestAdapter();
  if (!adapter) {
    throw Error("Couldn't request WebGPU adapter.");
  }

  const adapterFeatures = adapter.features;

  // Return the size of the set
  console.log(adapterFeatures.size);

  // Check whether a feature is supported by the adapter
  console.log(adapterFeatures.has("texture-compression-astc"));

  // Iterate through all the set values using values()
  const valueIterator = adapterFeatures.values();
  for (const value of valueIterator) {
    console.log(value);
  }

  // Iterate through all the set values using keys()
  const keyIterator = adapterFeatures.keys();
  for (const value of keyIterator) {
    console.log(value);
  }

  // Iterate through all the set values using entries()
  const entryIterator = adapterFeatures.entries();
  for (const entry of entryIterator) {
    console.log(entry[0]);
  }

  // Iterate through all the set values using forEach()
  adapterFeatures.forEach((value) => {
    console.log(value);
  });

  //...
}

```

Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpu-supportedfeatures](https://gpuweb.github.io/gpuweb/#gpu-supportedfeatures) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUSupportedFeatures` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUSupportedFeatures>

GPUSupportedLimits
==================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUSupportedLimits` interface of the [WebGPU API](webgpu_api) describes the limits supported by a [`GPUAdapter`](gpuadapter).

 The `GPUSupportedLimits` object for the current adapter is accessed via the [`GPUAdapter.limits`](gpuadapter/limits) property.

 You should note that, rather than reporting the exact limits of each GPU, browsers will likely report different tier values of different limits to reduce the unique information available to drive-by fingerprinting. For example, the tiers of a certain limit might be 2048, 8192, and 32768. If your GPU's actual limit is 16384, the browser will still report 8192.

 Given that different browsers will handle this differently and the tier values may change over time, it is hard to provide an accurate account of what limit values to expect — thorough testing is advised.



Instance properties
-------------------



The following limits are represented by properties in a `GPUSupportedLimits` object. See the [Limits](https://gpuweb.github.io/gpuweb/#limits) section of the specification for detailed descriptions of what the limits relate to.

 

| Limit name | Default value |
| --- | --- |
| `maxTextureDimension1D` | 8192 |
| `maxTextureDimension2D` | 8192 |
| `maxTextureDimension3D` | 2048 |
| `maxTextureArrayLayers` | 256 |
| `maxBindGroups` | 4 |
| `maxBindingsPerBindGroup` | 640 |
| `maxDynamicUniformBuffersPerPipelineLayout` | 8 |
| `maxDynamicStorageBuffersPerPipelineLayout` | 4 |
| `maxSampledTexturesPerShaderStage` | 16 |
| `maxSamplersPerShaderStage` | 16 |
| `maxStorageBuffersPerShaderStage` | 8 |
| `maxStorageTexturesPerShaderStage` | 4 |
| `maxUniformBuffersPerShaderStage` | 12 |
| `maxUniformBufferBindingSize` | 65536 bytes |
| `maxStorageBufferBindingSize` | 134217728 bytes (128 MB) |
| `minUniformBufferOffsetAlignment` | 256 bytes |
| `minStorageBufferOffsetAlignment` | 256 bytes |
| `maxVertexBuffers` | 8 |
| `maxBufferSize` | 268435456 bytes (256 MB) |
| `maxVertexAttributes` | 16 |
| `maxVertexBufferArrayStride` | 2048 bytes |
| `maxInterStageShaderComponents` | 60 |
| `maxInterStageShaderVariables` | 16 |
| `maxColorAttachments` | 8 |
| `maxColorAttachmentBytesPerSample` | 32 |
| `maxComputeWorkgroupStorageSize` | 16384 bytes |
| `maxComputeInvocationsPerWorkgroup` | 256 |
| `maxComputeWorkgroupSizeX` | 256 |
| `maxComputeWorkgroupSizeY` | 256 |
| `maxComputeWorkgroupSizeZ` | 64 |
| `maxComputeWorkgroupsPerDimension` | 65535 |



Examples
--------



In the following code we query the `GPUAdapter.limits` value of `maxBindGroups` to see if it is equal to or greater than 6. Our theoretical example app ideally needs 6 bind groups, so if the returned value is >= 6, we add a maximum limit of 6 to the `requiredLimits` object. We then request a device with that limit requirement using [`GPUAdapter.requestDevice()`](gpuadapter/requestdevice):

 
```
async function init() {
  if (!navigator.gpu) {
    throw Error("WebGPU not supported.");
  }

  const adapter = await navigator.gpu.requestAdapter();
  if (!adapter) {
    throw Error("Couldn't request WebGPU adapter.");
  }

  const requiredLimits = {};

  // App ideally needs 6 bind groups, so we'll try to request what the app needs
  if (adapter.limits.maxBindGroups >= 6) {
    requiredLimits.maxBindGroups = 6;
  }

  const device = await adapter.requestDevice({
    requiredLimits,
  });

  // ...
}

```


Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpusupportedlimits](https://gpuweb.github.io/gpuweb/#gpusupportedlimits) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUSupportedLimits` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxBindGroups` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxBindingsPerBindGroup` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxBufferSize` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxColorAttachmentBytesPerSample` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxColorAttachments` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxComputeInvocationsPerWorkgroup` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxComputeWorkgroupSizeX` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxComputeWorkgroupSizeY` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxComputeWorkgroupSizeZ` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxComputeWorkgroupStorageSize` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxComputeWorkgroupsPerDimension` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxDynamicStorageBuffersPerPipelineLayout` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxDynamicUniformBuffersPerPipelineLayout` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxInterStageShaderComponents` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxInterStageShaderVariables` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxSampledTexturesPerShaderStage` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxSamplersPerShaderStage` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxStorageBufferBindingSize` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxStorageBuffersPerShaderStage` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxStorageTexturesPerShaderStage` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxTextureArrayLayers` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxTextureDimension1D` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxTextureDimension2D` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxTextureDimension3D` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxUniformBufferBindingSize` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxUniformBuffersPerShaderStage` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxVertexAttributes` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxVertexBufferArrayStride` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `maxVertexBuffers` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `minStorageBufferOffsetAlignment` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `minUniformBufferOffsetAlignment` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUSupportedLimits>

GPUTextureView
==============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUTextureView` interface of the [WebGPU API](webgpu_api) represents a view into a subset of the texture resources defined by a particular [`GPUTexture`](gputexture).

 A `GPUTextureView` object instance is created using the [`GPUTexture.createView()`](gputexture/createview) method.



Instance properties
-------------------


 
[`label`](gputextureview/label)  Experimental 
  A string providing a label that can be used to identify the object, for example in [`GPUError`](gpuerror) messages or console warnings.

  
Examples
--------



In the WebGPU Samples [Cubemap demo](https://webgpu.github.io/webgpu-samples/samples/cubemap), you will see multiple examples of how `GPUTextureView`s (created by [`GPUTexture.createView()`](gputexture/createview) calls) are used, both as a `resource` in a [`GPUDevice.createBindGroup()`](gpudevice/createbindgroup) call, and as a provided `view` in the `depthStencilAttachment` object of a [`GPUCommandEncoder.beginRenderPass()`](gpucommandencoder/beginrenderpass) descriptor.

 
```
const uniformBindGroup = device.createBindGroup({
  layout: pipeline.getBindGroupLayout(0),
  entries: [
    {
      binding: 0,
      resource: {
        buffer: uniformBuffer,
        offset: 0,
        size: uniformBufferSize,
      },
    },
    {
      binding: 1,
      resource: sampler,
    },
    {
      binding: 2,
      resource: cubemapTexture.createView({
        dimension: "cube",
      }),
    },
  ],
});

const renderPassDescriptor: GPURenderPassDescriptor = {
  colorAttachments: [
    {
      view: undefined, // Assigned later
      loadOp: "clear",
      storeOp: "store",
    },
  ],
  depthStencilAttachment: {
    view: depthTexture.createView(),
    depthClearValue: 1.0,
    depthLoadOp: "clear",
    depthStoreOp: "store",
  },
};

// ...

const commandEncoder = device.createCommandEncoder();
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);

// ...

```


Specifications
--------------




| Specification |
| --- |
| [WebGPU # gputextureview](https://gpuweb.github.io/gpuweb/#gputextureview) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUTextureView` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `label` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUTextureView>

GPUUncapturedErrorEvent
=======================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUUncapturedErrorEvent` interface of the [WebGPU API](webgpu_api) is the event object type for the [`GPUDevice`](gpudevice) [`uncapturederror`](gpudevice/uncapturederror_event) event, used for telemetry and to report unexpected errors.

 Known error cases should be handled using [`pushErrorScope()`](gpudevice/pusherrorscope) and [`popErrorScope()`](gpudevice/poperrorscope).


 Event GPUUncapturedErrorEvent

Constructor
-----------


 
[`GPUUncapturedErrorEvent()`](gpuuncapturederrorevent/gpuuncapturederrorevent)  Experimental 
  Creates a new `GPUUncapturedErrorEvent` object instance.

  
Instance properties
-------------------



*Inherits properties from its parent, [`Event`](event).*

  
[`error`](gpuuncapturederrorevent/error)  Experimental  Read only 
  A [`GPUError`](gpuerror) object instance providing access to the details of the error.

  

Examples
--------



You could use something like the following as a global mechanism to pick up any errors that aren't handled by error scopes and capture them.

 
```
// ...

device.addEventListener("uncapturederror", (event) => {
  // Re-surface the error
  console.error("A WebGPU error was not captured:", event.error.message);
  reportErrorToServer({
    type: event.error.constructor.name,
    message: event.error.message,
  });
});

// ...

```


Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpuuncapturederrorevent](https://gpuweb.github.io/gpuweb/#gpuuncapturederrorevent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUUncapturedErrorEvent` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `GPUUncapturedErrorEvent` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `error` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | No | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)
* [WebGPU Error Handling best practices](https://toji.dev/webgpu-best-practices/error-handling)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUUncapturedErrorEvent>

GPUValidationError
==================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUValidationError` interface of the [WebGPU API](webgpu_api) describes an application error indicating that an operation did not pass the WebGPU API's validation constraints.

 It represents one of the types of errors surfaced by [`GPUDevice.popErrorScope`](gpudevice/poperrorscope) and the [`uncapturederror`](gpudevice/uncapturederror_event) event.

 Validation errors occur whenever invalid inputs are given to a WebGPU call. These are consistent, predictable, and should not occur provided your app is well-formed. They will occur in the same way on every device your code runs on, so once you've fixed any errors that show up during development you probably don't need to observe them directly most of the time. An exception to that rule is if you're consuming user-supplied assets, shaders, etc., in which case watching for validation errors while loading could be helpful.

  **Note:** We have attempted to provide useful information to help you understand why validation errors are occurring in your WebGPU code in "Validation" sections where appropriate, which list criteria to meet to avoid validation errors. See for example the [`GPUDevice.createBindGroup()` Validation section](gpudevice/createbindgroup#validation).

 
 GPUError GPUValidationError

Constructor
-----------


 
[`GPUValidationError()`](gpuvalidationerror/gpuvalidationerror)  Experimental 
  Creates a new `GPUValidationError` object instance.

  
Instance properties
-------------------



The `message` property is inherited from its parent, [`GPUError`](gpuerror):

  
[`message`](gpuerror/message)  Experimental  Read only 
  A string providing a human-readable message that explains why the error ocurred.

  

Examples
--------



The following example uses an error scope to capture a suspected validation error, logging it to the console.

 
```
device.pushErrorScope("validation");

let sampler = device.createSampler({
  maxAnisotropy: 0, // Invalid, maxAnisotropy must be at least 1.
});

device.popErrorScope().then((error) => {
  if (error) {
    // error is a GPUValidationError object instance
    sampler = null;
    console.error(`An error occurred while creating sampler: ${error.message}`);
  }
});

```


Specifications
--------------




| Specification |
| --- |
| [WebGPU # gpuvalidationerror](https://gpuweb.github.io/gpuweb/#gpuvalidationerror) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUValidationError` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `GPUValidationError` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)
* [WebGPU Error Handling best practices](https://toji.dev/webgpu-best-practices/error-handling)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUValidationError>

GravitySensor
=============



The `GravitySensor` interface of the [Sensor APIs](sensor_apis) provides on each reading the gravity applied to the device along all three axes.

 To use this sensor, the user must grant permission to the `'accelerometer'` device sensor through the [Permissions API](permissions_api). In addition, this feature may be blocked by a [Permissions Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy) set on your server.


 EventTarget Sensor Accelerometer GravitySensor

Constructor
-----------


 [`GravitySensor()`](gravitysensor/gravitysensor)  Creates a new `GravitySensor` object.

  
Instance properties
-------------------


*Inherits properties from its ancestors, [`Accelerometer`](accelerometer), [`Sensor`](sensor), and [`EventTarget`](eventtarget).*


Instance methods
----------------


*`GravitySensor` doesn't have own methods. However, it inherits methods from its parent interfaces, [`Sensor`](sensor) and [`EventTarget`](eventtarget).*


Events
------


*`GravitySensor` doesn't have own events. However, it inherits events from its parent interface, [`Sensor`](sensor).*


Example
-------



Gravity is typically read in the [`reading`](sensor/reading_event) event callback. In the example below this occurs sixty times a second.

 
```
let gravitySensor = new GravitySensor({ frequency: 60 });

gravitySensor.addEventListener("reading", (e) => {
  console.log(`Gravity along the X-axis ${gravitySensor.x}`);
  console.log(`Gravity along the Y-axis ${gravitySensor.y}`);
  console.log(`Gravity along the Z-axis ${gravitySensor.z}`);
});

gravitySensor.start();

```


Specifications
--------------




| Specification |
| --- |
| [Accelerometer # gravitysensor-interface](https://w3c.github.io/accelerometer/#gravitysensor-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GravitySensor` | 91 | 91 | No | No | 77 | No | 91 | 91 | No | 64 | No | 16.0 |
| `GravitySensor` | 91 | 91 | No | No | 77 | No | 91 | 91 | No | 64 | No | 16.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GravitySensor>

Headers
=======



The `Headers` interface of the [Fetch API](fetch_api) allows you to perform various actions on [HTTP request and response headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers). These actions include retrieving, setting, adding to, and removing headers from the list of the request's headers.

 A `Headers` object has an associated header list, which is initially empty and consists of zero or more name and value pairs. You can add to this using methods like [`append()`](headers/append) (see [Examples](#examples).) In all methods of this interface, header names are matched by case-insensitive byte sequence.

 For security reasons, some headers can only be controlled by the user agent. These headers include the [forbidden header names](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name) and [forbidden response header names](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_response_header_name).

 A Headers object also has an associated guard, which takes a value of `immutable`, `request`, `request-no-cors`, `response`, or `none`. This affects whether the [`set()`](headers/set), [`delete()`](headers/delete), and [`append()`](headers/append) methods will mutate the header. For more information see [Guard](https://developer.mozilla.org/en-US/docs/Glossary/Guard).

 You can retrieve a `Headers` object via the [`Request.headers`](request/headers) and [`Response.headers`](response/headers) properties, and create a new `Headers` object using the [`Headers()`](headers/headers) constructor.

 An object implementing `Headers` can directly be used in a [`for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) structure, instead of [`entries()`](headers/entries): `for (const p of myHeaders)` is equivalent to `for (const p of myHeaders.entries())`.

  **Note:** you can find out more about the available headers by reading our [HTTP headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) reference.

 

Constructor
-----------


 [`Headers()`](headers/headers)  Creates a new `Headers` object.

  
Instance methods
----------------



 [`Headers.append()`](headers/append)  Appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist.

  [`Headers.delete()`](headers/delete)  Deletes a header from a `Headers` object.

  [`Headers.entries()`](headers/entries)  Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all key/value pairs contained in this object.

  [`Headers.forEach()`](headers/foreach)  Executes a provided function once for each key/value pair in this `Headers` object.

  [`Headers.get()`](headers/get)  Returns a [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) sequence of all the values of a header within a `Headers` object with a given name.

  
[`Headers.getSetCookie()`](headers/getsetcookie)  Experimental 
  Returns an array containing the values of all [`Set-Cookie`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie) headers associated with a response.

  [`Headers.has()`](headers/has)  Returns a boolean stating whether a `Headers` object contains a certain header.

  [`Headers.keys()`](headers/keys)  Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing you to go through all keys of the key/value pairs contained in this object.

  [`Headers.set()`](headers/set)  Sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist.

  [`Headers.values()`](headers/values)  Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing you to go through all values of the key/value pairs contained in this object.

    **Note:** To be clear, the difference between [`Headers.set()`](headers/set) and [`Headers.append()`](headers/append) is that if the specified header does already exist and does accept multiple values, [`Headers.set()`](headers/set) will overwrite the existing value with the new one, whereas [`Headers.append()`](headers/append) will append the new value onto the end of the set of values. See their dedicated pages for example code.

   **Note:** All of the Headers methods will throw a [`TypeError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) if you try to pass in a reference to a name that isn't a [valid HTTP Header name](https://fetch.spec.whatwg.org/#concept-header-name). The mutation operations will throw a `TypeError` if the header has an immutable [Guard](https://developer.mozilla.org/en-US/docs/Glossary/Guard). In any other failure case they fail silently.

   **Note:** When Header values are iterated over, they are automatically sorted in lexicographical order, and values from duplicate header names are combined.

 

Examples
--------



In the following snippet, we create a new header using the `Headers()` constructor, add a new header to it using `append()`, then return that header value using `get()`:

 
```
const myHeaders = new Headers();

myHeaders.append("Content-Type", "text/xml");
myHeaders.get("Content-Type"); // should return 'text/xml'

```
 The same can be achieved by passing an array of arrays or an object literal to the constructor:

 
```
let myHeaders = new Headers({
  "Content-Type": "text/xml",
});

// or, using an array of arrays:
myHeaders = new Headers([["Content-Type", "text/xml"]]);

myHeaders.get("Content-Type"); // should return 'text/xml'

```


Specifications
--------------




| Specification |
| --- |
| [Fetch Standard # headers-class](https://fetch.spec.whatwg.org/#headers-class) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@iterator` | 42 | 16 | 44 | No | 29 | 10.1 | 42 | 42 | 44 | 29 | 10.3 | 4.0 |
| `Headers` | 42 | 14 | 39 | No | 29 | 10.1 | 42 | 42 | 44 | 29 | 10.3 | 4.0 |
| `Headers` | 42 | 14 | 39 | No | 29 | 10.1 | 42 | 42 | 44 | 29 | 10.3 | 4.0 |
| `append` | 42 | 14 | 39 | No | 29 | 10.1 | 42 | 42 | 44 | 29 | 10.3 | 4.0 |
| `delete` | 42 | 14 | 39 | No | 29 | 10.1 | 42 | 42 | 44 | 29 | 10.3 | 4.0 |
| `entries` | 42 | 16 | 44 | No | 29 | 10.1 | 42 | 42 | 44 | 29 | 10.3 | 4.0 |
| `forEach` | 42 | 14 | 47 | No | 29 | 10.1 | 42 | 42 | 47 | 29 | 10.3 | 4.0 |
| `get` | 42Before version 57, `get()` returns only the first value for the specified header. | 14 | 39Before version 52, `get()` returns only the first value for the specified header. | No | 29Before version 44, `get()` returns only the first value for the specified header. | 10.1 | 42Before version 57, `get()` returns only the first value for the specified header. | 42Before version 57, `get()` returns only the first value for the specified header. | 44Before version 52, `get()` returns only the first value for the specified header. | 29Before version 43, `get()` returns only the first value for the specified header. | 10.3 | 4.0Before version 7.0, `get()` returns only the first value for the specified header. |
| `getSetCookie` | 113 | 113 | No | No | No | No | 113 | 113 | No | No | No | No |
| `has` | 42 | 14 | 39 | No | 29 | 10.1 | 42 | 42 | 44 | 29 | 10.3 | 4.0 |
| `keys` | 42 | 16 | 44 | No | 29 | 10.1 | 42 | 42 | 44 | 29 | 10.3 | 4.0 |
| `lexicographical_sorting` | 57 | 79 | 44 | No | 44 | No | 57 | 57 | 44 | 43 | No | 7.0 |
| `set` | 42 | 14 | 39 | No | 29 | 10.1 | 42 | 42 | 44 | 29 | 10.3 | 4.0 |
| `values` | 42 | 16 | 44 | No | 29 | 10.1 | 42 | 42 | 44 | 29 | 10.3 | 4.0 |


See also
--------


* [ServiceWorker API](service_worker_api)
* [HTTP access control (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)
* [HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Headers>

GPUTexture
==========



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `GPUTexture` interface of the [WebGPU API](webgpu_api) represents a container used to store 1D, 2D, or 3D arrays of data, such as images, to use in GPU rendering operations.

 A `GPUTexture` object instance is created using the [`GPUDevice.createTexture()`](gpudevice/createtexture) method.



Instance properties
-------------------


 
[`depthOrArrayLayers`](gputexture/depthorarraylayers)  Experimental  Read only 
  A number representing the depth or layer count of the `GPUTexture` (pixels, or number of layers).

  
[`dimension`](gputexture/dimension)  Experimental  Read only 
  An enumerated value representing the dimension of the set of texels for each `GPUTexture` subresource.

  
[`format`](gputexture/format)  Experimental  Read only 
  An enumerated value representing the format of the `GPUTexture`.

  
[`height`](gputexture/height)  Experimental  Read only 
  A number representing the height of the `GPUTexture` in pixels.

  
[`label`](gputexture/label)  Experimental 
  A string providing a label that can be used to identify the object, for example in [`GPUError`](gpuerror) messages or console warnings.

  
[`mipLevelCount`](gputexture/miplevelcount)  Experimental  Read only 
  A number representing the number of mip levels of the `GPUTexture`.

  
[`sampleCount`](gputexture/samplecount)  Experimental  Read only 
  A number representing the sample count of the `GPUTexture`.

  
[`usage`](gputexture/usage)  Experimental  Read only 
  The [bitwise flags](https://developer.mozilla.org/en-US/docs/Glossary/Bitwise_flags) representing the allowed usages of the `GPUTexture`.

  
[`width`](gputexture/width)  Experimental  Read only 
  A number representing the width of the `GPUTexture` in pixels.

  
Instance methods
----------------


 
[`createView()`](gputexture/createview)  Experimental 
  Creates a [`GPUTextureView`](gputextureview) representing a specific view of the `GPUTexture`.

  
[`destroy()`](gputexture/destroy)  Experimental 
  Destroys the `GPUTexture`.

  
Examples
--------



In the WebGPU samples [Textured Cube sample](https://webgpu.github.io/webgpu-samples/samples/texturedCube), a texture to use on the faces of a cube is created by:

 * Loading the image into an [`HTMLImageElement`](htmlimageelement) and creating an image bitmap using [`createImageBitmap()`](createimagebitmap).
* Creating a new `GPUTexture` using `createTexture()`.
* Copying the image bitmap into the texture using [`GPUQueue.copyExternalImageToTexture()`](gpuqueue/copyexternalimagetotexture).

 
```
//...
let cubeTexture: GPUTexture; // Sample is written in TypeScript
{
  const img = document.createElement("img");

  img.src = new URL(
    "../../../assets/img/Di-3d.png",
    import.meta.url
  ).toString();

  await img.decode();

  const imageBitmap = await createImageBitmap(img);

  cubeTexture = device.createTexture({
    size: [imageBitmap.width, imageBitmap.height, 1],
    format: "rgba8unorm",
    usage:
      GPUTextureUsage.TEXTURE\_BINDING |
      GPUTextureUsage.COPY\_DST |
      GPUTextureUsage.RENDER\_ATTACHMENT,
  });

  device.queue.copyExternalImageToTexture(
    { source: imageBitmap },
    { texture: cubeTexture },
    [imageBitmap.width, imageBitmap.height]
  );
}
//...

```


Specifications
--------------




| Specification |
| --- |
| [WebGPU # texture-interface](https://gpuweb.github.io/gpuweb/#texture-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `GPUTexture` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `createView` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `depthOrArrayLayers` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `destroy` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `dimension` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `format` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `height` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `label` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `mipLevelCount` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `sampleCount` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `usage` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `width` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |


See also
--------


* The [WebGPU API](webgpu_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/GPUTexture>

Gyroscope
=========



The `Gyroscope` interface of the [Sensor APIs](sensor_apis) provides on each reading the angular velocity of the device along all three axes.

 To use this sensor, the user must grant permission to the `'gyroscope'` device sensor through the [Permissions API](permissions_api). In addition, this feature may be blocked by a [Permissions Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy) set on your server.


 EventTarget Sensor Gyroscope

Constructor
-----------


 [`Gyroscope()`](gyroscope/gyroscope)  Creates a new `Gyroscope` object.

  
Instance properties
-------------------


 
[`Gyroscope.x`](gyroscope/x) Read only 
  Returns a double, containing the angular velocity of the device along the device's x axis.

  
[`Gyroscope.y`](gyroscope/y) Read only 
  Returns a double, containing the angular velocity of the device along the device's y axis.

  
[`Gyroscope.z`](gyroscope/z) Read only 
  Returns a double, containing the angular velocity of the device along the device's z axis.

  
Instance methods
----------------


*`Gyroscope` doesn't have own methods. However, it inherits methods from its parent interfaces, [`Sensor`](sensor) and [`EventTarget`](eventtarget).*


Events
------


*`Gyroscope` doesn't have own events. However, it inherits events from its parent interface, [`Sensor`](sensor).*


Example
-------



The gyroscope is typically read in the [`reading`](sensor/reading_event) event callback. In the example below this occurs sixty times a second.

 
```
let gyroscope = new Gyroscope({ frequency: 60 });

gyroscope.addEventListener("reading", (e) => {
  console.log(`Angular velocity along the X-axis ${gyroscope.x}`);
  console.log(`Angular velocity along the Y-axis ${gyroscope.y}`);
  console.log(`Angular velocity along the Z-axis ${gyroscope.z}`);
});
gyroscope.start();

```


Specifications
--------------




| Specification |
| --- |
| [Gyroscope # gyroscope-interface](https://w3c.github.io/gyroscope/#gyroscope-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Gyroscope` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |
| `Gyroscope` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |
| `x` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |
| `y` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |
| `z` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Gyroscope>

HashChangeEvent
===============



The `HashChangeEvent` interface represents events that fire when the fragment identifier of the URL has changed.

 The fragment identifier is the part of the URL that follows (and includes) the `#` symbol.


 Event HashChangeEvent

Constructor
-----------


 [`HashChangeEvent()`](hashchangeevent/hashchangeevent)  Creates a new `HashChangeEvent` object.

  
Instance properties
-------------------



*This interface also inherits the properties of its parent, [`Event`](event).*

  
[`HashChangeEvent.newURL`](hashchangeevent/newurl) Read only 
  The new URL to which the window is navigating.

  
[`HashChangeEvent.oldURL`](hashchangeevent/oldurl) Read only 
  The previous URL from which the window was navigated.

  

Instance methods
----------------


*This interface has no methods of its own, but inherits the methods of its parent, [`Event`](event).*


Examples
--------


### Basic example



```
function locationHashChanged() {
  if (location.hash === "#somecoolfeature") {
    somecoolfeature();
  }
}

window.addEventListener("hashchange", locationHashChanged);

```

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-hashchangeevent-interface](https://html.spec.whatwg.org/multipage/nav-history-apis.html#the-hashchangeevent-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HashChangeEvent` | 16 | 12 | 11 | No | 15 | 6 | 4.4 | 18 | 14 | 14 | 6 | 1.0 |
| `HashChangeEvent` | 8 | 12 | 3.6 | 8 | 10.6 | 5 | 4.4 | 18 | 4 | 11 | 5 | 1.0 |
| `newURL` | 8 | 12 | 6 | No | ≤12.1 | 5.1 | 4.4 | 18 | 6 | ≤12.1 | 5 | 1.0 |
| `oldURL` | 8 | 12 | 6 | No | ≤12.1 | 5.1 | 4.4 | 18 | 6 | ≤12.1 | 5 | 1.0 |


Related events
--------------


* [`hashchange`](window/hashchange_event)
* [`popstate`](window/popstate_event)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HashChangeEvent>

HID
===



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `HID` interface provides methods for connecting to *HID devices*, listing attached HID devices and event handlers for connected HID devices.


 EventTarget HID

Instance properties
-------------------


*This interface also inherits properties of its parent, [`EventTarget`](eventtarget).*


Instance methods
----------------



*This interface also inherits methods of its parent, [`EventTarget`](eventtarget).*

  
[`getDevices()`](hid/getdevices)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with an array of connected [`HIDDevice`](hiddevice) objects.

  
[`requestDevice()`](hid/requestdevice)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with an array of connected [`HIDDevice`](hiddevice) objects. Calling this function will trigger the user agent's permission flow in order to gain permission to access one selected device from the returned list of devices.

  

### Events


 
[`connect`](hid/connect_event)  Experimental 
  Fired when an HID device is connected.

  
[`disconnect`](hid/disconnect_event)  Experimental 
  Fired when an HID device is disconnected.

  
Specifications
--------------




| Specification |
| --- |
| [WebHID API # dom-hid](https://wicg.github.io/webhid/#dom-hid) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HID` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `connect_event` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `disconnect_event` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `getDevices` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `requestDevice` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |


See also
--------


* [`WebHID API`](webhid_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HID>

HIDDevice
=========



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `HIDDevice` interface of the [`WebHID API`](webhid_api) represents a HID Device. It provides properties for accessing information about the device, methods for opening and closing the connection, and the sending and receiving of reports.


 EventTarget HIDDevice

Instance properties
-------------------



This interface also inherits properties from [`EventTarget`](eventtarget).

  
[`HIDDevice.opened`](hiddevice/opened) Read only   Experimental 
  Returns a [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean), true if the device has an open connection.

  
[`HIDDevice.vendorId`](hiddevice/vendorid) Read only   Experimental 
  Returns the vendorId of the HID device.

  
[`HIDDevice.productId`](hiddevice/productid) Read only   Experimental 
  Returns the productID of the HID device.

  
[`HIDDevice.productName`](hiddevice/productname) Read only   Experimental 
  Returns a string containing the product name of the HID device.

  
[`HIDDevice.collections`](hiddevice/collections) Read only   Experimental 
  Returns an array of report formats for the HID device.

  

### Events


 
[`inputreport`](hiddevice/inputreport_event)  Experimental 
  Fires when a report is sent from the device.

  
Instance methods
----------------



This interface also inherits methods from [`EventTarget`](eventtarget).

  
[`HIDDevice.open()`](hiddevice/open)  Experimental 
  Opens a connection to this HID device, and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which resolves once the connection has been successful.

  
[`HIDDevice.close()`](hiddevice/close)  Experimental 
  Closes the connection to this HID device, and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which resolves once the connection has been closed.

  
[`HIDDevice.forget()`](hiddevice/forget)  Experimental 
  Closes the connection to this HID device and resets access permission, and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which resolves once the permission was reset.

  
[`HIDDevice.sendReport()`](hiddevice/sendreport)  Experimental 
  Sends an output report to this HID Device, and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which resolves once the report has been sent.

  
[`HIDDevice.sendFeatureReport()`](hiddevice/sendfeaturereport)  Experimental 
  Sends a feature report to this HID device, and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which resolves once the report has been sent.

  
[`HIDDevice.receiveFeatureReport()`](hiddevice/receivefeaturereport)  Experimental 
  Receives a feature report from this HID device in the form of a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which resolves with a [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). This allows typed access to the contents of this message.

  

Examples
--------



The following example demonstrates listening for an `inputreport` event that will allow the application to detect which button is pressed on a Joy-Con Right device.

 
```
device.addEventListener("inputreport", (event) => {
  const { data, device, reportId } = event;

  // Handle only the Joy-Con Right device and a specific report ID.
  if (device.productId !== 0x2007 && reportId !== 0x3f) return;

  const value = data.getUint8(0);
  if (value === 0) return;

  const someButtons = { 1: "A", 2: "X", 4: "B", 8: "Y" };
  console.log(`User pressed button ${someButtons[value]}.`);
});

```
 In the following example `sendFeatureReport` is used to make a device blink.

 
```
const reportId = 1;
for (let i = 0; i < 10; i++) {
  // Turn off
  await device.sendFeatureReport(reportId, Uint32Array.from([0, 0]));
  await waitFor(100);
  // Turn on
  await device.sendFeatureReport(reportId, Uint32Array.from([512, 0]));
  await waitFor(100);
}

```
 You can see more examples, and live demos in the article [Connecting to uncommon HID devices](https://web.dev/hid/).



Specifications
--------------




| Specification |
| --- |
| [WebHID API # dom-hiddevice](https://wicg.github.io/webhid/#dom-hiddevice) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HIDDevice` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `close` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `collections` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `forget` | 100 | 100 | No | No | 86 | No | No | No | No | No | No | No |
| `inputreport_event` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `open` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `opened` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `productId` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `productName` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `receiveFeatureReport` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `sendFeatureReport` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `sendReport` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `vendorId` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HIDDevice>

History
=======



The `History` interface allows manipulation of the browser *session history*, that is the pages visited in the tab or frame that the current page is loaded in.

 There is only one instance of `history` (It is a *singleton*.) accessible via the global object [`history`](window/history).

  **Note:** This interface is only available on the main thread ([`Window`](window)). It cannot be accessed in [`Worker`](worker) or [`Worklet`](worklet) contexts.

 

Instance properties
-------------------



*The `History` interface doesn't inherit any property.*

  
[`length`](history/length) Read only 
  Returns an `Integer` representing the number of elements in the session history, including the currently loaded page. For example, for a page loaded in a new tab this property returns `1`.

  [`scrollRestoration`](history/scrollrestoration)  Allows web applications to explicitly set default scroll restoration behavior on history navigation. This property can be either `auto` or `manual`.

  
[`state`](history/state) Read only 
  Returns an `any` value representing the state at the top of the history stack. This is a way to look at the state without having to wait for a [`popstate`](window/popstate_event) event.

  

Instance methods
----------------



*The `History`* *interface doesn't inherit any methods.*

  [`back()`](history/back)  This asynchronous method goes to the previous page in session history, the same action as when the user clicks the browser's `Back` button. Equivalent to `history.go(-1)`.

 Calling this method to go back beyond the first page in the session history has no effect and doesn't raise an exception.

  [`forward()`](history/forward)  This asynchronous method goes to the next page in session history, the same action as when the user clicks the browser's `Forward` button; this is equivalent to `history.go(1)`.

 Calling this method to go forward beyond the most recent page in the session history has no effect and doesn't raise an exception.

  [`go()`](history/go)  Asynchronously loads a page from the session history, identified by its relative location to the current page, for example `-1` for the previous page or `1` for the next page. If you specify an out-of-bounds value (for instance, specifying `-1` when there are no previously-visited pages in the session history), this method silently has no effect. Calling `go()` without parameters or a value of `0` reloads the current page.

  [`pushState()`](history/pushstate)  Pushes the given data onto the session history stack with the specified title (and, if provided, URL). The data is treated as opaque by the DOM; you may specify any JavaScript object that can be serialized. Note that all browsers but Safari currently ignore the *title* parameter. For more information, see [Working with the History API](history_api/working_with_the_history_api).

  [`replaceState()`](history/replacestate)  Updates the most recent entry on the history stack to have the specified data, title, and, if provided, URL. The data is treated as opaque by the DOM; you may specify any JavaScript object that can be serialized. Note that all browsers but Safari currently ignore the *title* parameter. For more information, see [Working with the History API](history_api/working_with_the_history_api).

  

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-history-interface](https://html.spec.whatwg.org/multipage/nav-history-apis.html#the-history-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `History` | 1 | 12 | 1 | 10 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `back` | 1 | 12 | 1 | 10 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `forward` | 1 | 12 | 1 | 10 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `go` | 1 | 12 | 1 | 10 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `length` | 1 | 12 | 1 | 10 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `pushState` | 5 | 12 | 4Until Firefox 5, the passed object is serialized using JSON. Starting in Firefox 6, the object is serialized using [the structured clone algorithm](https://developer.mozilla.org/docs/DOM/The_structured_clone_algorithm). This allows a wider variety of objects to be safely passed. | 10 | 11.5 | 5 | ≤37 | 18 | 4Until Firefox 5, the passed object is serialized using JSON. Starting in Firefox 6, the object is serialized using [the structured clone algorithm](https://developer.mozilla.org/docs/DOM/The_structured_clone_algorithm). This allows a wider variety of objects to be safely passed. | 11.5 | 4 | 1.0 |
| `replaceState` | 5 | 12 | 4Until Firefox 5, the passed object is serialized using JSON. Starting in Firefox 6, the object is serialized using [the structured clone algorithm](https://developer.mozilla.org/docs/DOM/The_structured_clone_algorithm). This allows a wider variety of objects to be safely passed. | 10 | 11.5 | 5 | ≤37 | 18 | 4Until Firefox 5, the passed object is serialized using JSON. Starting in Firefox 6, the object is serialized using [the structured clone algorithm](https://developer.mozilla.org/docs/DOM/The_structured_clone_algorithm). This allows a wider variety of objects to be safely passed. | 11.5 | 4 | 1.0 |
| `scrollRestoration` | 46 | 79 | 46 | No | 33 | 11 | 46 | 46 | 46 | 33 | 11 | 5.0 |
| `state` | 19 | 12 | 4 | 10 | ≤12.1 | 6 | 4.4 | 25 | 4 | ≤12.1 | 6 | 1.5 |


See also
--------


* [`history`](window/history) global object


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/History>

HIDConnectionEvent
==================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `HIDConnectionEvent` interface of the [`WebHID API`](webhid_api) represents HID connection events, and is the event type passed to [`HID.onconnect`](hid/connect_event) and [`HID.ondisconnect`](hid/disconnect_event) when an input report is received.


 Event HIDConnectionEvent

Constructor
-----------


 
[`HIDConnectionEvent()`](hidconnectionevent/hidconnectionevent)  Experimental 
  Returns a new `HIDConnectionEvent` object. Typically this constructor is not used as events are created when an input report is received.

  
Instance properties
-------------------



*This interface also inherits properties from [`Event`](event).*

  
[`HIDConnectionEvent.device`](hidconnectionevent/device) Read only   Experimental 
  Returns the [`HIDDevice`](hiddevice) instance representing the device associated with the connection event.

  

Examples
--------



The following example registers event listeners for `connect` and `disconnect` events, then prints the [`HIDDevice.productName`](hiddevice/productname) to the console.

 
```
navigator.hid.addEventListener("connect", ({ device }) => {
  console.log(`HID connected: ${device.productName}`);
});

navigator.hid.addEventListener("disconnect", ({ device }) => {
  console.log(`HID disconnected: ${device.productName}`);
});

```


Specifications
--------------




| Specification |
| --- |
| [WebHID API # dom-hidconnectionevent](https://wicg.github.io/webhid/#dom-hidconnectionevent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HIDConnectionEvent` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `HIDConnectionEvent` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `device` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HIDConnectionEvent>

HIDInputReportEvent
===================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `HIDInputReportEvent` interface of the [`WebHID API`](webhid_api) is passed to [`HIDDevice.inputreport_event`](hiddevice/inputreport_event) when an input report is received from any associated HID device.


 Event HIDInputReportEvent

Instance properties
-------------------



*This interface also inherits properties from [`Event`](event).*

  
[`HIDInputReportEvent.data`](hidinputreportevent/data) Read only   Experimental 
  A [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) containing the data from the input report, excluding the `reportId` if the HID interface uses report IDs.

  
[`HIDInputReportEvent.device`](hidinputreportevent/device) Read only   Experimental 
  The [`HIDDevice`](hiddevice) instance that represents the HID interface that sent the input report.

  
[`HIDInputReportEvent.reportId`](hidinputreportevent/reportid) Read only   Experimental 
  The one-byte identification prefix for this report, or 0 if the HID interface does not use report IDs.

  

Instance methods
----------------


*This interface inherits methods from its parent, [`Event`](event).*


Examples
--------



The following example demonstrates listening for an `inputReport` that will allow the application to detect which button is pressed on a Joy-Con Right device. You can see more examples, and live demos in the article [Connecting to uncommon HID devices](https://web.dev/hid/).

 
```
device.addEventListener("inputreport", (event) => {
  const { data, device, reportId } = event;

  // Handle only the Joy-Con Right device and a specific report ID.
  if (device.productId !== 0x2007 && reportId !== 0x3f) return;

  const value = data.getUint8(0);
  if (value === 0) return;

  const someButtons = { 1: "A", 2: "X", 4: "B", 8: "Y" };
  console.log(`User pressed button ${someButtons[value]}.`);
});

```


Specifications
--------------




| Specification |
| --- |
| [WebHID API # dom-hidinputreportevent](https://wicg.github.io/webhid/#dom-hidinputreportevent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HIDInputReportEvent` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `data` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `device` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `reportId` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HIDInputReportEvent>

Highlight
=========



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `Highlight` interface is used to represent a collection of [`Range`](range) instances to be styled using the [CSS Custom Highlight API](css_custom_highlight_api).

 To style arbitrary ranges in a page, instantiate a new `Highlight` object, add one or more `Range` objects to it, and register it using the [`HighlightRegistry`](highlightregistry).

 A single `Highlight` object can hold one or more `Range` objects and behaves like a [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set).



Constructor
-----------


 
[`Highlight()`](highlight/highlight)  Experimental 
  Returns a newly created `Highlight` object.

  
Instance properties
-------------------



*The `Highlight` interface doesn't inherit any properties.*

  
[`Highlight.priority`](highlight/priority)  Experimental 
  A number that indicates the priority of this `Highlight` object. When multiple highlights overlap, the browser uses this priority to decide how to style the overlapping parts.

  
[`Highlight.size`](highlight/size) Read only   Experimental 
  Returns the number of ranges in the `Highlight` object.

  
[`Highlight.type`](highlight/type)  Experimental 
  An enumerated [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) used to specify the semantic meaning of the highlight. This allows assistive technologies to include this meaning when exposing the highlight to users.

  

Instance methods
----------------



*The `Highlight` interface doesn't inherit any methods*.

  
[`Highlight.add()`](highlight/add)  Experimental 
  Add a new range to this highlight.

  
[`Highlight.clear()`](highlight/clear)  Experimental 
  Remove all ranges from this highlight.

  
[`Highlight.delete()`](highlight/delete)  Experimental 
  Remove a range from this highlight.

  
[`Highlight.entries()`](highlight/entries)  Experimental 
  Returns a new iterator object that contains each range in the highlight object, in insertion order.

  
[`Highlight.forEach()`](highlight/foreach)  Experimental 
  Calls the given callback once for each range in the highlight object, in insertion order.

  
[`Highlight.has()`](highlight/has)  Experimental 
  Returns a boolean asserting whether a range is present the highlight object or not.

  
[`Highlight.keys()`](highlight/keys)  Experimental 
  An alias for [`Highlight.values()`](highlight/values).

  
[`Highlight.values()`](highlight/values)  Experimental 
  Returns a new iterator object that yields the ranges in the highlight object in insertion order.

  

Examples
--------



The following example demonstrates how to create ranges, instantiate a new `Highlight` object for them, and register it to be styled on the page:

 
```
const parentNode = document.getElementById("foo");

// Create a couple of ranges.
const range1 = new Range();
range1.setStart(parentNode, 10);
range1.setEnd(parentNode, 20);

const range2 = new Range();
range2.setStart(parentNode, 40);
range2.setEnd(parentNode, 60);

// Create a custom highlight for these ranges.
const highlight = new Highlight(range1, range2);

// Register the ranges in the HighlightRegistry.
CSS.highlights.set("my-custom-highlight", highlight);

```
 The following CSS code snippet demonstrates how to style the registered custom highlight by using the [`::highlight`](https://developer.mozilla.org/en-US/docs/Web/CSS/::highlight) pseudo-element:

 
```
::highlight(my-custom-highlight) {
  background-color: peachpuff;
}

```


Specifications
--------------




| Specification |
| --- |
| [CSS Custom Highlight API Module Level 1 # highlight](https://w3c.github.io/csswg-drafts/css-highlight-api/#highlight) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@iterator` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `Highlight` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `Highlight` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `add` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `clear` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `delete` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `entries` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `forEach` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `has` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `keys` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `priority` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `size` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `type` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `values` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |


See also
--------


* [The CSS Custom Highlight API](css_custom_highlight_api)
* [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Highlight>

HighlightRegistry
=================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `HighlightRegistry` interface, accessed via [`CSS.highlights`](css/highlights), is a [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)-like object used to register [`Highlight`](highlight) objects to be styled using the [CSS Custom Highlight API](css_custom_highlight_api).



Instance properties
-------------------



*The `HighlightRegistry` interface doesn't inherit any properties.*

  
[`HighlightRegistry.size`](highlightregistry/size) Read only   Experimental 
  Returns the number of `Highlight` objects currently registered.

  

Instance methods
----------------



*The `HighlightRegistry` interface doesn't inherit any methods*.

  
[`HighlightRegistry.clear()`](highlightregistry/clear)  Experimental 
  Remove all `Highlight` objects from the registry.

  
[`HighlightRegistry.delete()`](highlightregistry/delete)  Experimental 
  Remove the named `Highlight` object from the registry.

  
[`HighlightRegistry.entries()`](highlightregistry/entries)  Experimental 
  Returns a new iterator object that contains each `Highlight` object in the registry, in insertion order.

  
[`HighlightRegistry.forEach()`](highlightregistry/foreach)  Experimental 
  Calls the given callback once for each `Highlight` object in the registry, in insertion order.

  
[`HighlightRegistry.get()`](highlightregistry/get)  Experimental 
  Gets the named `Highlight` object from the registry.

  
[`HighlightRegistry.has()`](highlightregistry/has)  Experimental 
  Returns a boolean asserting whether a `Highlight` object is present the registry or not.

  
[`HighlightRegistry.keys()`](highlightregistry/keys)  Experimental 
  An alias for [`HighlightRegistry.values()`](highlightregistry/values).

  
[`HighlightRegistry.set()`](highlightregistry/set)  Experimental 
  Adds the given `Highlight` object to the registry with the given name, or updates the named `Highlight` object, if it already exists in the registry.

  
[`HighlightRegistry.values()`](highlightregistry/values)  Experimental 
  Returns a new iterator object that yields the `Highlight` objects in the registry, in insertion order.

  

Examples
--------


### Registering a highlight



The following example demonstrates how to create ranges, instantiate a new `Highlight` object for them, and register the highlight using the `HighlightRegistry`, to style it on the page:

 #### HTML

 
```
<p id="foo">CSS Custom Highlight API</p>

```
 #### CSS

 
```
::highlight(my-custom-highlight) {
  background-color: peachpuff;
}

```
 #### JavaScript

 
```
const text = document.getElementById("foo").firstChild;

if (!CSS.highlights) {
  text.textContent =
    "The CSS Custom Highlight API is not supported in this browser!";
}

// Create a couple of ranges.
const range1 = new Range();
range1.setStart(text, 0);
range1.setEnd(text, 3);

const range2 = new Range();
range2.setStart(text, 21);
range2.setEnd(text, 24);

// Create a custom highlight for these ranges.
const highlight = new Highlight(range1, range2);

// Register the ranges in the HighlightRegistry.
CSS.highlights.set("my-custom-highlight", highlight);

```
 #### Result




Specifications
--------------




| Specification |
| --- |
| [CSS Custom Highlight API Module Level 1 # highlight-registry](https://w3c.github.io/csswg-drafts/css-highlight-api/#highlight-registry) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@iterator` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `HighlightRegistry` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `clear` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `delete` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `entries` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `forEach` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `get` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `has` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `keys` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `set` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `size` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `values` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |


See also
--------


* [The CSS Custom Highlight API](css_custom_highlight_api)
* [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HighlightRegistry>

HmacImportParams
================


The `HmacImportParams` dictionary of the [Web Crypto API](web_crypto_api) represents the object that should be passed as the `algorithm` parameter into [`SubtleCrypto.importKey()`](subtlecrypto/importkey) or [`SubtleCrypto.unwrapKey()`](subtlecrypto/unwrapkey), when generating a key for the [HMAC](subtlecrypto/sign#hmac) algorithm.


Instance properties
-------------------


 `name`  A string. This should be set to `HMAC`.

  `hash`  A string representing the name of the [digest function](subtlecrypto/digest#supported_algorithms) to use. The can take a value of `SHA-256`, `SHA-384`, or `SHA-512`.

  **Warning:** Although you can technically pass `SHA-1` here, this is strongly discouraged as it is considered vulnerable.

   
`length` Optional
  A `Number` representing the length in bits of the key. If this is omitted the length of the key is equal to the length of the digest generated by the digest function you have chosen. Unless you have a good reason to use a different length, omit this property and use the default.

  
Examples
--------


See the examples for [`SubtleCrypto.importKey()`](subtlecrypto/importkey).


Specifications
--------------




| Specification |
| --- |
| [Web Cryptography API # dfn-HmacImportParams](https://w3c.github.io/webcrypto/#dfn-HmacImportParams) |


Browser compatibility
---------------------


See also
--------


* [`SubtleCrypto.importKey()`](subtlecrypto/importkey).
* [`SubtleCrypto.unwrapKey()`](subtlecrypto/unwrapkey).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HmacImportParams>

HmacKeyGenParams
================


The `HmacKeyGenParams` dictionary of the [Web Crypto API](web_crypto_api) represents the object that should be passed as the `algorithm` parameter into [`SubtleCrypto.generateKey()`](subtlecrypto/generatekey), when generating a key for the [HMAC](subtlecrypto/sign#hmac) algorithm.


Instance properties
-------------------


 `name`  A string. This should be set to `HMAC`.

  `hash`  A string representing the name of the [digest function](subtlecrypto/digest#supported_algorithms) to use. You can pass any of `SHA-1`, `SHA-256`, `SHA-384`, or `SHA-512` here.

  
`length` Optional
  A `Number` — the length in bits of the key. If this is omitted, the length of the key is equal to the block size of the hash function you have chosen. Unless you have a good reason to use a different length, omit this property and use the default.

  
Examples
--------


See the examples for [`SubtleCrypto.generateKey()`](subtlecrypto/generatekey).


Specifications
--------------




| Specification |
| --- |
| [Web Cryptography API # dfn-HmacKeyGenParams](https://w3c.github.io/webcrypto/#dfn-HmacKeyGenParams) |


Browser compatibility
---------------------


See also
--------


* [`SubtleCrypto.generateKey()`](subtlecrypto/generatekey).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HmacKeyGenParams>

HTMLAnchorElement
=================



The `HTMLAnchorElement` interface represents hyperlink elements and provides special properties and methods (beyond those of the regular [`HTMLElement`](htmlelement) object interface that they inherit from) for manipulating the layout and presentation of such elements. This interface corresponds to [`<a>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a) element; not to be confused with [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link), which is represented by [`HTMLLinkElement`](htmllinkelement))


 EventTarget Node Element HTMLElement HTMLAnchorElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  [`HTMLElement.accessKey`](htmlelement/accesskey)  A string representing a single character that switches input focus to the hyperlink.

  [`HTMLAnchorElement.download`](htmlanchorelement/download)  A string indicating that the linked resource is intended to be downloaded rather than displayed in the browser. The value represent the proposed name of the file. If the name is not a valid filename of the underlying OS, browser will adapt it.

  [`HTMLAnchorElement.hash`](htmlanchorelement/hash)  A string representing the fragment identifier, including the leading hash mark ('`#`'), if any, in the referenced URL.

  [`HTMLAnchorElement.host`](htmlanchorelement/host)  A string representing the hostname and port (if it's not the default port) in the referenced URL.

  [`HTMLAnchorElement.hostname`](htmlanchorelement/hostname)  A string representing the hostname in the referenced URL.

  [`HTMLAnchorElement.href`](htmlanchorelement/href)  A string that is the result of parsing the [`href`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#href) HTML attribute relative to the document, containing a valid URL of a linked resource.

  `HTMLAnchorElement.hreflang`  A string that reflects the [`hreflang`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#hreflang) HTML attribute, indicating the language of the linked resource.

  
[`HTMLAnchorElement.origin`](htmlanchorelement/origin) Read only 
  Returns a string containing the origin of the URL, that is its scheme, its domain and its port.

  [`HTMLAnchorElement.password`](htmlanchorelement/password)  A string containing the password specified before the domain name.

  [`HTMLAnchorElement.pathname`](htmlanchorelement/pathname)  A string containing an initial `'/'` followed by the path of the URL, not including the query string or fragment.

  [`HTMLAnchorElement.port`](htmlanchorelement/port)  A string representing the port component, if any, of the referenced URL.

  [`HTMLAnchorElement.protocol`](htmlanchorelement/protocol)  A string representing the protocol component, including trailing colon ('`:`'), of the referenced URL.

  [`HTMLAnchorElement.referrerPolicy`](htmlanchorelement/referrerpolicy)  A string that reflects the [`referrerpolicy`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#referrerpolicy) HTML attribute indicating which referrer to use.

  [`HTMLAnchorElement.rel`](htmlanchorelement/rel)  A string that reflects the [`rel`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#rel) HTML attribute, specifying the relationship of the target object to the linked object.

  
[`HTMLAnchorElement.relList`](htmlanchorelement/rellist) Read only 
  Returns a [`DOMTokenList`](domtokenlist) that reflects the [`rel`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#rel) HTML attribute, as a list of tokens.

  [`HTMLAnchorElement.search`](htmlanchorelement/search)  A string representing the search element, including leading question mark ('`?`'), if any, of the referenced URL.

  [`HTMLElement.tabIndex`](htmlelement/tabindex)  A `long` containing the position of the element in the tabbing navigation order for the current document.

  `HTMLAnchorElement.target`  A string that reflects the [`target`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#target) HTML attribute, indicating where to display the linked resource.

  `HTMLAnchorElement.text`  A string being a synonym for the [`Node.textContent`](node/textcontent) property.

  `HTMLAnchorElement.type`  A string that reflects the [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#type) HTML attribute, indicating the MIME type of the linked resource.

  [`HTMLAnchorElement.username`](htmlanchorelement/username)  A string containing the username specified before the domain name.

  

### Obsolete properties


 
`HTMLAnchorElement.charset`  Deprecated 
  A string representing the character encoding of the linked resource.

  
`HTMLAnchorElement.coords`  Deprecated 
  A string representing a comma-separated list of coordinates.

  
`HTMLAnchorElement.name`  Deprecated 
  A string representing the anchor name.

  
`HTMLAnchorElement.rev`  Deprecated 
  A string representing that the [`rev`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#rev) HTML attribute, specifying the relationship of the link object to the target object.

  **Note:** Currently the W3C HTML 5.2 spec states that `rev` is no longer obsolete, whereas the WHATWG living standard still has it labeled obsolete. Until this discrepancy is resolved, you should still assume it is obsolete.

   
`HTMLAnchorElement.shape`  Deprecated 
  A string representing the shape of the active area.

  
Instance methods
----------------



*Inherits methods from its parent, [`HTMLElement`](htmlelement).*

  [`HTMLElement.blur`](htmlelement/blur)  Removes the keyboard focus from the current element.

  [`HTMLElement.focus`](htmlelement/focus)  Gives the keyboard focus to the current element.

  [`HTMLAnchorElement.toString()`](htmlanchorelement/tostring)  Returns a string containing the whole URL. It is a synonym for [`HTMLAnchorElement.href`](htmlanchorelement/href), though it can't be used to modify the value.

   The `blur()` and `focus()` methods are inherited from [`HTMLElement`](htmlelement).



Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlanchorelement](https://html.spec.whatwg.org/multipage/text-level-semantics.html#htmlanchorelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLAnchorElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `attributionSourceId` | No | No | No | No | No | 15.414.1–15.4 | No | No | No | No | 15.414.5–15.4 | No |
| `charset` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `coords` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `download` | 15 | 13 | 20 | No | 15 | 10.1 | 4.4 | 18 | 20 | 14 | 10.3 | 1.0 |
| `hash` | 1 | 12 | 1From Firefox 29 to Firefox 40, the returned value was incorrectly percent-decoded. | 5.5 | 15 | 1 | 4.4 | 18 | 4From Firefox 29 to Firefox 40, the returned value was incorrectly percent-decoded. | 14 | 1 | 1.0 |
| `host` | 1 | 12 | 1 | 5.5In Internet Explorer 9, the host of an [`<a>`](https://developer.mozilla.org/docs/Web/HTML/Element/a) always include the port (e.g. `developer.mozilla.org:443`), even if there is no explicit port in the `href` attribute value. | 15 | 1 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `hostname` | 1 | 12 | 1 | 5.5 | 15 | 1 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `href` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `hreflang` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `name` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `origin` | 8 | 17 | 26Before Firefox 49, results for URL using the `blob` scheme incorrectly returned `null`. | No | 15 | 5.1 | 3 | 18 | 26Before Firefox 49, results for URL using the `blob` scheme incorrectly returned `null`. | 14 | 5 | 1.0 |
| `password` | 32 | 79 | 26 | No | 19 | 10 | 4.4.3 | 32 | 26 | 19 | 10 | 2.0 |
| `pathname` | 1 | 12 | 1Before Firefox 53, the `pathname` and `search` `HTMLHyperlinkElementUtils` properties returned the wrong parts of the URL. For example, for a URL of `http://z.com/x?a=true&b=false`, `pathname` would return `'/x?a=true&b=false'` and `search` would return '', rather than `'/x'` and `'?a=true&b=false'` respectively. This has now been fixed. | 5.5 | 15 | 1 | 4.4 | 18 | 4Before Firefox 53, the `pathname` and `search` `HTMLHyperlinkElementUtils` properties returned the wrong parts of the URL. For example, for a URL of `http://z.com/x?a=true&b=false`, `pathname` would return `'/x?a=true&b=false'` and `search` would return '', rather than `'/x'` and `'?a=true&b=false'` respectively. This has now been fixed. | 14 | 1 | 1.0 |
| `ping` | 12 | 17 | 1 | No | 15 | 5.1 | ≤37 | 18 | 4 | 14 | 5 | 1.0 |
| `port` | 1 | 12 | 1 | 5.5 | 15 | 1 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `protocol` | 1 | 12 | 1 | 5.5 | 15 | 1 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `referrerPolicy` | 5251–52 | 79 | 50 | No | 3938–39 | 14 | 5251–52 | 5251–52 | 50 | 41 | 14 | 6.05.0–6.0 |
| `rel` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `relList` | 65 | 18 | 30 | No | 52 | 9 | 65 | 65 | 30 | 47 | 9 | 9.0 |
| `rev` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `search` | 1 | 12 | 1Before Firefox 53, the `pathname` and `search` `HTMLHyperlinkElementUtils` properties returned the wrong parts of the URL. For example, for a URL of `http://z.com/x?a=true&b=false`, `pathname` would return `'/x?a=true&b=false'` and `search` would return '', rather than `'/x'` and `'?a=true&b=false'` respectively. This has now been fixed. | 5.5 | 15 | 1 | 4.4 | 18 | 4Before Firefox 53, the `pathname` and `search` `HTMLHyperlinkElementUtils` properties returned the wrong parts of the URL. For example, for a URL of `http://z.com/x?a=true&b=false`, `pathname` would return `'/x?a=true&b=false'` and `search` would return '', rather than `'/x'` and `'?a=true&b=false'` respectively. This has now been fixed. | 14 | 1 | 1.0 |
| `shape` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `target` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `text` | 1 | 12 | 1 | 10 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `toString` | 52 | 12 | 22 | 5.5 | 39 | 3 | 52 | 52 | 22 | 41 | 1 | 6.0 |
| `type` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `username` | 32 | 79 | 26 | No | 19 | 10 | 4.4.3 | 32 | 26 | 19 | 10 | 2.0 |


See also
--------


* The HTML element implementing this interface: [`<a>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement>

HTMLAreaElement
===============



The `HTMLAreaElement` interface provides special properties and methods (beyond those of the regular object [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating the layout and presentation of [`<area>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area) elements.


 EventTarget Node Element HTMLElement HTMLAreaElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  [`HTMLElement.accessKey`](htmlelement/accesskey)  A string containing a single character that switches input focus to the control.

  `HTMLAreaElement.alt`  A string that reflects the [`alt`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area#alt) HTML attribute, containing alternative text for the element.

  `HTMLAreaElement.coords`  A string that reflects the [`coords`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area#coords) HTML attribute, containing coordinates to define the hot-spot region.

  `HTMLAreaElement.download`  A string indicating that the linked resource is intended to be downloaded rather than displayed in the browser. The value represent the proposed name of the file. If the name is not a valid filename of the underlying OS, browser will adapt it.

  [`HTMLAreaElement.hash`](htmlareaelement/hash)  A string containing the fragment identifier (including the leading hash mark (#)), if any, in the referenced URL.

  [`HTMLAreaElement.host`](htmlareaelement/host)  A string containing the hostname and port (if it's not the default port) in the referenced URL.

  [`HTMLAreaElement.hostname`](htmlareaelement/hostname)  A string containing the hostname in the referenced URL.

  [`HTMLAreaElement.href`](htmlareaelement/href)  A string containing that reflects the [`href`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area#href) HTML attribute, containing a valid URL of a linked resource.

  
`HTMLAreaElement.noHref`  Deprecated 
  A boolean flag indicating if the area is inactive (`true`) or active (`false`).

  
[`HTMLAreaElement.origin`](htmlareaelement/origin) Read only 
  Returns a string containing the origin of the URL, that is its scheme, its domain and its port.

  [`HTMLAreaElement.password`](htmlareaelement/password)  A string containing the password specified before the domain name.

  [`HTMLAreaElement.pathname`](htmlareaelement/pathname)  A string containing the path name component, if any, of the referenced URL.

  [`HTMLAreaElement.port`](htmlareaelement/port)  A string containing the port component, if any, of the referenced URL.

  [`HTMLAreaElement.protocol`](htmlareaelement/protocol)  A string containing the protocol component (including trailing colon `':'`), of the referenced URL.

  [`HTMLAreaElement.referrerPolicy`](htmlareaelement/referrerpolicy)  A string that reflects the [`referrerpolicy`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area#referrerpolicy) HTML attribute indicating which referrer to use when fetching the linked resource.

  [`HTMLAreaElement.rel`](htmlareaelement/rel)  A string that reflects the [`rel`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area#rel) HTML attribute, indicating relationships of the current document to the linked resource.

  
[`HTMLAreaElement.relList`](htmlareaelement/rellist) Read only 
  Returns a [`DOMTokenList`](domtokenlist) that reflects the [`rel`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area#rel) HTML attribute, indicating relationships of the current document to the linked resource, as a list of tokens.

  [`HTMLAreaElement.search`](htmlareaelement/search)  A string containing the search element (including leading question mark `'?'`), if any, of the referenced URL.

  `HTMLAreaElement.shape`  A string that reflects the [`shape`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area#shape) HTML attribute, indicating the shape of the hot-spot, limited to known values.

  [`HTMLElement.tabIndex`](htmlelement/tabindex)  A `long` containing the element's position in the tabbing order.

  `HTMLAreaElement.target`  A string that reflects the [`target`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area#target) HTML attribute, indicating the browsing context in which to open the linked resource.

  [`HTMLAreaElement.username`](htmlareaelement/username)  A string containing the username specified before the domain name.

  

Instance methods
----------------



*Inherits methods from its parent, [`HTMLElement`](htmlelement).*

  [`HTMLAreaElement.toString()`](htmlareaelement/tostring)  Returns a string containing the whole URL. It is a synonym for [`HTMLAreaElement.href`](htmlareaelement/href).

  

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlareaelement](https://html.spec.whatwg.org/multipage/image-maps.html#htmlareaelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLAreaElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `alt` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `coords` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `download` | 54 | 13 | 20 | No | 41 | 10.1 | 54 | 54 | 20 | 41 | 10.3 | 6.0 |
| `hash` | 1 | 12 | 1From Firefox 29 to Firefox 40, the returned value was incorrectly percent-decoded. | 5.5 | 15 | 1 | 4.4 | 18 | 4From Firefox 29 to Firefox 40, the returned value was incorrectly percent-decoded. | 14 | 1 | 1.0 |
| `host` | 1 | 12 | 1 | 5.5In Internet Explorer 9, the host of an [`<a>`](https://developer.mozilla.org/docs/Web/HTML/Element/a) always include the port (e.g. `developer.mozilla.org:443`), even if there is no explicit port in the `href` attribute value. | 15 | 1 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `hostname` | 1 | 12 | 1 | 5.5 | 15 | 1 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `href` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `noHref` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `origin` | 32 | 17 | 26Before Firefox 49, results for URL using the `blob` scheme incorrectly returned `null`. | No | 19 | 10 | ≤37 | 32 | 26Before Firefox 49, results for URL using the `blob` scheme incorrectly returned `null`. | 19 | 10 | 2.0 |
| `password` | 32 | 79 | 26 | No | 19 | 10 | 4.4.3 | 32 | 26 | 19 | 10 | 2.0 |
| `pathname` | 1 | 12 | 1Before Firefox 53, the `pathname` and `search` `HTMLHyperlinkElementUtils` properties returned the wrong parts of the URL. For example, for a URL of `http://z.com/x?a=true&b=false`, `pathname` would return `'/x?a=true&b=false'` and `search` would return '', rather than `'/x'` and `'?a=true&b=false'` respectively. This has now been fixed. | 5.5 | 15 | 1 | 4.4 | 18 | 4Before Firefox 53, the `pathname` and `search` `HTMLHyperlinkElementUtils` properties returned the wrong parts of the URL. For example, for a URL of `http://z.com/x?a=true&b=false`, `pathname` would return `'/x?a=true&b=false'` and `search` would return '', rather than `'/x'` and `'?a=true&b=false'` respectively. This has now been fixed. | 14 | 1 | 1.0 |
| `ping` | 12 | 17 | 1 | No | 15 | 5.1 | ≤37 | 18 | 4 | 14 | 5 | 1.0 |
| `port` | 1 | 12 | 1 | 5.5 | 15 | 1 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `protocol` | 1 | 12 | 1 | 5.5 | 15 | 1 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `referrerPolicy` | 5251–52 | 79 | 50 | No | 3938–39 | 14.1 | 5251–52 | 5251–52 | 50 | 41 | 14.5 | 6.05.0–6.0 |
| `rel` | 54 | 12 | 30 | 11 | 41 | 9 | 54 | 54 | 30 | 41 | 9 | 6.0 |
| `relList` | 65 | 18 | 30 | No | 41 | 9 | 65 | 65 | 30 | 41 | 9 | 9.0 |
| `search` | 1 | 12 | 1Before Firefox 53, the `pathname` and `search` `HTMLHyperlinkElementUtils` properties returned the wrong parts of the URL. For example, for a URL of `http://z.com/x?a=true&b=false`, `pathname` would return `'/x?a=true&b=false'` and `search` would return '', rather than `'/x'` and `'?a=true&b=false'` respectively. This has now been fixed. | 5.5 | 15 | 1 | 4.4 | 18 | 4Before Firefox 53, the `pathname` and `search` `HTMLHyperlinkElementUtils` properties returned the wrong parts of the URL. For example, for a URL of `http://z.com/x?a=true&b=false`, `pathname` would return `'/x?a=true&b=false'` and `search` would return '', rather than `'/x'` and `'?a=true&b=false'` respectively. This has now been fixed. | 14 | 1 | 1.0 |
| `shape` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `target` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `toString` | 32 | 12 | 22 | 5.5 | 19 | 10.1 | 4.4.3 | 32 | 22 | 19 | 10.3 | 2.0 |
| `username` | 32 | 79 | 26 | No | 19 | 10 | 4.4.3 | 32 | 26 | 19 | 10 | 2.0 |


See also
--------


* HTML element implementing this interface: [`<area>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLAreaElement>

HTMLAudioElement
================



The `HTMLAudioElement` interface provides access to the properties of [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) elements, as well as methods to manipulate them.

 This element is based on, and inherits properties and methods from, the [`HTMLMediaElement`](htmlmediaelement) interface.


 EventTarget Node Element HTMLElement HTMLMediaElement HTMLAudioElement

Constructor
-----------


 [`Audio()`](htmlaudioelement/audio)  Creates and returns a new `HTMLAudioElement` object, optionally starting the process of loading an audio file into it if the file URL is given.

  
Instance properties
-------------------


*No specific properties; inherits properties from its parent, [`HTMLMediaElement`](htmlmediaelement), and from [`HTMLElement`](htmlelement).*


Instance methods
----------------


*Inherits methods from its parent, [`HTMLMediaElement`](htmlmediaelement), and from [`HTMLElement`](htmlelement). It offers no methods of its own.*


Examples
--------


### Basic usage



You can create a `HTMLAudioElement` entirely with JavaScript using the [`Audio()`](htmlaudioelement/audio) constructor:

 
```
const audioElement = new Audio("car\_horn.wav");

```
 then you can invoke the `play()` method on the element

 
```
audioElement.play();

```
  **Note:** A common gotcha is trying to play an audio element immediately on page load. Modern browser's default autoplay policy will block that from happening. Refer to [Firefox](https://hacks.mozilla.org/2019/02/firefox-66-to-block-automatically-playing-audible-video-and-audio/) and [chrome](https://developer.chrome.com/blog/autoplay/) for best practices and work arounds.

  Some of the more commonly used properties of the audio element include [`src`](htmlmediaelement/src), [`currentTime`](htmlmediaelement/currenttime), [`duration`](htmlmediaelement/duration), [`paused`](htmlmediaelement/paused), [`muted`](htmlmediaelement/muted), and [`volume`](htmlmediaelement/volume). This snippet copies the audio file's duration to a variable:

 
```
const audioElement = new Audio("car\_horn.wav");
audioElement.addEventListener("loadeddata", () => {
  let duration = audioElement.duration;
  // The duration variable now holds the duration (in seconds) of the audio clip
});

```


Events
------


*Inherits methods from its parent, [`HTMLMediaElement`](htmlmediaelement), and from its ancestor [`HTMLElement`](htmlelement).* Listen to events using [`addEventListener()`](eventtarget/addeventlistener) or by assigning an event listener to the `oneventname` property of this interface.


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlaudioelement](https://html.spec.whatwg.org/multipage/media.html#htmlaudioelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Audio` | 4 | 12 | 3.5 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 3 | 1.0 |
| `HTMLAudioElement` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |


See also
--------


* [Web media technologies](https://developer.mozilla.org/en-US/docs/Web/Media)
* [Using audio and video in HTML](https://developer.mozilla.org/en-US/docs/Web/Media/HTML_media)
* HTML element implementing this interface: [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement>

HTMLBaseElement
===============



The `HTMLBaseElement` interface contains the base URI for a document. This object inherits all of the properties and methods as described in the [`HTMLElement`](htmlelement) interface.


 EventTarget Node Element HTMLElement HTMLBaseElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  `HTMLBaseElement.href`  A string that reflects the [`href`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base#href) HTML attribute, containing a base URL for relative URLs in the document.

  `HTMLBaseElement.target`  A string that reflects the [`target`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base#target) HTML attribute, containing a default target browsing context or frame for elements that do not have a target reference specified.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlbaseelement](https://html.spec.whatwg.org/multipage/semantics.html#htmlbaseelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLBaseElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `href` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `target` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* HTML element implementing this interface: [`<base>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLBaseElement>

HkdfParams
==========


The `HkdfParams` dictionary of the [Web Crypto API](web_crypto_api) represents the object that should be passed as the `algorithm` parameter into [`SubtleCrypto.deriveKey()`](subtlecrypto/derivekey), when using the [HKDF](subtlecrypto/derivekey#hkdf) algorithm.


Instance properties
-------------------


 `name`  A string. This should be set to `HKDF`.

  `hash`  A string representing the [digest algorithm](subtlecrypto/digest#supported_algorithms) to use. This may be one of:

 * `SHA-1`
* `SHA-256`
* `SHA-384`
* `SHA-512`

  `salt`  An [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), a [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), or a [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). The [HKDF specification](https://datatracker.ietf.org/doc/html/rfc5869) states that adding salt "adds significantly to the strength of HKDF". Ideally, the salt is a random or pseudo-random value with the same length as the output of the digest function. Unlike the input key material passed into `deriveKey()`, salt does not need to be kept secret.

  `info`  An [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), a [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), or a [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) representing application-specific contextual information. This is used to bind the derived key to an application or context, and enables you to derive different keys for different contexts while using the same input key material. It's important that this should be independent of the input key material itself. This property is required but may be an empty buffer.

  
Examples
--------


See the examples for [`SubtleCrypto.deriveKey()`](subtlecrypto/derivekey).


Specifications
--------------




| Specification |
| --- |
| [Web Cryptography API # dfn-HkdfParams](https://w3c.github.io/webcrypto/#dfn-HkdfParams) |


Browser compatibility
---------------------


See also
--------


* [`SubtleCrypto.deriveKey()`](subtlecrypto/derivekey).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HkdfParams>

HMDVRDevice
===========



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.


**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The `HMDVRDevice` interface of the [WebVR API](webvr_api) represents a head mounted display, providing access to information about each eye, and allowing us to modify the current field of view.



Instance methods
----------------


 
[`HMDVRDevice.getEyeParameters()`](hmdvrdevice/geteyeparameters)  Deprecated   Non-standard 
  Returns current parameters for the eye specified as its argument ("left" or "right") — such as field of view information — stored in a [`VREyeParameters`](vreyeparameters) object.

  
[`HMDVRDevice.setFieldOfView()`](hmdvrdevice/setfieldofview)  Deprecated   Non-standard 
  Sets the field of view for both eyes.

  
Instance properties
-------------------



*This interface doesn't define any properties of its own, but it does inherit the properties of its parent interface, [`VRDisplay`](vrdisplay).*

  
`VRDisplay.hardwareUnitId` Read only 
  Returns the distinct hardware ID for the overall hardware unit that this `VRDevice` is a part of. All devices that are part of the same physical piece of hardware will have the same `hardwareUnitId`.

  
[`VRDisplay.displayId`](vrdisplay/displayid) Read only 
  Returns the ID for this specific `VRDevice`. The ID shouldn't change across browser restarts, allowing configuration data to be saved based on it.

  
[`VRDisplay.displayName`](vrdisplay/displayname) Read only 
  A human-readable name to identify the `VRDevice`.

  

Examples
--------



The following example, taken from the WebVR spec, finds the first available `HMDVRDevice` and its associated [`PositionSensorVRDevice`](positionsensorvrdevice), if it has one.

 
```
navigator.getVRDevices().then((devices) => {
  for (const device of devices) {
    if (device instanceof HMDVRDevice) {
      gHMD = device;
      break;
    }
  }

  if (gHMD) {
    for (const device of devices) {
      if (
        device instanceof PositionSensorVRDevice &&
        device.hardwareUnitId === gHMD.hardwareUnitId
      ) {
        gPositionSensor = devices[i];
        break;
      }
    }
  }
});

```


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HMDVRDevice` | No | No | 39 | No | No | No | No | No | No | No | No | No |
| `getEyeParameters` | No | No | 39 | No | No | No | No | No | No | No | No | No |
| `setFieldOfView` | No | No | 39 | No | No | No | No | No | No | No | No | No |


See also
--------


* [WebVR API homepage](webvr_api).
* <https://mixedreality.mozilla.org/> — demos, downloads, and other resources from the Mozilla VR team.


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HMDVRDevice>

HTMLBodyElement
===============



The `HTMLBodyElement` interface provides special properties (beyond those inherited from the regular [`HTMLElement`](htmlelement) interface) for manipulating [`<body>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/body) elements.


 EventTarget Node Element HTMLElement HTMLBodyElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
`HTMLBodyElement.aLink`  Deprecated 
  A string that represents the color of active hyperlinks.

  
`HTMLBodyElement.background`  Deprecated 
  A string that represents the description of the location of the background image resource. Note that this is not an URI, though some older version of some browsers do expect it.

  
`HTMLBodyElement.bgColor`  Deprecated 
  A string that represents the background color for the document.

  
`HTMLBodyElement.link`  Deprecated 
  A string that represents the color of unvisited links.

  
`HTMLBodyElement.text`  Deprecated 
  A string that represents the foreground color of text.

  
`HTMLBodyElement.vLink`  Deprecated 
  A string that represents the color of visited links.

  

Instance methods
----------------


*No specific methods; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Event handlers
--------------



The [`HTMLElement`](htmlelement) events are inherited.

 The following [`Window`](window) `onXYZ` event handler properties are also available as aliases targeting the `window` object. However, it is advised to listen to them on the `window` object directly rather than on `HTMLBodyElement`.

  **Note:** Using `addEventListener()` on `HTMLBodyElement` will not work for the `onXYZ` event handlers listed below. Listen to the events on the [`window`](window) object instead.

   [`HTMLBodyElement.onafterprint`](window/afterprint_event)  Fired after the associated document has started printing or the print preview has been closed.

  [`HTMLBodyElement.onbeforeprint`](window/beforeprint_event)  Fired when the associated document is about to be printed or previewed for printing.

  [`HTMLBodyElement.onbeforeunload`](window/beforeunload_event)  Fired when the window, the document and its resources are about to be unloaded.

  [`HTMLBodyElement.ongamepadconnected`](window/gamepadconnected_event)  Fired when the browser detects that a gamepad has been connected or the first time a button/axis of the gamepad is used.

  [`HTMLBodyElement.ongamepaddisconnected`](window/gamepaddisconnected_event)  Fired when the browser detects that a gamepad has been disconnected.

  [`HTMLBodyElement.onhashchange`](window/hashchange_event)  Fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the `#` symbol).

  [`HTMLBodyElement.onlanguagechange`](window/languagechange_event)  Fired when the user's preferred language changes.

  [`HTMLBodyElement.onmessage`](window/message_event)  Fired when the window receives a message, for example from a call to [`Window.postMessage()`](window/postmessage) from another browsing context.

  [`HTMLBodyElement.onmessageerror`](window/messageerror_event)  Fired when the window receives a message that can't be deserialized.

  [`HTMLBodyElement.onoffline`](window/offline_event)  Fired when the browser has lost access to the network and the value of [`Navigator.onLine`](navigator/online) switches to `false`.

  [`HTMLBodyElement.ononline`](window/online_event)  Fired when the browser has gained access to the network and the value of [`Navigator.onLine`](navigator/online) switches to `true`.

  [`HTMLBodyElement.onpagehide`](window/pagehide_event)  Fired when the browser hides the current page in the process of presenting a different page from the session's history.

  [`HTMLBodyElement.onpageshow`](window/pageshow_event)  Fired when the browser displays the window's document due to navigation.

  [`HTMLBodyElement.onpopstate`](window/popstate_event)  Fired when the active history entry changes while the user navigates the session history.

  [`HTMLBodyElement.onrejectionhandled`](window/rejectionhandled_event)  Fired whenever a JavaScript [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) is rejected and the rejection has been handled.

  [`HTMLBodyElement.onstorage`](window/storage_event)  Fired when a storage area (`localStorage`) has been modified in the context of another document.

  [`HTMLBodyElement.onunhandledrejection`](window/unhandledrejection_event)  Fired whenever a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) is rejected but the rejection was not handled.

  [`HTMLBodyElement.onunload`](window/unload_event)  Fired when the document is being unloaded.

  

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlbodyelement](https://html.spec.whatwg.org/multipage/sections.html#htmlbodyelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLBodyElement` | 1 | 12 | 1 | 4 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `aLink` | 1 | 12 | 1 | 4 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `background` | 1 | 12 | 1 | 4 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `bgColor` | 1 | 12 | 1 | 4 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `link` | 1 | 12 | 1 | 4 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `text` | 1 | 12 | 1 | 4 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `vLink` | 1 | 12 | 1 | 4 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* HTML element implementing this interface: [`<body>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/body)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLBodyElement>

HTMLBRElement
=============



The `HTMLBRElement` interface represents an HTML line break element ([`<br>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/br)). It inherits from [`HTMLElement`](htmlelement).


 EventTarget Node Element HTMLElement HTMLBRElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
`HTMLBRElement.clear`  Deprecated 
  A string indicating the flow of text around floating objects.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement)*.


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlbrelement](https://html.spec.whatwg.org/multipage/text-level-semantics.html#htmlbrelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLBRElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `clear` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* HTML element implementing this interface: [`<br>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/br)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLBRElement>

HTMLButtonElement
=================



The `HTMLButtonElement` interface provides properties and methods (beyond the regular [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating [`<button>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button) elements.


 EventTarget Node Element HTMLElement HTMLButtonElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  `HTMLButtonElement.accessKey`  A string indicating the single-character keyboard key to give access to the button.

  `HTMLButtonElement.autofocus`  A boolean value indicating whether or not the control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form-associated element in a document can have this attribute specified.

  [`HTMLButtonElement.disabled`](htmlbuttonelement/disabled)  A boolean value indicating whether or not the control is disabled, meaning that it does not accept any clicks.

  
`HTMLButtonElement.form` Read only 
   An [`HTMLFormElement`](htmlformelement) reflecting the form that this button is associated with. If the button is a descendant of a form element, then this attribute is a reference to that form's associated `HTMLFormElement`. If the button is not a descendant of a form element, then the attribute can be a reference to any `HTMLFormElement` element in the same document it is related to, or the `null` value if none matches. 

  `HTMLButtonElement.formAction`  A string reflecting the URI of a resource that processes information submitted by the button. If specified, this attribute overrides the [`action`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#action) attribute of the [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) element that owns this element.

  `HTMLButtonElement.formEnctype`  A string reflecting the type of content that is used to submit the form to the server. If specified, this attribute overrides the [`enctype`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#enctype) attribute of the [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) element that owns this element.

  `HTMLButtonElement.formMethod`  A string reflecting the HTTP method that the browser uses to submit the form. If specified, this attribute overrides the [`method`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#method) attribute of the [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) element that owns this element.

  `HTMLButtonElement.formNoValidate`  A boolean value indicating that the form is not to be validated when it is submitted. If specified, this attribute overrides the [`novalidate`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#novalidate) attribute of the [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) element that owns this element.

  `HTMLButtonElement.formTarget`  A string reflecting a name or keyword indicating where to display the response that is received after submitting the form. If specified, this attribute overrides the [`target`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#target) attribute of the [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) element that owns this element.

  
[`HTMLButtonElement.labels`](htmlbuttonelement/labels) Read only 
  A [`NodeList`](nodelist) that represents a list of [`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label) elements that are labels for this button.

  
`HTMLButtonElement.menu`  Experimental 
  A [`HTMLMenuElement`](htmlmenuelement) representing the menu element to be displayed if the button is clicked and is of `type="menu"`.

  `HTMLButtonElement.name`  A string representing the name of the object when submitted with a form. If specified, it must not be the empty string.

  `HTMLButtonElement.tabIndex`  A `long` that represents this element's position in the tabbing order.

  `HTMLButtonElement.type`  A string indicating the behavior of the button. This is an enumerated attribute with the following possible values:

 * `submit`: The button submits the form. This is the default value if the attribute is not specified, or if it is dynamically changed to an empty or invalid value.
* `reset`: The button resets the form.
* `button`: The button does nothing.
* `menu`: The button displays a menu.  Experimental

  
`HTMLButtonElement.willValidate` Read only 
  A boolean value indicating whether the button is a candidate for constraint validation. It is `false` if any conditions bar it from constraint validation, including: its `type` property is `reset` or `button`; it has a [`<datalist>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist) ancestor; or the `disabled` property is set to `true`.

  
`HTMLButtonElement.validationMessage` Read only 
  A string representing the localized message that describes the validation constraints that the control does not satisfy (if any). This attribute is the empty string if the control is not a candidate for constraint validation (`willValidate` is `false`), or it satisfies its constraints.

  
`HTMLButtonElement.validity` Read only 
  A [`ValidityState`](validitystate) representing the validity states that this button is in.

  `HTMLButtonElement.value`  A string representing the current form control value of the button.

  

Instance methods
----------------


*Inherits methods from its parent, [`HTMLElement`](htmlelement)*.


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlbuttonelement](https://html.spec.whatwg.org/multipage/form-elements.html#htmlbuttonelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLButtonElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `checkValidity` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `disabled` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `form` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `formAction` | 9 | 12 | 4In Firefox 56, the implementation has been updated so that the `formAction` property returns the correct form submission URL, as per spec, when the associated button is being used to submit a form ([bug 1366361](https://bugzil.la/1366361)). | 10 | ≤12.1 | 5.1 | 3 | 18 | 4In Firefox 56, the implementation has been updated so that the `formAction` property returns the correct form submission URL, as per spec, when the associated button is being used to submit a form ([bug 1366361](https://bugzil.la/1366361)). | ≤12.1 | 5 | 1.0 |
| `formEnctype` | 9 | 12 | 4 | 10 | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `formMethod` | 9 | 12 | 4 | 10 | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `formNoValidate` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 |
| `formTarget` | 9 | 12 | 4 | 10 | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `labels` | 6 | 18 | 56 | No | ≤12.1 | 5.1 | 3 | 18 | 56 | ≤12.1 | 5 | 1.0 |
| `name` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `reportValidity` | 40 | 17 | 49 | No | 27 | 10.1 | 40 | 40 | 64 | 27 | 10.3 | 4.0 |
| `setCustomValidity` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `type` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `validationMessage` | 5 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 |
| `validity` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 |
| `value` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `willValidate` | 2 | 12 | 4 | 10 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3 | 1.0 |


See also
--------


* HTML element implementing this interface: [`<button>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLButtonElement>

HTMLCollection
==============



The `HTMLCollection` interface represents a generic collection (array-like object similar to [`arguments`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments)) of elements (in document order) and offers methods and properties for selecting from the list.

  **Note:** This interface is called `HTMLCollection` for historical reasons (before the modern DOM, collections implementing this interface could only have HTML elements as their items).

  An `HTMLCollection` in the HTML DOM is live; it is automatically updated when the underlying document is changed. For this reason it is a good idea to make a copy (e.g., using [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)) to iterate over if adding, moving, or removing nodes.

  **Note:** This interface was an [attempt to create an unmodifiable list](https://stackoverflow.com/questions/74630989/why-use-domstringlist-rather-than-an-array/74641156#74641156) and only continues to be supported to not break code that's already using it. Modern APIs use types that wrap around ECMAScript array types instead, so you can treat them like ECMAScript arrays, and at the same time impose additional semantics on their usage (such as making their items read-only).

 

Instance properties
-------------------


 
[`HTMLCollection.length`](htmlcollection/length) Read only 
  Returns the number of items in the collection.

  
Instance methods
----------------


 [`HTMLCollection.item()`](htmlcollection/item)  Returns the specific node at the given zero-based `index` into the list. Returns `null` if the `index` is out of range.

 An alternative to accessing `collection[i]` (which instead returns `undefined` when `i` is out-of-bounds). This is mostly useful for non-JavaScript DOM implementations.

  [`HTMLCollection.namedItem()`](htmlcollection/nameditem)  Returns the specific node whose ID or, as a fallback, name matches the string specified by `name`. Matching by name is only done as a last resort, only in HTML, and only if the referenced element supports the `name` attribute. Returns `null` if no node exists by the given name.

 An alternative to accessing `collection[name]` (which instead returns `undefined` when `name` does not exist). This is mostly useful for non-JavaScript DOM implementations.

  
Usage in JavaScript
-------------------



`HTMLCollection` also exposes its members directly as properties by both name and index. HTML IDs may contain `:` and `.` as valid characters, which would necessitate using bracket notation for property access. Currently `HTMLCollections` does not recognize purely numeric IDs, which would cause conflict with the array-style access, though HTML5 does permit these.

 For example, assuming there is one `<form>` element in the document and its `id` is `myForm`:

 
```
let elem1, elem2;

// document.forms is an HTMLCollection

elem1 = document.forms[0];
elem2 = document.forms.item(0);

alert(elem1 === elem2); // shows: "true"

elem1 = document.forms.myForm;
elem2 = document.forms.namedItem("myForm");

alert(elem1 === elem2); // shows: "true"

elem1 = document.forms["named.item.with.periods"];

```


Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-htmlcollection](https://dom.spec.whatwg.org/#interface-htmlcollection) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLCollection` | 1 | 12 | 1 | 8 | 8 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `item` | 1 | 12 | 1 | 8 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `length` | 1 | 12 | 1 | 8 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `namedItem` | 1 | 12 | 1 | 8 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* [`NodeList`](nodelist)
* [`HTMLFormControlsCollection`](htmlformcontrolscollection), [`HTMLOptionsCollection`](htmloptionscollection)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection>

HTMLDataElement
===============



The `HTMLDataElement` interface provides special properties (beyond the regular [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating [`<data>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/data) elements.


 EventTarget Node Element HTMLElement HTMLDataElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  [`HTMLDataElement.value`](htmldataelement/value)  A string reflecting the [`value`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/data#value) HTML attribute, containing a machine-readable form of the element's value.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmldataelement](https://html.spec.whatwg.org/multipage/text-level-semantics.html#htmldataelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLDataElement` | 62 | 14 | 22 | No | 49 | 10 | 62 | 62 | 22 | 46 | 10 | 8.0 |
| `value` | 62 | 14 | 22 | No | 49 | 10 | 62 | 62 | 22 | 46 | 10 | 8.0 |


See also
--------


* The HTML element implementing this interface: [`<data>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/data).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLDataElement>

HTMLDataListElement
===================



The `HTMLDataListElement` interface provides special properties (beyond the [`HTMLElement`](htmlelement) object interface it also has available to it by inheritance) to manipulate [`<datalist>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist) elements and their content.


 EventTarget Node Element HTMLElement HTMLDataListElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement)*.

  
`HTMLDataListElement.options` Read only 
  A [`HTMLCollection`](htmlcollection) representing a collection of the contained option elements.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmldatalistelement](https://html.spec.whatwg.org/multipage/form-elements.html#htmldatalistelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLDataListElement` | 20 | 12 | 4 | 10 | ≤12.1 | 12.1 | 4.4.3 | 25 | 4 | ≤12.1 | 12.2 | 1.5 |
| `options` | 20 | 12 | 4 | 10 | ≤12.1 | 12.1 | 4.4.3 | 25 | 4 | ≤12.1 | 12.2 | 1.5 |


See also
--------


* The HTML element implementing this interface: [`<datalist>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLDataListElement>

HTMLDetailsElement
==================



The `HTMLDetailsElement` interface provides special properties (beyond the regular [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating [`<details>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details) elements.


 EventTarget Node Element HTMLElement HTMLDetailsElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  [`HTMLDetailsElement.open`](htmldetailselement/open)  A boolean value reflecting the [`open`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details#open) HTML attribute, indicating whether or not the element's contents (not counting the [`<summary>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/summary)) is to be shown to the user.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Events
------



Listen to this event using [`addEventListener()`](eventtarget/addeventlistener) or by assigning an event listener to the `oneventname` property of this interface.

  [`toggle`](htmldetailselement/toggle_event)  Fired when the `open`/`closed` state of a [`<details>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details) element is toggled.

  

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmldetailselement](https://html.spec.whatwg.org/multipage/interactive-elements.html#htmldetailselement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLDetailsElement` | 10 | 79 | 49 | No | 15 | 6 | ≤37 | 18 | 49 | 14 | 6 | 1.0 |
| `open` | 10 | 79 | 49 | No | 15 | 6 | ≤37 | 18 | 49 | 14 | 6 | 1.0 |
| `toggle_event` | 36 | 79 | 49 | No | 23 | 10.1 | 37 | 36 | 49 | 24 | 10.3 | 3.0 |


See also
--------


* The HTML element implementing this interface: [`<details>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLDetailsElement>

HTMLCanvasElement
=================



The `HTMLCanvasElement` interface provides properties and methods for manipulating the layout and presentation of [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) elements. The `HTMLCanvasElement` interface also inherits the properties and methods of the [`HTMLElement`](htmlelement) interface.


 EventTarget Node Element HTMLElement HTMLCanvasElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  [`HTMLCanvasElement.height`](htmlcanvaselement/height)  The [`height`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas#height) HTML attribute of the [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element is a positive `integer` reflecting the number of logical pixels (or RGBA values) going down one column of the canvas. When the attribute is not specified, or if it is set to an invalid value, like a negative, the default value of `150` is used. If no [separate] CSS height is assigned to the [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas), then this value will also be used as the height of the canvas in the length-unit CSS Pixel.

  [`HTMLCanvasElement.width`](htmlcanvaselement/width)  The [`width`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas#width) HTML attribute of the [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element is a positive `integer` reflecting the number of logical pixels (or RGBA values) going across one row of the canvas. When the attribute is not specified, or if it is set to an invalid value, like a negative, the default value of `300` is used. If no [separate] CSS width is assigned to the [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas), then this value will also be used as the width of the canvas in the length-unit CSS Pixel.

  
[`HTMLCanvasElement.mozOpaque`](htmlcanvaselement/mozopaque)  Non-standard   Deprecated 
  A boolean value reflecting the [`moz-opaque`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas#moz-opaque) HTML attribute of the [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element. It lets the canvas know whether or not translucency will be a factor. If the canvas knows there's no translucency, painting performance can be optimized. This is only supported in Mozilla-based browsers; use the standardized [`canvas.getContext('2d', { alpha: false })`](htmlcanvaselement/getcontext) instead.

  
`HTMLCanvasElement.mozPrintCallback`  Non-standard 
  A `function` that is Initially null. Web content can set this to a JavaScript function that will be called when the canvas is to be redrawn while the page is being printed. When called, the callback is passed a "printState" object that implements the [MozCanvasPrintState](https://searchfox.org/mozilla-central/search?q=interface%20MozCanvasPrintState&path=HTMLCanvasElement.webidl) interface. The callback can get the context to draw to from the printState object and must then call done() on it when finished. The purpose of `mozPrintCallback` is to obtain a higher resolution rendering of the canvas at the resolution of the printer being used. [See this blog post.](https://blog.mozilla.org/labs/2012/09/a-new-way-to-control-printing-output/)

  

Instance methods
----------------



*Inherits methods from its parent, [`HTMLElement`](htmlelement).*

  [`HTMLCanvasElement.captureStream()`](htmlcanvaselement/capturestream)  Returns a [`CanvasCaptureMediaStreamTrack`](canvascapturemediastreamtrack) that is a real-time video capture of the surface of the canvas.

  [`HTMLCanvasElement.getContext()`](htmlcanvaselement/getcontext)  Returns a drawing context on the canvas, or null if the context ID is not supported. A drawing context lets you draw on the canvas. Calling getContext with `"2d"` returns a [`CanvasRenderingContext2D`](canvasrenderingcontext2d) object, whereas calling it with `"webgl"` (or `"experimental-webgl"`) returns a [`WebGLRenderingContext`](webglrenderingcontext) object. This context is only available on browsers that implement [WebGL](webgl_api).

  [`HTMLCanvasElement.toDataURL()`](htmlcanvaselement/todataurl)  Returns a data-URL containing a representation of the image in the format specified by the `type` parameter (defaults to `png`). The returned image is in a resolution of 96dpi.

  [`HTMLCanvasElement.toBlob()`](htmlcanvaselement/toblob)  Creates a [`Blob`](blob) object representing the image contained in the canvas; this file may be cached on the disk or stored in memory at the discretion of the user agent.

  [`HTMLCanvasElement.transferControlToOffscreen()`](htmlcanvaselement/transfercontroltooffscreen)  Transfers control to an [`OffscreenCanvas`](offscreencanvas) object, either on the main thread or on a worker.

  

Events
------



Listen to these events using [`addEventListener()`](eventtarget/addeventlistener).

  
[`contextlost`](htmlcanvaselement/contextlost_event)  Experimental 
  Fired if the user agent detects that the backing storage associated with a `CanvasRenderingContext2D` or an `OffscreenCanvasRenderingContext2D` context has been lost.

  
[`contextrestored`](htmlcanvaselement/contextrestored_event)  Experimental 
  Fired if the user agent successfully restores a `CanvasRenderingContext2D` or an `OffscreenCanvasRenderingContext2D` context.

  [`webglcontextcreationerror`](htmlcanvaselement/webglcontextcreationerror_event)  Fired if the user agent is unable to create a `WebGLRenderingContext` or `WebGL2RenderingContext` context.

  [`webglcontextlost`](htmlcanvaselement/webglcontextlost_event)  Fired if the user agent detects that the drawing buffer associated with a `WebGLRenderingContext` or `WebGL2RenderingContext` object has been lost.

  [`webglcontextrestored`](htmlcanvaselement/webglcontextrestored_event)  Fired if the user agent restores the drawing buffer for a `WebGLRenderingContext` or `WebGL2RenderingContext` object.

  

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlcanvaselement](https://html.spec.whatwg.org/multipage/canvas.html#htmlcanvaselement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLCanvasElement` | 1 | 12 | 1.5 | 9 | 9 | 2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `captureStream` | 51 | 79 | 43 | No | 36 | 11 | 51 | 51 | 43 | 36 | 11 | 5.0 |
| `contextlost_event` | 98 | 98 | No | No | 84 | No | 98 | 98 | No | 68 | No | 18.0 |
| `contextrestored_event` | 98 | 98 | No | No | 84 | No | 98 | 98 | No | 68 | No | 18.0 |
| `getContext` | 1 | 12 | 1.5 | 9 | 9 | 2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `height` | 1 | 12 | 1.5 | 9 | 9 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `mozOpaque` | No | No | 3.5 | No | No | No | No | No | 4 | No | No | No |
| `toBlob` | 50 | 7912–79 | 18 | 10 | 37 | 11 | 50 | 50 | 18 | 37 | 11 | 5.0 |
| `toDataURL` | 2 | 12 | 2 | 9 | 9 | 4 | ≤37 | 18 | 4 | 10.1 | 3 | 1.0 |
| `transferControlToOffscreen` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `webglcontextcreationerror_event` | 9 | 12 | 49 | 11 | 12 | 5.1 | 4.4 | 25 | 49 | 12 | 8 | 1.5 |
| `webglcontextlost_event` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4 | 25 | 4 | 12 | 8 | 1.5 |
| `webglcontextrestored_event` | 9 | 12 | 4 | 11 | 12 | 5.1 | 4.4 | 25 | 4 | 12 | 8 | 1.5 |
| `width` | 1 | 12 | 1.5 | 9 | 9 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |


See also
--------


* HTML element implementing this interface: [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement>

HTMLDialogElement
=================



The `HTMLDialogElement` interface provides methods to manipulate [`<dialog>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog) elements. It inherits properties and methods from the [`HTMLElement`](htmlelement) interface.


 EventTarget Node Element HTMLElement HTMLDialogElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  [`HTMLDialogElement.open`](htmldialogelement/open)  A boolean value reflecting the [`open`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog#open) HTML attribute, indicating whether the dialog is available for interaction.

  [`HTMLDialogElement.returnValue`](htmldialogelement/returnvalue)  A string that sets or returns the return value for the dialog.

  

Instance methods
----------------



*Inherits methods from its parent, [`HTMLElement`](htmlelement).*

  [`HTMLDialogElement.close()`](htmldialogelement/close)  Closes the dialog. An optional string may be passed as an argument, updating the `returnValue` of the dialog.

  [`HTMLDialogElement.show()`](htmldialogelement/show)  Displays the dialog modelessly, i.e. still allowing interaction with content outside of the dialog.

  [`HTMLDialogElement.showModal()`](htmldialogelement/showmodal)  Displays the dialog as a modal, over the top of any other dialogs that might be present. Everything outside the dialog are [inert](htmlelement/inert) with interactions outside the dialog being blocked.

  

Events
------


 [`cancel`](htmldialogelement/cancel_event)  Fired when the user dismisses the current open dialog with the escape key.

  [`close`](htmldialogelement/close_event)  Fired when the dialog is closed, whether with the escape key, the `HTMLDialogElement.close()` method, or via submitting a form within the dialog with [`method="dialog"`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#method).

  
Examples
--------


### Opening a modal dialog



The following example shows a button that, when clicked, opens a modal [`<dialog>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog) containing a form via the [`HTMLDialogElement.showModal()`](htmldialogelement/showmodal) function. While open, everything other than the modal dialog's contents is inert. From there you can click the *Cancel* button to close the dialog (via the [`HTMLDialogElement.close()`](htmldialogelement/close) function), or submit the form via the submit button. Selecting the cancel button closes the dialog, creating a [`close`](htmldialogelement/close_event) event, not a [`cancel`](htmldialogelement/cancel_event) event.

 #### HTML

 
```
<!-- pop-up dialog box, containing a form -->
<dialog id="favDialog">
  <form method="dialog">
    <p>
      <label for="favAnimal">Favorite animal:</label>
      <select id="favAnimal" name="favAnimal">
        <option></option>
        <option>Brine shrimp</option>
        <option>Red panda</option>
        <option>Spider monkey</option>
      </select>
    </p>
    <div>
      <button id="cancel" type="reset">Cancel</button>
      <button type="submit">Confirm</button>
    </div>
  </form>
</dialog>

<div>
  <button id="updateDetails">Update details</button>
</div>

```
 #### JavaScript

 
```
const updateButton = document.getElementById("updateDetails");
const cancelButton = document.getElementById("cancel");
const dialog = document.getElementById("favDialog");
dialog.returnValue = "favAnimal";

function openCheck(dialog) {
  if (dialog.open) {
    console.log("Dialog open");
  } else {
    console.log("Dialog closed");
  }
}

// Update button opens a modal dialog
updateButton.addEventListener("click", () => {
  dialog.showModal();
  openCheck(dialog);
});

// Form cancel button closes the dialog box
cancelButton.addEventListener("click", () => {
  dialog.close("animalNotChosen");
  openCheck(dialog);
});

```
 #### Result




Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmldialogelement](https://html.spec.whatwg.org/multipage/interactive-elements.html#htmldialogelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLDialogElement` | 37 | 79 | 98 | No | 24 | 15.4 | 37 | 37 | 98 | 24 | 15.4 | 3.0 |
| `cancel_event` | 37 | 79 | 98 | No | 24 | 15.4 | No | No | 98 | No | 15.4 | No |
| `close` | 37 | 79 | 98 | No | 24 | 15.4 | 37 | 37 | 98 | 24 | 15.4 | 3.0 |
| `close_event` | 37 | 79 | 98 | No | 24 | 15.4 | No | No | 98 | No | 15.4 | No |
| `open` | 37 | 79 | 98 | No | 24 | 15.4 | 37 | 37 | 98 | 24 | 15.4 | 3.0 |
| `returnValue` | 37 | 79 | 98 | No | 24 | 15.4 | 37 | 37 | 98 | 24 | 15.4 | 3.0 |
| `show` | 37 | 79 | 98 | No | 24 | 15.4 | 37 | 37 | 98 | 24 | 15.4 | 3.0 |
| `showModal` | 37 | 79 | 98 | No | 24 | 15.4 | 37 | 37 | 98 | 24 | 15.4 | 3.0 |


See also
--------


* The HTML element implementing this interface: [`<dialog>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement>

HTMLEmbedElement
================



The `HTMLEmbedElement` interface provides special properties (beyond the regular [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating [`<embed>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/embed) elements.

  **Note:** This topic describes the `HTMLEmbedElement` interface as defined in the standard. It does not address earlier, non-standardized version of the interface.

 
 EventTarget Node Element HTMLElement HTMLEmbedElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
`HTMLEmbedElement.align`  Deprecated 
  A string representing an enumerated property indicating alignment of the element's contents with respect to the surrounding context. The possible values are `"left"`, `"right"`, `"center"`, and `"justify"`.

  `HTMLEmbedElement.height`  A string reflecting the [`height`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/embed#height) HTML attribute, containing the displayed height of the resource.

  
`HTMLEmbedElement.name`  Deprecated 
  A string representing the name of the embedded object.

  `HTMLEmbedElement.src`  A string that reflects the [`src`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/embed#src) HTML attribute, containing the address of the resource.

  `HTMLEmbedElement.type`  A string that reflects the [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/embed#type) HTML attribute, containing the type of the resource.

  `HTMLEmbedElement.width`  A string that reflects the [`width`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/embed#width) HTML attribute, containing the displayed width of the resource.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlembedelement](https://html.spec.whatwg.org/multipage/iframe-embed-object.html#htmlembedelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLEmbedElement` | 1Starting with Chrome 58, this interface can no longer be called as a function. | 12 | 1 | 5.5 | ≤12.1Starting with Opera 45, this interface can no longer be called as a function. | 3 | 4.4Starting with Chrome 58, this interface can no longer be called as a function. | 18Starting with Chrome 58, this interface can no longer be called as a function. | 4 | ≤12.1Starting with Opera 45, this interface can no longer be called as a function. | 1 | 1.0Starting with Samsung Internet 7.0, this interface can no longer be called as a function. |
| `align` | 1 | 79 | 1 | No | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `getSVGDocument` | 1 | 12 | 1.5 | 9 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `height` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `name` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `src` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `type` | 1 | 79 | 1 | No | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `width` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<embed>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/embed)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLEmbedElement>

HTMLFieldSetElement
===================



The `HTMLFieldSetElement` interface provides special properties and methods (beyond the regular [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating the layout and presentation of [`<fieldset>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset) elements.


 EventTarget Node Element HTMLElement HTMLFieldSetElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  `HTMLFieldSetElement.disabled`  A boolean value reflecting the [`disabled`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset#disabled) HTML attribute, indicating whether the user can interact with the control.

  
`HTMLFieldSetElement.elements` Read only 
  The elements belonging to this field set. The type of this property depends on the version of the spec that is implemented by the browser.

  
`HTMLFieldSetElement.form` Read only 
   An [`HTMLFormControlsCollection`](htmlformcontrolscollection) or [`HTMLCollection`](htmlcollection) referencing the containing form element, if this element is in a form. If the field set is not a descendant of a form element, then the attribute can be the ID of any form element in the same document it is related to, or the `null` value if none matches. 

  `HTMLFieldSetElement.name`  A string reflecting the [`name`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset#name) HTML attribute, containing the name of the field set. This can be used when accessing the field set in JavaScript. It is *not* part of the data which is sent to the server.

  
`HTMLFieldSetElement.type` Read only 
  The string "`fieldset`".

  `HTMLFieldSetElement.validationMessage`  A string representing a localized message that describes the validation constraints that the element does not satisfy (if any). This is the empty string if the element is not a candidate for constraint validation (`willValidate` is `false`), or it satisfies its constraints.

  `HTMLFieldSetElement.validity`  A [`ValidityState`](validitystate) representing the validity states that this element is in.

  `HTMLFieldSetElement.willValidate`  A boolean value `false`, because [`<fieldset>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset) objects are never candidates for constraint validation.

  

Instance methods
----------------



*Inherits methods from its parent, [`HTMLElement`](htmlelement).*

  `HTMLFieldSetElement.checkValidity()`  Always returns `true` because [`<fieldset>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset) objects are never candidates for constraint validation.

  `HTMLFieldSetElement.reportValidity()`  Always returns `true` because [`<fieldset>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset) objects are never candidates for constraint validation.

  `HTMLFieldSetElement.setCustomValidity()`  Sets a custom validity message for the field set. If this message is not the empty string, then the field set is suffering from a custom validity error, and does not validate.

  

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlfieldsetelement](https://html.spec.whatwg.org/multipage/form-elements.html#htmlfieldsetelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLFieldSetElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `checkValidity` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `disabled` | 20 | 12 | 4 | 5.5 | ≤12.1 | 6 | 4.4 | 25 | 4 | ≤12.1 | 6 | 1.5 |
| `elements` | 21 | 17 | 4 | No | ≤12.1 | 7 | 4.4 | 25 | 4 | ≤12.1 | 7 | 1.0 |
| `form` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `name` | 19 | 14 | 4 | No | 15 | 6 | 4.4 | 25 | 4 | 14 | 6 | 1.0 |
| `reportValidity` | 40 | 17 | 49 | No | 27 | 10.1 | 40 | 40 | 64 | 27 | 10.3 | 4.0 |
| `setCustomValidity` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `type` | 19 | 17 | 4 | No | 15 | 6 | 4.4 | 25 | 4 | 14 | 6 | 1.0 |
| `validationMessage` | 5 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 |
| `validity` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 |
| `willValidate` | 2 | 12 | 4 | 10 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<fieldset>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLFieldSetElement>

HTMLDivElement
==============



The `HTMLDivElement` interface provides special properties (beyond the regular [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating [`<div>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div) elements.


 EventTarget Node Element HTMLElement HTMLDivElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
`HTMLDivElement.align`  Deprecated 
  A string representing an enumerated property indicating alignment of the element's contents with respect to the surrounding context. The possible values are `"left"`, `"right"`, `"justify"`, and `"center"`.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmldivelement](https://html.spec.whatwg.org/multipage/grouping-content.html#htmldivelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLDivElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `align` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<div>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLDivElement>

HTMLDListElement
================



The `HTMLDListElement` interface provides special properties (beyond those of the regular [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating definition list ([`<dl>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dl)) elements.


 EventTarget Node Element HTMLElement HTMLDListElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
`HTMLDListElement.compact`  Deprecated 
  A boolean value indicating that spacing between list items should be reduced.

  

Instance methods
----------------


*No specific methods; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmldlistelement](https://html.spec.whatwg.org/multipage/grouping-content.html#htmldlistelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLDListElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `compact` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<dl>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dl)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLDListElement>

HTMLDocument
============


For historical reasons, [`Window`](window) objects have a `window.HTMLDocument` property whose value is the [`Document`](document) interface. So you can think of `HTMLDocument` as an alias for [`Document`](document), and you can find documentation for `HTMLDocument` members under the documentation for the [`Document`](document) interface.


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmldocument](https://html.spec.whatwg.org/multipage/window-object.html#htmldocument) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLDocument` | 1 | 12 | 1 | 4 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLDocument>

HTMLElement
===========



The `HTMLElement` interface represents any [HTML](https://developer.mozilla.org/en-US/docs/Web/HTML) element. Some elements directly implement this interface, while others implement it via an interface that inherits it.


 EventTarget Node Element HTMLElement

Instance properties
-------------------



*Inherits properties from its parent, [`Element`](element).*

  [`HTMLElement.accessKey`](htmlelement/accesskey)  A string representing the access key assigned to the element.

  
[`HTMLElement.accessKeyLabel`](htmlelement/accesskeylabel) Read only 
  Returns a string containing the element's assigned access key.

  
`HTMLElement.attributeStyleMap` Read only 
  A [`StylePropertyMap`](stylepropertymap) representing the declarations of the element's [`style`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#style) attribute.

  [`HTMLElement.contentEditable`](htmlelement/contenteditable)  A string, where a value of `true` means the element is editable and a value of `false` means it isn't.

  
[`HTMLElement.isContentEditable`](htmlelement/iscontenteditable) Read only 
  Returns a boolean value indicating whether or not the content of the element can be edited.

  
[`HTMLElement.dataset`](htmlelement/dataset) Read only 
  Returns a [`DOMStringMap`](domstringmap) with which script can read and write the element's [custom data attributes](https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes) (`data-*`) .

  [`HTMLElement.dir`](htmlelement/dir)  A string, reflecting the `dir` global attribute, representing the directionality of the element. Possible values are `"ltr"`, `"rtl"`, and `"auto"`.

  `HTMLElement.draggable`  A boolean value indicating if the element can be dragged.

  [`HTMLElement.enterKeyHint`](htmlelement/enterkeyhint)  A string defining what action label (or icon) to present for the enter key on virtual keyboards.

  [`HTMLElement.hidden`](htmlelement/hidden)  A string or boolean value reflecting the value of the element's [`hidden`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/hidden) attribute.

  [`HTMLElement.inert`](htmlelement/inert)  A boolean value indicating whether the user agent must act as though the given node is absent for the purposes of user interaction events, in-page text searches ("find in page"), and text selection.

  [`HTMLElement.innerText`](htmlelement/innertext)   Represents the rendered text content of a node and its descendants. As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied it to the clipboard. As a setter, it replaces the content inside the selected element, converting any line breaks into [`<br>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/br) elements. 

  [`HTMLElement.inputMode`](htmlelement/inputmode)  A string value reflecting the value of the element's [`inputmode`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/inputmode) attribute.

  
`HTMLElement.popover`  Experimental 
  A string value reflecting the value of the element's [`popover`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/popover) attribute.

  [`HTMLElement.lang`](htmlelement/lang)  A string representing the language of an element's attributes, text, and element contents.

  `HTMLElement.noModule`  A boolean value indicating whether an import script can be executed in user agents that support module scripts.

  [`HTMLElement.nonce`](htmlelement/nonce)  Returns the cryptographic number used once that is used by Content Security Policy to determine whether a given fetch will be allowed to proceed.

  
[`HTMLElement.offsetHeight`](htmlelement/offsetheight) Read only 
  Returns a `double` containing the height of an element, relative to the layout.

  
[`HTMLElement.offsetLeft`](htmlelement/offsetleft) Read only 
  Returns a `double`, the distance from this element's left border to its `offsetParent`'s left border.

  
[`HTMLElement.offsetParent`](htmlelement/offsetparent) Read only 
  An [`Element`](element) that is the element from which all offset calculations are currently computed.

  
[`HTMLElement.offsetTop`](htmlelement/offsettop) Read only 
  Returns a `double`, the distance from this element's top border to its `offsetParent`'s top border.

  
[`HTMLElement.offsetWidth`](htmlelement/offsetwidth) Read only 
  Returns a `double` containing the width of an element, relative to the layout.

  [`HTMLElement.outerText`](htmlelement/outertext)   Represents the rendered text content of a node and its descendants. As a getter, it is the same as [`HTMLElement.innerText`](htmlelement/innertext) (it represents the rendered text content of an element and its descendants). As a setter, it replaces the selected node and its contents with the given value, converting any line breaks into [`<br>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/br) elements. 

  
`HTMLElement.properties`  Experimental  Read only 
  Returns a `HTMLPropertiesCollection`…

  `HTMLElement.spellcheck`  A boolean value that controls [spell-checking](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/spellcheck). It is present on all HTML elements, though it doesn't have an effect on all of them.

  [`HTMLElement.style`](htmlelement/style)  A [`CSSStyleDeclaration`](cssstyledeclaration) representing the declarations of the element's [`style`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#style) attribute.

  [`HTMLElement.tabIndex`](htmlelement/tabindex)  A `long` representing the position of the element in the tabbing order.

  [`HTMLElement.title`](htmlelement/title)  A string containing the text that appears in a popup box when mouse is over the element.

  `HTMLElement.translate`  A boolean value representing the translation.

  

Instance methods
----------------



*Inherits methods from its parent, [`Element`](element).*

  [`HTMLElement.attachInternals()`](htmlelement/attachinternals)  Returns an [`ElementInternals`](elementinternals) object, and enables a custom element to participate in HTML forms.

  [`HTMLElement.blur()`](htmlelement/blur)  Removes keyboard focus from the currently focused element.

  [`HTMLElement.click()`](htmlelement/click)  Sends a mouse click event to the element.

  [`HTMLElement.focus()`](htmlelement/focus)  Makes the element the current keyboard focus.

  
[`HTMLElement.hidePopover()`](htmlelement/hidepopover)  Experimental 
  Hides the element, if it has a valid `HTMLElement.popover` value.

  
[`HTMLElement.showPopover()`](htmlelement/showpopover)  Experimental 
  Shows the element, promoting it to the top layer, if it has a valid `HTMLElement.popover` value.

  
[`HTMLElement.togglePopover()`](htmlelement/togglepopover)  Experimental 
  Hides or shows the element, if it has a valid `HTMLElement.popover` value.

  

Events
------



Listen to these events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface.

  [`copy`](htmlelement/copy_event)  Fired when the user initiates a copy action through the browser's user interface.

  [`cut`](htmlelement/cut_event)  Fired when the user initiates a cut action through the browser's user interface.

  [`paste`](htmlelement/paste_event)  Fired when the user initiates a paste action through the browser's user interface.

  [`invalid`](htmlinputelement/invalid_event)  Fired when an element does not satisfy its constraints during constraint validation.

  `beforetoggle`  Fired when the element is a popover, before it is hidden or shown.

  `toggle`  Fired when the element is a popover, just after it is hidden or shown.

  

### Animation events


 [`animationcancel`](element/animationcancel_event)  Fired when an animation unexpectedly aborts.

  [`animationend`](element/animationend_event)  Fired when an animation has completed normally.

  [`animationiteration`](element/animationiteration_event)  Fired when an animation iteration has completed.

  [`animationstart`](element/animationstart_event)  Fired when an animation starts.

  
### Input events


 [`beforeinput`](htmlelement/beforeinput_event)  Fired when the value of an [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input), [`<select>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select), or [`<textarea>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea) element is about to be modified.

  [`input`](htmlelement/input_event)  Fired when the `value` of an [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input), [`<select>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select), or [`<textarea>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea) element has been changed.

  [`change`](htmlelement/change_event)  Fired when the `value` of an [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input), [`<select>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select), or [`<textarea>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea) element has been changed and committed by the user. Unlike the [`input`](htmlelement/input_event) event, the `change` event is not necessarily fired for each alteration to an element's `value`.

  
### Pointer events


 [`gotpointercapture`](element/gotpointercapture_event)  Fired when an element captures a pointer using [`setPointerCapture()`](element/setpointercapture).

  [`lostpointercapture`](element/lostpointercapture_event)  Fired when a [captured pointer](pointer_events#pointer_capture) is released.

  [`pointercancel`](element/pointercancel_event)  Fired when a pointer event is canceled.

  [`pointerdown`](element/pointerdown_event)  Fired when a pointer becomes active.

  [`pointerenter`](element/pointerenter_event)  Fired when a pointer is moved into the hit test boundaries of an element or one of its descendants.

  [`pointerleave`](element/pointerleave_event)  Fired when a pointer is moved out of the hit test boundaries of an element.

  [`pointermove`](element/pointermove_event)  Fired when a pointer changes coordinates.

  [`pointerout`](element/pointerout_event)  Fired when a pointer is moved out of the *hit test* boundaries of an element (among other reasons).

  [`pointerover`](element/pointerover_event)  Fired when a pointer is moved into an element's hit test boundaries.

  [`pointerup`](element/pointerup_event)  Fired when a pointer is no longer active.

  
### Transition events


 [`transitioncancel`](element/transitioncancel_event)  Fired when a [CSS transition](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions) is canceled.

  [`transitionend`](element/transitionend_event)  Fired when a [CSS transition](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions) has completed.

  [`transitionrun`](element/transitionrun_event)  Fired when a [CSS transition](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions) is first created.

  [`transitionstart`](element/transitionstart_event)  Fired when a [CSS transition](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions) has actually started.

  
Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlelement](https://html.spec.whatwg.org/multipage/dom.html#htmlelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLElement` | 1 | 12 | 1 | 5.5 | 8 | 1 | 1 | 18 | 4 | 10.1 | 1 | 1.0 |
| `accessKey` | 17 | 12 | 5 | 5.5 | ≤12.1 | 6 | 4.4 | 18 | 5 | ≤12.1 | 6 | 1.0 |
| `accessKeyLabel` | NoSee [bug 393466](https://crbug.com/393466). | NoSee [bug 393466](https://crbug.com/393466). | 8 | No | NoSee [bug 393466](https://crbug.com/393466). | 14 | NoSee [bug 393466](https://crbug.com/393466). | NoSee [bug 393466](https://crbug.com/393466). | 8 | NoSee [bug 393466](https://crbug.com/393466). | 14 | NoSee [bug 393466](https://crbug.com/393466). |
| `attachInternals` | 77 | 79 | 93 | No | 64 | 16.4See [bug 197960](https://webkit.org/b/197960). | 77 | 77 | 93 | 55 | 16.4See [bug 197960](https://webkit.org/b/197960). | 12.0 |
| `attributeStyleMap` | 66 | 79 | No | No | 53 | 16.4 | 66 | 66 | No | 47 | 16.4 | 9.0 |
| `autocapitalize` | 66 | 79 | 111 | No | 53 | No | 66 | 66 | 111 | 47 | 10.3 | 9.0 |
| `autofocus` | 791–79Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. | 7912–79Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. | 1Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. | 10Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. | 66≤12.1–66Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. | 15.44Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. | 79≤37–79Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. | 7918–79Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. | 4Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. | 57≤12.1–57Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. | 15.43.2Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. | 12.01.0–12.0Supported for `HTMLButtonElement`, `HTMLInputElement`, `HTMLSelectElement`, and `HTMLTextAreaElement`. |
| `beforeinput_event` | 60 | 79 | 87 | No | 47 | 10.1 | 60 | 60 | 87 | 44 | 10.3 | 8.0 |
| `beforematch_event` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `beforetoggle_event` | 114 | 114 | No | No | No | No | 114 | 114 | No | No | No | No |
| `blur` | 1 | 12 | 1.5 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `change_event` | 1 | 12 | 1 | 9 | 9 | 3 | 4.4 | 18 | 4 | 10.1 | 2 | 1.0 |
| `click` | 9Before Chrome 19, `click()` is only defined on buttons and inputs. | 12 | 3["Before Firefox 5, `click()` is only defined on buttons and inputs, and has no effect on text and file inputs.", "Starting in Firefox 75, the `click()` function works even when the element is not attached to a DOM tree."] | 5.5 | 10.5 | 6 | 4.4Before Android WebView 4.4, `click()` is only defined on buttons and inputs. | 18Before Chrome 19, `click()` is only defined on buttons and inputs. | 4["Before Firefox 5, `click()` is only defined on buttons and inputs, and has no effect on text and file inputs.", "Starting in Firefox for Android 79, the `click()` function works even when the element is not attached to a DOM tree."] | 11 | 6 | 1.0Before Samsung Internet 1.5, `click()` is only defined on buttons and inputs. |
| `contentEditable` | 1 | 12 | 3 | 5.5 | 9 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `dataset` | 7 | 12 | 6 | 11 | 11 | 5.1 | 3 | 18 | 6 | 11 | 5 | 1.0 |
| `dir` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `drag_event` | 1 | 12 | 9 | 9 | 12 | 3.1 | 4.4 | 18 | 9 | 12 | 2 | 1.0 |
| `dragend_event` | 1 | 12 | 9 | 9 | 12 | 3.1 | 4.4 | 18 | 9 | 12 | 2 | 1.0 |
| `dragenter_event` | 1 | 12 | 9 | 9 | 12 | 3.1 | 4.4 | 18 | 9 | 12 | 2 | 1.0 |
| `dragexit_event` | No | 12–79 | 3.5 | 10 | 12 | 3.1 | No | No | 4 | No | No | No |
| `draggable` | 4 | 12 | 2 | 10 | 12 | 5 | 4.4 | 18 | 4 | 12 | 4 | 1.0 |
| `dragleave_event` | 1 | 12 | 9 | 9 | 12 | 3.1 | 4.4 | 18 | 9 | 12 | 2 | 1.0 |
| `dragover_event` | 1 | 12 | 9 | 9 | 12 | 3.1 | 4.4 | 18 | 9 | 12 | 2 | 1.0 |
| `dragstart_event` | 1 | 12 | 9 | 9 | 12 | 3.1 | 4.4 | 18 | 9 | 12 | 2 | 1.0 |
| `drop_event` | 1 | 12 | 9 | 9 | 12 | 3.1 | 4.4 | 18 | 9 | 12 | 2 | 1.0 |
| `enterKeyHint` | 77 | 79 | 94 | No | 64 | 13.1 | 77 | 77 | 94 | 55 | 13.4 | 12.0 |
| `focus` | 1 | 12 | 1.5 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `hidden` | 6 | 12 | 4 | 11 | 11.6 | 5.1 | 3 | 18 | 4 | 12 | 5 | 1.0 |
| `hidePopover` | 114 | 114 | No | No | No | No | 114 | 114 | No | No | No | No |
| `inert` | 102 | 102 | 112 | No | 88 | 15.5 | 102 | 102 | 112 | 70 | 15.5 | 19.0 |
| `innerText` | 1 | 12 | 45 | 5.5 | 9.6 | 1 | 1 | 18 | 45 | 10.1 | 1 | 1.0 |
| `inputMode` | 66 | 79 | 95 | No | 53 | 12.1 | 66 | 66 | 79 | 47 | 12.2 | 9.0 |
| `input_event` | 1 | 7912–79Not supported on `select`, `checkbox`, or `radio` inputs. | 6 | 9Only supports `input` of type `text` and `password`. | 11.6 | 3.1 | 4.4 | 18 | 6 | 12 | 2 | 1.0 |
| `isContentEditable` | 1 | 12 | 4 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `lang` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `nonce` | 61 | 79 | 75 | No | 48 | 10The property is defined only for its useful elements: `<link>`, `<script>`, and `<style>`; it is undefined for all other elements. | 61 | 61 | 79 | 45 | 10The property is defined only for its useful elements: `<link>`, `<script>`, and `<style>`; it is undefined for all other elements. | 8.0 |
| `offsetHeight` | 1 | 12 | 1 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `offsetLeft` | 1 | 12 | 1 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `offsetParent` | 1 | 12 | 1 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `offsetTop` | 1 | 12 | 1 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `offsetWidth` | 1 | 12 | 1 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `outerText` | 1 | 12 | 98 | 5.5 | ≤12.1 | 1.3 | 1 | 18 | 98 | ≤12.1 | 1 | 1.0 |
| `popover` | 114 | 114 | No | No | No | No | 114 | 114 | No | No | No | No |
| `showPopover` | 114 | 114 | No | No | No | No | 114 | 114 | No | No | No | No |
| `spellcheck` | 9 | 12 | 2 | 10 | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `style` | 1 | 12 | 1 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `tabIndex` | 1 | 1812Returns incorrect value for elements without an explicit tabindex attribute. See [issue 4365703](https://developer.microsoft.com/microsoft-edge/platform/issues/4365703/) for details. | 1 | 5.5Returns incorrect value for elements without an explicit tabindex attribute. See [issue 4365703](https://developer.microsoft.com/microsoft-edge/platform/issues/4365703/) for details. | ≤12.1 | 3.1 | 4.4 | 18 | 4 | ≤12.1 | 2 | 1.0 |
| `title` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `togglePopover` | 114 | 114 | No | No | No | No | 114 | 114 | No | No | No | No |
| `toggle_event` | 114 | 114 | No | No | No | No | 114 | 114 | No | No | No | No |
| `translate` | 19 | 79 | 111 | No | 15 | 6 | 4.4 | 25 | 111 | 14 | 6 | 1.5 |
| `virtualKeyboardPolicy` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |


See also
--------


* [`Element`](element)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement>

HTMLFontElement
===============



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 Implements the document object model (DOM) representation of the font element. The HTML Font Element [`<font>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/font) defines the font size, font face and color of text.


 EventTarget Node Element HTMLElement HTMLFontElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
[`HTMLFontElement.color`](htmlfontelement/color)  Deprecated 
  A string that reflects the [`color`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/font#color) HTML attribute, containing either a named color or a color specified in the hexadecimal #RRGGBB format.

  
[`HTMLFontElement.face`](htmlfontelement/face)  Deprecated 
  A string that reflects the [`face`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/font#face) HTML attribute, containing a comma-separated list of one or more font names.

  
[`HTMLFontElement.size`](htmlfontelement/size)  Deprecated 
  A string that reflects the [`size`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/font#size) HTML attribute, containing either a font size ranging from 1 to 7 or a number relative to the default value 3, for example -2 or +1.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlfontelement](https://html.spec.whatwg.org/multipage/obsolete.html#htmlfontelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLFontElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `color` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `face` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `size` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<font>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/font).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLFontElement>

HTMLFormControlsCollection
==========================



The `HTMLFormControlsCollection` interface represents a *collection* of HTML *form control elements*, returned by the [`HTMLFormElement`](htmlformelement) interface's [`elements`](htmlformelement/elements) property.

 This interface replaces one method from [`HTMLCollection`](htmlcollection), on which it is based.


 HTMLCollection HTMLFormControlsCollection

Instance properties
-------------------


*This interface inherits the properties of its parent, [`HTMLCollection`](htmlcollection).*


Instance methods
----------------



*This interface inherits the methods of its parent, [`HTMLCollection`](htmlcollection).*

  [`HTMLFormControlsCollection.namedItem()`](htmlformcontrolscollection/nameditem)  Returns the [`RadioNodeList`](radionodelist) or the [`Element`](element) in the collection whose `name` or `id` matches the specified name, or `null` if no nodes match. Note that this version of `namedItem()` hides the one inherited from [`HTMLCollection`](htmlcollection). Like that method, using the JavaScript array bracket syntax with a [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String), as in `collection["value"]`, is equivalent to `collection.namedItem("value")`.

  

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlformcontrolscollection](https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#htmlformcontrolscollection) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLFormControlsCollection` | 1 | 12 | 1 | No | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `namedItem` | 1 | 12 | 3327–33Returned a [`NodeList`](https://developer.mozilla.org/docs/Web/API/NodeList) instead of a [`RadioNodeList`](https://developer.mozilla.org/docs/Web/API/RadioNodeList). | No | ≤12.1 | ≤4 | 4.4 | 18 | 3327–33Returned a [`NodeList`](https://developer.mozilla.org/docs/Web/API/NodeList) instead of a [`RadioNodeList`](https://developer.mozilla.org/docs/Web/API/RadioNodeList). | ≤12.1 | 1 | 1.0 |


See also
--------


* [`HTMLCollection`](htmlcollection), [`RadioNodeList`](radionodelist), [`HTMLOptionsCollection`](htmloptionscollection)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormControlsCollection>

HTMLHeadElement
===============



The `HTMLHeadElement` interface contains the descriptive information, or metadata, for a document. This object inherits all of the properties and methods described in the [`HTMLElement`](htmlelement) interface.


 EventTarget Node Element HTMLElement HTMLHeadElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
`HTMLHeadElement.profile`  Deprecated 
  A string representing the URIs of one or more metadata profiles (white space separated).

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlheadelement](https://html.spec.whatwg.org/multipage/semantics.html#htmlheadelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLHeadElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `profile` | No | 12–79 | 1–4 | 6 | No | 1 | No | No | No | No | 1 | No |


See also
--------


* The HTML element implementing this interface: [`<head>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLHeadElement>

HTMLHRElement
=============



The `HTMLHRElement` interface provides special properties (beyond those of the [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating [`<hr>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/hr) elements.


 EventTarget Node Element HTMLElement HTMLHRElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
`HTMLHRElement.align`  Deprecated 
  A string, an enumerated attribute indicating alignment of the rule with respect to the surrounding context.

  
`HTMLHRElement.color`  Deprecated 
  A string representing the name of the color of the rule.

  
`HTMLHRElement.noshade`  Deprecated 
  A boolean value that sets the rule to have no shading.

  
`HTMLHRElement.size`  Deprecated 
  A string representing the height of the rule.

  
`HTMLHRElement.width`  Deprecated 
  A string representing the width of the rule on the page.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement)*.


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlhrelement](https://html.spec.whatwg.org/multipage/grouping-content.html#htmlhrelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLHRElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `align` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `color` | 33 | 12 | 1 | 6 | 20 | 10.1 | 4.4.3 | 33 | 4 | 20 | 10.3 | 2.0 |
| `noShade` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `size` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `width` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<hr>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/hr)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLHRElement>

HTMLHtmlElement
===============



The `HTMLHtmlElement` interface serves as the root node for a given HTML document. This object inherits the properties and methods described in the [`HTMLElement`](htmlelement) interface.

 You can retrieve the `HTMLHtmlElement` object for a given document by reading the value of the [`document.documentElement`](document/documentelement) property.


 EventTarget Node Element HTMLElement HTMLHtmlElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
[`HTMLHtmlElement.version`](htmlhtmlelement/version)  Deprecated 
  A string representing the version of the HTML Document Type Definition (DTD) that governs this document. This property should not be used any more as it is non-conforming. Omit it.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlhtmlelement](https://html.spec.whatwg.org/multipage/semantics.html#htmlhtmlelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLHtmlElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `version` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* HTML element implementing this interface: [`<html>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/html).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLHtmlElement>

HTMLIFrameElement
=================



The `HTMLIFrameElement` interface provides special properties and methods (beyond those of the [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating the layout and presentation of inline frame elements.


 EventTarget Node Element HTMLElement HTMLIFrameElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement)*.

  
`HTMLIFrameElement.align`  Deprecated 
  A string that specifies the alignment of the frame with respect to the surrounding context.

  `HTMLIFrameElement.allow`  A list of origins the frame is allowed to display content from. This attribute also accepts the values `self` and `src` which represent the origin in the iframe's src attribute. The default value is `src`.

  
`HTMLIFrameElement.allowfullscreen`  Experimental 
  A boolean value indicating whether the inline frame is willing to be placed into full screen mode. See [Using fullscreen mode](fullscreen_api) for details.

  
[`HTMLIFrameElement.allowPaymentRequest`](htmliframeelement/allowpaymentrequest)  Deprecated   Non-standard 
  A boolean value indicating whether the [Payment Request API](payment_request_api) may be invoked inside a cross-origin iframe.

  
[`HTMLIFrameElement.contentDocument`](htmliframeelement/contentdocument) Read only 
  Returns a [`Document`](document), the active document in the inline frame's nested browsing context.

  
[`HTMLIFrameElement.contentWindow`](htmliframeelement/contentwindow) Read only 
  Returns a [WindowProxy](https://developer.mozilla.org/en-US/docs/Glossary/WindowProxy), the window proxy for the nested browsing context.

  
[`HTMLIFrameElement.credentialless`](htmliframeelement/credentialless)  Experimental 
  A boolean value indicating whether the `<iframe>` is credentialless, meaning that its content is loaded in a new, ephemeral context. This context does not have access to the parent context's shared storage and credentials. In return, the [`Cross-Origin-Embedder-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy) (COEP) embedding rules can be lifted, so documents with COEP set can embed third-party documents that do not. See [IFrame credentialless](https://developer.mozilla.org/en-US/docs/Web/Security/IFrame_credentialless) for a deeper explanation.

  
[`HTMLIFrameElement.csp`](htmliframeelement/csp)  Experimental 
  Specifies the Content Security Policy that an embedded document must agree to enforce upon itself.

  
`HTMLIFrameElement.frameBorder`  Deprecated 
  A string that indicates whether to create borders between frames.

  `HTMLIFrameElement.height`  A string that reflects the [`height`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#height) HTML attribute, indicating the height of the frame.

  
`HTMLIFrameElement.longDesc`  Deprecated 
  A string that contains the URI of a long description of the frame.

  
`HTMLIFrameElement.marginHeight`  Deprecated 
  A string being the height of the frame margin.

  
`HTMLIFrameElement.marginWidth`  Deprecated 
  A string being the width of the frame margin.

  `HTMLIFrameElement.name`  A string that reflects the [`name`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#name) HTML attribute, containing a name by which to refer to the frame.

  
[`HTMLIFrameElement.featurePolicy`](htmliframeelement/featurepolicy) Read only   Experimental 
  Returns the [`FeaturePolicy`](featurepolicy) interface which provides a simple API for introspecting the [Permissions Policies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy) applied to a specific document.

  [`HTMLIFrameElement.referrerPolicy`](htmliframeelement/referrerpolicy)  A string that reflects the [`referrerPolicy`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#referrerpolicy) HTML attribute indicating which referrer to use when fetching the linked resource.

  `HTMLIFrameElement.sandbox`  A [`DOMTokenList`](domtokenlist) that reflects the [`sandbox`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#sandbox) HTML attribute, indicating extra restrictions on the behavior of the nested content.

  
`HTMLIFrameElement.scrolling`  Deprecated 
  A string that indicates whether the browser should provide scrollbars for the frame.

  [`HTMLIFrameElement.src`](htmliframeelement/src)  A string that reflects the [`src`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#src) HTML attribute, containing the address of the content to be embedded. Note that programmatically removing an `<iframe>`'s src attribute (e.g. via [`Element.removeAttribute()`](element/removeattribute)) causes `about:blank` to be loaded in the frame in Firefox (from version 65), Chromium-based browsers, and Safari/iOS.

  [`HTMLIFrameElement.srcdoc`](htmliframeelement/srcdoc)  A string that represents the content to display in the frame.

  `HTMLIFrameElement.width`  A string that reflects the [`width`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#width) HTML attribute, indicating the width of the frame.

  

Instance methods
----------------


*Inherits methods from its parent, [`HTMLElement`](htmlelement)*.


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmliframeelement](https://html.spec.whatwg.org/multipage/iframe-embed-object.html#htmliframeelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLIFrameElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `align` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `allow` | 60 | 79 | 74 | No | 47 | 11.1 | 60 | 60 | 79 | 44 | 11.3 | 8.0 |
| `allowFullscreen` | 38 | 12 | 229–18 | No | 25 | 10.1 | 38 | 38 | 229–18 | 25 | 12Only available on iPad, not on iPhone. | 3.0 |
| `allowPaymentRequest` | 60 | 15 | 56–83 | No | 47 | No | No | 57 | 56–83 | 43 | No | 7.0 |
| `contentDocument` | 1 | 12 | 1 | 8 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `contentWindow` | 1 | 12 | 1 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `csp` | 61 | 79 | No | No | 48 | No | 61 | 61 | No | 45 | No | 8.0 |
| `featurePolicy` | 74 | 79 | 69 | No | 62 | No | 74 | 74 | No | 53 | No | 11.0 |
| `frameBorder` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `getSVGDocument` | 1 | 12 | 3.5 | 9 | ≤12.1 | 3.1 | 3 | 18 | 4 | ≤12.1 | 2 | 1.0 |
| `height` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `loading` | 77 | 79 | No | No | 60 | 16.4 | 77 | 77 | No | 55 | 16.4 | 12.0 |
| `longDesc` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `marginHeight` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `marginWidth` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `name` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `referrerPolicy` | 5251–52 | 79 | 50 | No | 3938–39 | 14 | 5251–52 | 5251–52 | 50 | 41 | 14 | 6.05.0–6.0 |
| `sandbox` | 5Before Chrome 50, this property returned the deprecated child `DOMSettableTokenList` instead of `DOMTokenList`. | 12 | 17Previously, the type of `sandbox` was a `DOMString` instead of a `DOMSettableTokenList`. This has been fixed with Firefox 29. Other browsers may still implement the property as `DOMString` since it was a late change in the specification. | 10 | 15Before Opera 37, this property returned the deprecated child `DOMSettableTokenList` instead of `DOMTokenList`. | 5 | ≤37Before WebView 50, this property returned the deprecated child `DOMSettableTokenList` instead of `DOMTokenList`. | 18Before Chrome 50, this property returned the deprecated child `DOMSettableTokenList` instead of `DOMTokenList`. | 17Previously, the type of `sandbox` was a `DOMString` instead of a `DOMSettableTokenList`. This has been fixed with Firefox 29. Other browsers may still implement the property as `DOMString` since it was a late change in the specification. | 14Before Opera 37, this property returned the deprecated child `DOMSettableTokenList` instead of `DOMTokenList`. | 4 | 1.0Before Samsung Internet 5.0, this property returned the deprecated child `DOMSettableTokenList` instead of `DOMTokenList`. |
| `scrolling` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `src` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `srcdoc` | 20 | 79 | 25 | No | 15 | 6 | 4.4 | 25 | 25 | 14 | 6 | 1.5 |
| `width` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement>

HTMLImageElement
================



The `HTMLImageElement` interface represents an HTML [`<img>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img) element, providing the properties and methods used to manipulate image elements.


 EventTarget Node Element HTMLElement HTMLImageElement

Constructor
-----------


 [`Image()`](htmlimageelement/image)  The `Image()` constructor creates and returns a new `HTMLImageElement` object representing an HTML [`<img>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img) element which is not attached to any DOM tree. It accepts optional width and height parameters. When called without parameters, `new Image()` is equivalent to calling [`document.createElement('img')`](document/createelement).

  
Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  [`HTMLImageElement.alt`](htmlimageelement/alt)  A string that reflects the [`alt`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#alt) HTML attribute, thus indicating the alternate fallback content to be displayed if the image has not been loaded.

  
[`HTMLImageElement.complete`](htmlimageelement/complete) Read only 
  Returns a boolean value that is `true` if the browser has finished fetching the image, whether successful or not. That means this value is also `true` if the image has no [`src`](htmlimageelement/src) value indicating an image to load.

  [`HTMLImageElement.crossOrigin`](htmlimageelement/crossorigin)  A string specifying the CORS setting for this image element. See [CORS settings attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) for further details. This may be `null` if CORS is not used.

  
[`HTMLImageElement.currentSrc`](htmlimageelement/currentsrc) Read only 
  Returns a string representing the URL from which the currently displayed image was loaded. This may change as the image is adjusted due to changing conditions, as directed by any [media queries](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries) which are in place.

  [`HTMLImageElement.decoding`](htmlimageelement/decoding)  An optional string representing a hint given to the browser on how it should decode the image. If this value is provided, it must be one of the possible permitted values: `sync` to decode the image synchronously, `async` to decode it asynchronously, or `auto` to indicate no preference (which is the default). Read the [`decoding`](htmlimageelement/decoding) page for details on the implications of this property's values.

  
[`HTMLImageElement.fetchPriority`](htmlimageelement/fetchpriority)  Experimental 
  An optional string representing a hint given to the browser on how it should prioritize fetching of the image relative to other images. If this value is provided, it must be one of the possible permitted values: `high` to fetch at a high priority, `low` to fetch at a low priority, or `auto` to indicate no preference (which is the default).

  [`HTMLImageElement.height`](htmlimageelement/height)  An integer value that reflects the [`height`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#height) HTML attribute, indicating the rendered height of the image in CSS pixels.

  [`HTMLImageElement.isMap`](htmlimageelement/ismap)  A boolean value that reflects the [`ismap`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#ismap) HTML attribute, indicating that the image is part of a server-side image map. This is different from a client-side image map, specified using an `<img>` element and a corresponding [`<map>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/map) which contains [`<area>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area) elements indicating the clickable areas in the image. The image *must* be contained within an [`<a>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a) element; see the `ismap` page for details.

  [`HTMLImageElement.loading`](htmlimageelement/loading)  A string providing a hint to the browser used to optimize loading the document by determining whether to load the image immediately (`eager`) or on an as-needed basis (`lazy`).

  
[`HTMLImageElement.naturalHeight`](htmlimageelement/naturalheight) Read only 
  Returns an integer value representing the intrinsic height of the image in CSS pixels, if it is available; else, it shows `0`. This is the height the image would be if it were rendered at its natural full size.

  
[`HTMLImageElement.naturalWidth`](htmlimageelement/naturalwidth) Read only 
  An integer value representing the intrinsic width of the image in CSS pixels, if it is available; otherwise, it will show `0`. This is the width the image would be if it were rendered at its natural full size.

  [`HTMLImageElement.referrerPolicy`](htmlimageelement/referrerpolicy)  A string that reflects the [`referrerpolicy`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#referrerpolicy) HTML attribute, which tells the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) how to decide which referrer to use in order to fetch the image. Read this article for details on the possible values of this string.

  [`HTMLImageElement.sizes`](htmlimageelement/sizes)  A string reflecting the [`sizes`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#sizes) HTML attribute. This string specifies a list of comma-separated conditional sizes for the image; that is, for a given viewport size, a particular image size is to be used. Read the documentation on the [`sizes`](htmlimageelement/sizes) page for details on the format of this string.

  [`HTMLImageElement.src`](htmlimageelement/src)  A string that reflects the [`src`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#src) HTML attribute, which contains the full URL of the image including base URI. You can load a different image into the element by changing the URL in the `src` attribute.

  [`HTMLImageElement.srcset`](htmlimageelement/srcset)  A string reflecting the [`srcset`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#srcset) HTML attribute. This specifies a list of candidate images, separated by commas (`',', U+002C COMMA`). Each candidate image is a URL followed by a space, followed by a specially-formatted string indicating the size of the image. The size may be specified either the width or a size multiple. Read the [`srcset`](htmlimageelement/srcset) page for specifics on the format of the size substring.

  [`HTMLImageElement.useMap`](htmlimageelement/usemap)  A string reflecting the [`usemap`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#usemap) HTML attribute, containing the page-local URL of the [`<map>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/map) element describing the image map to use. The page-local URL is a pound (hash) symbol (`#`) followed by the ID of the `<map>` element, such as `#my-map-element`. The `<map>` in turn contains [`<area>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area) elements indicating the clickable areas in the image.

  [`HTMLImageElement.width`](htmlimageelement/width)  An integer value that reflects the [`width`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#width) HTML attribute, indicating the rendered width of the image in CSS pixels.

  
[`HTMLImageElement.x`](htmlimageelement/x) Read only 
  An integer indicating the horizontal offset of the left border edge of the image's CSS layout box relative to the origin of the [`<html>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/html) element's containing block.

  
[`HTMLImageElement.y`](htmlimageelement/y) Read only 
  The integer vertical offset of the top border edge of the image's CSS layout box relative to the origin of the [`<html>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/html) element's containing block.

  

Obsolete properties
-------------------


 
[`HTMLImageElement.align`](htmlimageelement/align)  Deprecated 
  A string indicating the alignment of the image with respect to the surrounding context. The possible values are `"left"`, `"right"`, `"justify"`, and `"center"`. This is obsolete; you should instead use CSS (such as [`text-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/text-align), which works with images despite its name) to specify the alignment.

  
[`HTMLImageElement.border`](htmlimageelement/border)  Deprecated 
  A string which defines the width of the border surrounding the image. This is deprecated; use the CSS [`border`](https://developer.mozilla.org/en-US/docs/Web/CSS/border) property instead.

  
[`HTMLImageElement.hspace`](htmlimageelement/hspace)  Deprecated 
  An integer value which specifies the amount of space (in pixels) to leave empty on the left and right sides of the image.

  
[`HTMLImageElement.longDesc`](htmlimageelement/longdesc)  Deprecated 
  A string specifying the URL at which a long description of the image's contents may be found. This is used to turn the image into a hyperlink automatically. Modern HTML should instead place an `<img>` inside an [`<a>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a) element defining the hyperlink.

  
[`HTMLImageElement.name`](htmlimageelement/name)  Deprecated 
  A string representing the name of the element.

  
[`HTMLImageElement.vspace`](htmlimageelement/vspace)  Deprecated 
  An integer value specifying the amount of empty space, in pixels, to leave above and below the image.

  
Instance methods
----------------



*Inherits methods from its parent, [`HTMLElement`](htmlelement).*

  [`HTMLImageElement.decode()`](htmlimageelement/decode)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves when the image is decoded and it's safe to append the image to the DOM. This prevents rendering of the next frame from having to pause to decode the image, as would happen if an undecoded image were added to the DOM.

  

Errors
------



If an error occurs while trying to load or render the image, and an [`onerror`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#onerror) event handler has been configured to handle the [`error`](element/error_event) event, that event handler will get called. This can happen in a number of situations, including:

 * The [`src`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#src) attribute is empty or `null`.
* The specified `src` URL is the same as the URL of the page the user is currently on.
* The specified image is corrupted in some way that prevents it from being loaded.
* The specified image's metadata is corrupted in such a way that it's impossible to retrieve its dimensions, and no dimensions were specified in the `<img>` element's attributes.
* The specified image is in a format not supported by the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent).



Example
-------



```
const img1 = new Image(); // Image constructor
img1.src = "image1.png";
img1.alt = "alt";
document.body.appendChild(img1);

const img2 = document.createElement("img"); // Use DOM HTMLImageElement
img2.src = "image2.jpg";
img2.alt = "alt text";
document.body.appendChild(img2);

// using first image in the document
alert(document.images[0].src);

```

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlimageelement](https://html.spec.whatwg.org/multipage/embedded-content.html#htmlimageelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Image` | 1 | 12 | 1 | 5.5 | 8 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `HTMLImageElement` | 1 | 12 | 1 | 5.5 | 8 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `align` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `alt` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `border` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `complete` | 1 | 12 | 1 | 5.5IE reports `false` for broken images. | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `crossOrigin` | 13 | 12 | 8 | 11 | ≤12.1 | 6 | 4.4 | 18 | 8 | ≤12.1 | 6 | 1.0 |
| `currentSrc` | 38 | 13 | 38 | No | 25 | 9.1 | 38 | 38 | 38 | 25 | 9.3 | 3.0 |
| `decode` | 64 | 79 | 68 | No | 51 | 11.1 | 64 | 64 | 68 | 47 | 11.3 | 9.0 |
| `decoding` | 65 | 79 | 63 | No | 52 | 11.1 | 65 | 65 | 63 | 47 | 11.3 | 9.0 |
| `fetchPriority` | 102101–102 | 102101–102 | No | No | 8887–88 | No | 102101–102 | 102101–102 | No | 70 | No | 19.0 |
| `height` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `hspace` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `isMap` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `loading` | 77 | 79 | 75 | No | 64 | 15.4 | 77 | 77 | 79 | 55 | 15.4 | 12.0 |
| `longDesc` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `lowsrc` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 2 | 1.0 |
| `name` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `naturalHeight` | 1 | 12 | 1 | 9 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `naturalWidth` | 1 | 12 | 1 | 9 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `referrerPolicy` | 5251–52 | 79 | 50 | No | 3938–39 | 14 | 5251–52 | 5251–52 | 50 | 41 | 14 | 6.05.0–6.0 |
| `sizes` | 38 | 13 | 38 | No | 25 | 9.1 | 38 | 38 | 38 | 25 | 9.3 | 3.0 |
| `src` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `srcset` | 34 | 12 | 38 | No | 21 | 8 | 37 | 34 | 38 | 21 | 8 | 2.0 |
| `useMap` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `vspace` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `width` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `x` | 1 | 12 | 141–7 | No | ≤12.1 | 3 | 4.4 | 18 | 144–7 | ≤12.1 | 1 | 1.0 |
| `y` | 1 | 12 | 141–7 | No | ≤12.1 | 3 | 4.4 | 18 | 144–7 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<img>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement>

HTMLInputElement
================



The `HTMLInputElement` interface provides special properties and methods for manipulating the options, layout, and presentation of [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) elements.


 EventTarget Node Element HTMLElement HTMLInputElement

Instance properties
-------------------



Some properties only apply to input element types that support the corresponding attributes.

  
`align`  Deprecated 
  `string`: **Represents** the alignment of the element. *Use CSS instead.*

  
`autocapitalize`  Experimental 
  `string`: **Defines** the capitalization behavior for user input. Valid values are `none`, `off`, `characters`, `words` or `sentences`.

  `defaultValue`  `string`: **Returns / Sets** the default value as originally specified in the HTML that created this object.

  `dirName`  `string`: **Returns / Sets** the directionality of the element.

  `inputmode`  Provides a hint to browsers as to the type of virtual keyboard configuration to use when editing this element or its contents.

  
[`labels`](htmlinputelement/labels) Read only 
  [`NodeList`](nodelist) array: **Returns** a list of [`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label) elements that are labels for this element.

  
`list` Read only 
  [`HTMLElement`](htmlelement): **Returns** the element pointed to by the [`list`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#list) attribute. The property may be `null` if no HTML element is found in the same tree.

  [`multiple`](htmlinputelement/multiple)  `boolean`: **Returns / Sets** the element's [`multiple`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#multiple) attribute, indicating whether more than one value is possible (e.g., multiple files).

  `name`  `string`: **Returns / Sets** the element's [`name`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#name) attribute, containing a name that identifies the element when submitting the form.

  `step`  `string`: **Returns / Sets** the element's [`step`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#step) attribute, which works with [`min`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#min) and [`max`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#max) to limit the increments at which a numeric or date-time value can be set. It can be the string `any` or a positive floating point number. If this is not set to `any`, the control accepts only values at multiples of the step value greater than the minimum.

  `type`  `string`: **Returns / Sets** the element's [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#type) attribute, indicating the type of control to display. For possible values, see the documentation for the [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#type) attribute.

  
`useMap`  Deprecated 
  `string`: **Represents** a client-side image map.

  `value`  `string`: **Returns / Sets** the current value of the control. If the user enters a value different from the value expected, this may return an empty string.

  `valueAsDate`  [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date): **Returns / Sets** the value of the element, interpreted as a date, or `null` if conversion is not possible.

  `valueAsNumber`  `double`: **Returns** the value of the element, interpreted as one of the following, in order: A time value, a number or `NaN` if conversion is impossible

  

### Instance properties related to the parent form


 
`form` Read only 
  [`HTMLFormElement`](htmlformelement): **Returns** a reference to the parent [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) element.

  `formAction`  `string`: **Returns / Sets** the element's [`formaction`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#formaction) attribute, containing the URL of a program that processes information submitted by the element. This overrides the [`action`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#action) attribute of the parent form.

  `formEnctype`  `string`: **Returns / Sets** the element's [`formenctype`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#formenctype) attribute, containing the type of content that is used to submit the form to the server. This overrides the [`enctype`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#enctype) attribute of the parent form.

  `formMethod`  `string`: **Returns / Sets** the element's [`formmethod`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#formmethod) attribute, containing the HTTP method that the browser uses to submit the form. This overrides the [`method`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#method) attribute of the parent form.

  `formNoValidate`  `boolean`: **Returns / Sets** the element's [`formnovalidate`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#formnovalidate) attribute, indicating that the form is not to be validated when it is submitted. This overrides the [`novalidate`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#novalidate) attribute of the parent form.

  `formTarget`  `string`: **Returns / Sets** the element's [`formtarget`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#formtarget) attribute, containing a name or keyword indicating where to display the response that is received after submitting the form. This overrides the [`target`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#target) attribute of the parent form.

  
### Instance properties that apply to any type of input element that is not hidden


 `autofocus`  `boolean`: **Returns / Sets** the element's [`autofocus`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#autofocus) attribute, which specifies that a form control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form element in a document can have the [`autofocus`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#autofocus) attribute.

  [`disabled`](htmlinputelement/disabled)  `boolean`: **Returns / Sets** the element's [`disabled`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#disabled) attribute, indicating that the control is not available for interaction. The input values will not be submitted with the form. See also [`readonly`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#readonly).

  `required`  `boolean`: **Returns / Sets** the element's [`required`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#required) attribute, indicating that the user must fill in a value before submitting a form.

  
`validationMessage` Read only 
  `string`: **Returns** a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation ([`willValidate`](htmlobjectelement/willvalidate) is `false`), or it satisfies its constraints. This value can be set by the [`setCustomValidity()`](htmlinputelement/setcustomvalidity) method.

  
`validity` Read only 
  [`ValidityState`](validitystate): **Returns** the element's current validity state.

  
`willValidate` Read only 
  `boolean`: **Returns** whether the element is a candidate for constraint validation. It is `false` if any conditions bar it from constraint validation, including: its `type` is one of `hidden`, `reset` or `button`, it has a [`<datalist>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist) ancestor or its `disabled` property is `true`.

  
### Instance properties that apply only to elements of type checkbox or radio


 `checked`  `boolean`: **Returns / Sets** the current state of the element.

  `defaultChecked`  `boolean`: **Returns / Sets** the default state of a radio button or checkbox as originally specified in HTML that created this object.

  `indeterminate`  `boolean`: **Returns** whether the checkbox or radio button is in indeterminate state. For checkboxes, the effect is that the appearance of the checkbox is obscured/greyed in some way as to indicate its state is indeterminate (not checked but not unchecked). Does not affect the value of the `checked` attribute, and clicking the checkbox will set the value to false.

  
### Instance properties that apply only to elements of type image


 `alt`  `string`: **Returns / Sets** the element's [`alt`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#alt) attribute, containing alternative text to use.

  `height`  `string`: **Returns / Sets** the element's [`height`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#height) attribute, which defines the height of the image displayed for the button.

  `src`  `string`: **Returns / Sets** the element's [`src`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#src) attribute, which specifies a URI for the location of an image to display on the graphical submit button.

  `width`  `string`: **Returns / Sets** the element's [`width`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#width) attribute, which defines the width of the image displayed for the button.

  
### Instance properties that apply only to elements of type file


 `accept`  `string`: **Returns / Sets** the element's [`accept`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#accept) attribute, containing comma-separated list of file types that can be selected.

  
`allowdirs`  Non-standard 
  `boolean`: Part of the non-standard Directory Upload API. Indicates whether or not to allow directories and files both to be selected in the file list. Implemented only in Firefox and is hidden behind a preference.

  [`files`](htmlinputelement/files)  [`FileList`](filelist): **Returns / Sets** a list of [`File`](file) objects representing the files selected for upload.

  [`webkitdirectory`](htmlinputelement/webkitdirectory)  `boolean`: **Returns** the [`webkitdirectory`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#webkitdirectory) attribute. If `true`, the file-system-picker interface only accepts directories instead of files.

  [`webkitEntries`](htmlinputelement/webkitentries)  [`FileSystemEntry`](filesystementry) array: **Describes** the currently selected files or directories.

  
### Instance properties that apply only to visible elements containing text or numbers


 `autocomplete`  `string`: **Returns / Sets** the element's [`autocomplete`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#autocomplete) attribute, indicating whether the value of the control can be automatically completed by the browser.

  `max`  `string`: **Returns / Sets** the element's [`max`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#max) attribute, containing the maximum (numeric or date-time) value for this item, which must not be less than its minimum ([`min`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#min) attribute) value.

  `maxLength`  `unsigned long`: **Returns / Sets** the element's [`maxlength`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#maxlength) attribute, containing the maximum number of characters (in Unicode code points) that the value can have.

  `min`  `string`: **Returns / Sets** the element's [`min`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#min) attribute, containing the minimum (numeric or date-time) value for this item, which must not be greater than its maximum ([`max`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#max) attribute) value.

  `minLength`  `unsigned long`: **Returns / Sets** the element's [`minlength`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#minlength) attribute, containing the minimum number of characters (in Unicode code points) that the value can have.

  `pattern`  `string`: **Returns / Sets** the element's [`pattern`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#pattern) attribute, containing a regular expression that the control's value is checked against. Use the [`title`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#title) attribute to describe the pattern to help the user. This attribute only applies when the value of the [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#type) attribute is `text`, `search`, `tel`, `url` or `email`.

  `placeholder`  `string`: **Returns / Sets** the element's [`placeholder`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#placeholder) attribute, containing a hint to the user of what can be entered in the control. The placeholder text must not contain carriage returns or line-feeds. This attribute only applies when the value of the [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#type) attribute is `text`, `search`, `tel`, `url` or `email`.

  `readOnly`  `boolean`: **Returns / Sets** the element's [`readonly`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#readonly) attribute, indicating that the user cannot modify the value of the control. This is ignored if the [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#type) is `hidden`, `range`, `color`, `checkbox`, `radio`, `file`, or a button type.

  `selectionEnd`  `unsigned long`: **Returns / Sets** the end index of the selected text. When there's no selection, this returns the offset of the character immediately following the current text input cursor position.

  `selectionStart`  `unsigned long`: **Returns / Sets** the beginning index of the selected text. When nothing is selected, this returns the position of the text input cursor (caret) inside of the [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) element.

  `selectionDirection`  `string`: **Returns / Sets** the direction in which selection occurred. Possible values are: `forward` (the selection was performed in the start-to-end direction of the current locale), `backward` (the opposite direction) or `none` (the direction is unknown).

  `size`  `unsigned long`: **Returns / Sets** the element's [`size`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#size) attribute, containing visual size of the control. This value is in pixels unless the value of [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#type) is `text` or `password`, in which case, it is an integer number of characters. Applies only when [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#type) is set to `text`, `search`, `tel`, `url`, `email`, or `password`.

  
Instance methods
----------------


 [`blur()`](htmlelement/blur)  Removes focus from the input element; keystrokes will subsequently go nowhere.

  [`click()`](htmlelement/click)  Simulates a click on the input element.

  [`focus()`](htmlelement/focus)  Focuses on the input element; keystrokes will subsequently go to this element.

  [`select()`](htmlinputelement/select)  Selects all the text in the input element, and focuses it so the user can subsequently replace all of its content.

  [`setSelectionRange()`](htmlinputelement/setselectionrange)  Selects a range of text in the input element (but does not focus it).

  [`setRangeText()`](htmlinputelement/setrangetext)  Replaces a range of text in the input element with new text.

  [`setCustomValidity()`](htmlinputelement/setcustomvalidity)  Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate.

  [`showPicker()`](htmlinputelement/showpicker)  Shows a browser picker for date, time, color, and files.

  [`checkValidity()`](htmlinputelement/checkvalidity)  Returns a boolean value that is `false` if the element is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires an [`invalid`](htmlinputelement/invalid_event) event at the element. It returns `true` if the element is not a candidate for constraint validation, or if it satisfies its constraints.

  [`reportValidity()`](htmlinputelement/reportvalidity)  Runs the `checkValidity()` method, and if it returns false (for an invalid input or no pattern attribute provided), then it reports to the user that the input is invalid in the same manner as if you submitted a form.

  [`stepDown()`](htmlinputelement/stepdown)  Decrements the [`value`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#value) by ([`step`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#step) \* n), where n defaults to 1 if not specified. Throws an `InvalidStateError` exception:

 * if the method is not applicable to for the current [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#type) value,
* if the element has no [`step`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#step) value,
* if the [`value`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#value) cannot be converted to a number,
* if the resulting value is above the [`max`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#max) or below the [`min`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#min).

  [`stepUp()`](htmlinputelement/stepup)  Increments the [`value`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#value) by ([`step`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#step) \* n), where n defaults to 1 if not specified. Throws an `InvalidStateError` exception:

 * if the method is not applicable to for the current [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#type) value.,
* if the element has no [`step`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#step) value,
* if the [`value`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#value) cannot be converted to a number,
* if the resulting value is above the [`max`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#max) or below the [`min`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#min).

  
Events
------



Listen to these events using [`addEventListener()`](eventtarget/addeventlistener) or by assigning an event listener to the `oneventname` property of this interface:

  [`input`](htmlelement/input_event)  Fires when the `value` of an [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input), [`<select>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select), or [`<textarea>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea) element has been changed. Note that this is actually fired on the [`HTMLElement`](htmlelement) interface and also applies to [`contenteditable`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/contenteditable) elements, but we've listed it here because it is most commonly used with form input elements.

  [`invalid`](htmlinputelement/invalid_event)  Fired when an element does not satisfy its constraints during constraint validation.

  
[`search`](htmlinputelement/search_event)  Non-standard 
  Fired when a search is initiated on an [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) of `type="search"`.

  
[`selectionchange`](htmlinputelement/selectionchange_event) event  Experimental 
  Fires when the text selection in a [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) element has been changed.

  

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlinputelement](https://html.spec.whatwg.org/multipage/input.html#htmlinputelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLInputElement` | 1 | 12 | 1 | 5.5 | 8 | 1 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 |
| `accept` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `align` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `alt` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `autocomplete` | 14 | 12 | 4 | 10 | ≤12.1 | 6 | 4.4 | 18 | 4 | ≤12.1 | 6 | 1.0 |
| `cancel_event` | NoSee [bug 1227424](https://crbug.com/1227424). | NoSee [bug 1227424](https://crbug.com/1227424). | 91 | No | NoSee [bug 1227424](https://crbug.com/1227424). | NoSee [bug 227799](https://webkit.org/b/227799). | NoSee [bug 1227424](https://crbug.com/1227424). | NoSee [bug 1227424](https://crbug.com/1227424). | 91 | NoSee [bug 1227424](https://crbug.com/1227424). | NoSee [bug 227799](https://webkit.org/b/227799). | NoSee [bug 1227424](https://crbug.com/1227424). |
| `capture` | No | No | No | No | No | No | 4.4 | 25 | 79 | 14 | 10 | 1.5 |
| `checkValidity` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 |
| `checked` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `defaultChecked` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `defaultValue` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `dirName` | 17 | 79 | No | No | ≤12.1 | 6 | 4.4 | 18 | No | ≤12.1 | 6 | 1.0 |
| `disabled` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `files` | 2 | 12 | 3 | 10This property is read-only. | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3 | 1.0 |
| `form` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `formAction` | 9 | 12 | 4 | 10 | ≤12.1 | 5 | 3 | 18 | 4 | ≤12.1 | 4.2 | 1.0 |
| `formEnctype` | 9 | 12 | 4 | 10 | ≤12.1 | 5 | 3 | 18 | 4 | ≤12.1 | 4.2 | 1.0 |
| `formMethod` | 9 | 12 | 4 | 10 | ≤12.1 | 5 | 3 | 18 | 4 | ≤12.1 | 4.2 | 1.0 |
| `formNoValidate` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 |
| `formTarget` | 9 | 12 | 4 | 10 | ≤12.1 | 5 | 3 | 18 | 4 | ≤12.1 | 4.2 | 1.0 |
| `height` | 21 | 12 | 16 | 5.5 | ≤12.1 | 7 | 4.4 | 25 | 16 | ≤12.1 | 7 | 1.5 |
| `incremental` | 10 | 79 | No | No | 15 | 5 | ≤37 | 18 | No | 14 | 4.2 | 1.0 |
| `indeterminate` | 1 | 12 | 3.6 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `invalid_event` | 10 | 12 | 4 | 10 | 10 | 5 | 4 | 18 | 64 | 12 | 5 | 4.0 |
| `labels` | 6 | 18 | 56 | No | ≤12.1 | 5 | 3 | 18 | 56 | ≤12.1 | 4.2 | 1.0 |
| `list` | 20 | 12 | 4 | 10 | ≤12.1 | 12.1 | 4.4.3 | 25 | 4 | ≤12.1 | 12.2 | 1.5 |
| `max` | 4 | 12 | 16 | 10 | ≤12.1 | 5 | ≤37 | 18 | 16 | ≤12.1 | 4 | 1.0 |
| `maxLength` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `min` | 4 | 12 | 16 | 10 | ≤12.1 | 5 | ≤37 | 18 | 16 | ≤12.1 | 4 | 1.0 |
| `minLength` | 40 | 17 | 51 | No | 27 | 10.1 | 40 | 40 | 51 | 27 | 10.3 | 4.0 |
| `multiple` | 2 | 12 | 3.6 | 10 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `name` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `pattern` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 |
| `placeholder` | 3 | 12 | 4 | 10 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `readOnly` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `reportValidity` | 40 | 17 | 49 | No | 27 | 10.1 | 40 | 40 | 64 | 27 | 10.3 | 4.0 |
| `required` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 |
| `search_event` | 1 | 79 | No | No | 15 | 2 | 4.4 | 18 | No | 14 | 1 | 1.0 |
| `select` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `select_event` | 1 | 12 | 6 | 9 | ≤12.1 | 1 | 4.4 | 18 | 6 | ≤12.1 | 1 | 1.0 |
| `selectionDirection` | 15 | 13 | 8 | No | ≤12.1 | 6 | 4.4 | 18 | 8 | ≤12.1 | 6 | 1.0 |
| `selectionEnd` | 1 | 12 | 1 | 9 | ≤12.1 | 1.3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `selectionStart` | 1 | 12 | 1 | 9 | ≤12.1 | 1.3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `selectionchange_event` | NoA `selectionchange` event is fired on `Document`, see [`Document`'s `selectionchange` event](https://developer.mozilla.org/docs/Web/API/Document/selectionchange_event). See [bug 1327098](https://crbug.com/1327098) for firing the event on `<input>` elements. | NoA `selectionchange` event is fired on `Document`, see [`Document`'s `selectionchange` event](https://developer.mozilla.org/docs/Web/API/Document/selectionchange_event). See [bug 1327098](https://crbug.com/1327098) for firing the event on `<input>` elements. | 92 | No | NoA `selectionchange` event is fired on `Document`, see [`Document`'s `selectionchange` event](https://developer.mozilla.org/docs/Web/API/Document/selectionchange_event). See [bug 1327098](https://crbug.com/1327098) for firing the event on `<input>` elements. | NoSee [bug 234348](https://webkit.org/b/234348). | NoA `selectionchange` event is fired on `Document`, see [`Document`'s `selectionchange` event](https://developer.mozilla.org/docs/Web/API/Document/selectionchange_event). See [bug 1327098](https://crbug.com/1327098) for firing the event on `<input>` elements. | NoA `selectionchange` event is fired on `Document`, see [`Document`'s `selectionchange` event](https://developer.mozilla.org/docs/Web/API/Document/selectionchange_event). See [bug 1327098](https://crbug.com/1327098) for firing the event on `<input>` elements. | 92 | NoA `selectionchange` event is fired on `Document`, see [`Document`'s `selectionchange` event](https://developer.mozilla.org/docs/Web/API/Document/selectionchange_event). See [bug 1327098](https://crbug.com/1327098) for firing the event on `<input>` elements. | NoSee [bug 234348](https://webkit.org/b/234348). | NoA `selectionchange` event is fired on `Document`, see [`Document`'s `selectionchange` event](https://developer.mozilla.org/docs/Web/API/Document/selectionchange_event). See [bug 1327098](https://crbug.com/1327098) for firing the event on `<input>` elements. |
| `setCustomValidity` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 |
| `setRangeText` | 24 | 79 | 27 | No | 15 | 7 | 4.4 | 25 | 27 | 14 | 7 | 1.5 |
| `setSelectionRange` | 1 | 12 | 1 | 9 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `showPicker` | 99 | 99 | 101 | No | 85 | 16 | 99 | 99 | 101 | 68 | 16 | 18.0 |
| `size` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `src` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `step` | 5 | 12 | 16 | 10 | ≤12.1 | 5 | ≤37 | 18 | 16 | ≤12.1 | 4 | 1.0 |
| `stepDown` | 5 | 12 | 16Does not have a specific UI. There are still differences with the latest spec; see [bug 835773](https://bugzil.la/835773). | 10 | ≤12.1 | 5 | ≤37 | 18 | 16Does not have a specific UI. There are still differences with the latest spec; see [bug 835773](https://bugzil.la/835773). | ≤12.1 | 4 | 1.0 |
| `stepUp` | 5 | 12 | 16Does not have a specific UI. There are still differences with the latest spec; see [bug 835773](https://bugzil.la/835773). | 10 | ≤12.1 | 5 | ≤37 | 18 | 16Does not have a specific UI. There are still differences with the latest spec; see [bug 835773](https://bugzil.la/835773). | ≤12.1 | 4 | 1.0 |
| `type` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `useMap` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `validationMessage` | 5 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 |
| `validity` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 |
| `value` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `valueAsDate` | 5 | 12 | 5720–24 | No | ≤12.1 | 5 | ≤37 | 18 | 5720–24 | ≤12.1 | 4 | 1.0 |
| `valueAsNumber` | 5 | 12 | 16 | 10 | ≤12.1 | 5 | ≤37 | 18 | 16 | ≤12.1 | 4 | 1.0 |
| `webkitEntries` | 22 | 79 | 50 | No | 15 | 11.1 | No | 25 | No | 14 | 11.3 | 1.5 |
| `webkitdirectory` | 7 | 13 | 50 | No | 15 | 11.1 | 4.4 | 18 | No | 14 | 11.3 | 1.0 |
| `width` | 21 | 12 | 16 | 5.5 | ≤12.1 | 7 | 4.4 | 25 | 16 | ≤12.1 | 7 | 1.5 |
| `willValidate` | 2 | 12 | 4 | 10 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3 | 1.0 |


See also
--------


* HTML element implementing this interface: [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement>

HTMLFormElement
===============



The `HTMLFormElement` interface represents a [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) element in the DOM. It allows access to—and, in some cases, modification of—aspects of the form, as well as access to its component elements.


 EventTarget Node Element HTMLElement HTMLFormElement

Instance properties
-------------------



*This interface also inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
[`HTMLFormElement.elements`](htmlformelement/elements) Read only 
  A [`HTMLFormControlsCollection`](htmlformcontrolscollection) holding all form controls belonging to this form element.

  
[`HTMLFormElement.length`](htmlformelement/length) Read only 
  A `long` reflecting the number of controls in the form.

  [`HTMLFormElement.name`](htmlformelement/name)  A string reflecting the value of the form's [`name`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#name) HTML attribute, containing the name of the form.

  [`HTMLFormElement.method`](htmlformelement/method)  A string reflecting the value of the form's [`method`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#method) HTML attribute, indicating the HTTP method used to submit the form. Only specified values can be set.

  [`HTMLFormElement.target`](htmlformelement/target)  A string reflecting the value of the form's [`target`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#target) HTML attribute, indicating where to display the results received from submitting the form.

  [`HTMLFormElement.action`](htmlformelement/action)  A string reflecting the value of the form's [`action`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#action) HTML attribute, containing the URI of a program that processes the information submitted by the form.

  
[`HTMLFormElement.encoding`](htmlformelement/encoding) or [`HTMLFormElement.enctype`](htmlformelement/enctype)
  A string reflecting the value of the form's [`enctype`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#enctype) HTML attribute, indicating the type of content that is used to transmit the form to the server. Only specified values can be set. The two properties are synonyms.

  [`HTMLFormElement.acceptCharset`](htmlformelement/acceptcharset)  A string reflecting the value of the form's [`accept-charset`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#accept-charset) HTML attribute, representing the character encoding that the server accepts.

  `HTMLFormElement.autocomplete`  A string reflecting the value of the form's [`autocomplete`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#autocomplete) HTML attribute, indicating whether the controls in this form can have their values automatically populated by the browser.

  `HTMLFormElement.noValidate`  A boolean value reflecting the value of the form's [`novalidate`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#novalidate) HTML attribute, indicating whether the form should not be validated.

   Named inputs are added to their owner form instance as properties, and can overwrite native properties if they share the same name (e.g. a form with an input named `action` will have its `action` property return that input instead of the form's [`action`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#action) HTML attribute).



Instance methods
----------------



*This interface also inherits methods from its parent, [`HTMLElement`](htmlelement).*

  `checkValidity()`  Returns `true` if the element's child controls are subject to [constraint validation](https://developer.mozilla.org/en-US/docs/Web/HTML/Constraint_validation) and satisfy those constraints; returns `false` if some controls do not satisfy their constraints. Fires an event named [`invalid`](htmlinputelement/invalid_event) at any control that does not satisfy its constraints; such controls are considered invalid if the event is not canceled. It is up to the programmer to decide how to respond to `false`.

  [`reportValidity()`](htmlformelement/reportvalidity)  Returns `true` if the element's child controls satisfy their [validation constraints](https://developer.mozilla.org/en-US/docs/Web/HTML/Constraint_validation). When `false` is returned, cancelable [`invalid`](htmlinputelement/invalid_event) events are fired for each invalid child and validation problems are reported to the user.

  [`requestSubmit()`](htmlformelement/requestsubmit)  Requests that the form be submitted using the specified submit button and its corresponding configuration.

  [`reset()`](htmlformelement/reset)  Resets the form to its initial state.

  [`submit()`](htmlformelement/submit)  Submits the form to the server.

  

### Deprecated methods


 
`HTMLFormElement.requestAutocomplete()`  Deprecated 
  Triggers a native browser interface to assist the user in completing the fields which have an [autofill field name](https://html.spec.whatwg.org/#autofill-field-name) value that is not `off` or `on`. The form will receive an event once the user has finished with the interface, the event will either be `autocomplete` when the fields have been filled or `autocompleteerror` when there was a problem.

  
Events
------



Listen to these events using `addEventListener()`, or by assigning an event listener to the `oneventname` property of this interface.

  [`formdata`](htmlformelement/formdata_event)  The `formdata` event fires after the entry list representing the form's data is constructed.

  [`reset`](htmlformelement/reset_event)  The `reset` event fires when a form is reset.

  [`submit`](htmlformelement/submit_event)  The `submit` event fires when a form is submitted.

  

Usage notes
-----------


### Obtaining a form element object



To obtain an `HTMLFormElement` object, you can use a [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors) with [`querySelector()`](document/queryselector), or you can get a list of all of the forms in the document using its [`forms`](document/forms) property.

 [`Document.forms`](document/forms) returns an array of `HTMLFormElement` objects listing each of the forms on the page. You can then use any of the following syntaxes to get an individual form:

  `document.forms[index]`  Returns the form at the specified `index` into the array of forms.

  `document.forms[id]`  Returns the form whose ID is `id`.

  `document.forms[name]`  Returns the form whose `name` attribute's value is `name`.

  

### Accessing the form's elements



You can access the list of the form's data-containing elements by examining the form's [`elements`](htmlformelement/elements) property. This returns an [`HTMLFormControlsCollection`](htmlformcontrolscollection) listing all of the form's user data entry elements, both those which are descendants of the `<form>` and those which are made members of the form using their `form` attributes.

 You can also get the form's element by using its `name` attribute as a key of the `form`, but using `elements` is a better approach—it contains *only* the form's elements, and it cannot be mixed with other attributes of the `form`.



### Issues with Naming Elements



Some names will interfere with JavaScript access to the form's properties and elements.

 For example:

 * `<input name="id">` will take precedence over `<form id="…">`. This means that `form.id` will not refer to the form's id, but to the element whose name is "`id`". This will be the case with any other form properties, such as `<input name="action">` or `<input name="post">`.
* `<input name="elements">` will render the form's `elements` collection inaccessible. The reference `form.elements` will now refer to the individual element.

 To avoid such problems with element names:

 * *Always* use the `elements` collection to avoid ambiguity between an element name and a form property.
* *Never* use "`elements`" as an element name.

 If you are not using JavaScript, this will not cause a problem.



### Elements that are considered form controls



The elements included by `HTMLFormElement.elements` and `HTMLFormElement.length` are the following:

 * [`<button>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button)
* [`<fieldset>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset)
* [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) (with the exception that any whose [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#type) is `"image"` are omitted for historical reasons)
* [`<object>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object)
* [`<output>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/output)
* [`<select>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select)
* [`<textarea>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea)

 No other elements are included in the list returned by `elements`, which makes it an excellent way to get at the elements most important when processing forms.



Examples
--------



Creating a new form element, modifying its attributes, then submitting it:

 
```
const f = document.createElement("form"); // Create a form
document.body.appendChild(f); // Add it to the document body
f.action = "/cgi-bin/some.cgi"; // Add action and method attributes
f.method = "POST";
f.submit(); // Call the form's submit() method

```
 Extract information from a `<form>` element and set some of its attributes:

 
```
<form name="formA" action="/cgi-bin/test" method="post">
  <p>Press "Info" for form details, or "Set" to change those details.</p>
  <p>
    <button type="button" onclick="getFormInfo();">Info</button>
    <button type="button" onclick="setFormInfo(this.form);">Set</button>
    <button type="reset">Reset</button>
  </p>

  <textarea id="form-info" rows="15" cols="20"></textarea>
</form>

<script>
 function getFormInfo() {
 // Get a reference to the form via its name
 const f = document.forms["formA"];
 // The form properties we're interested in
 const properties = [
 "elements",
 "length",
 "name",
 "charset",
 "action",
 "acceptCharset",
 "action",
 "enctype",
 "method",
 "target",
 ];
 // Iterate over the properties, turning them into a string that we can display to the user
 const info = properties
 .map((property) => `${property}: ${f[property]}`)
 .join("\n");

 // Set the form's <textarea> to display the form's properties
 document.forms["formA"].elements["form-info"].value = info; // document.forms["formA"]['form-info'].value would also work
 }

 function setFormInfo(f) {
 // Argument should be a form element reference.
 f.action = "a-different-url.cgi";
 f.name = "a-different-name";
 }
</script>

```
 Submit a `<form>` into a new window:

 
```
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8" />
    <title>Example new-window form submission</title>
  </head>
  <body>
    <form action="test.php" target="\_blank">
      <p>
        <label>First name: <input type="text" name="firstname" /></label>
      </p>
      <p>
        <label>Last name: <input type="text" name="lastname" /></label>
      </p>
      <p>
        <label><input type="password" name="pwd" /></label>
      </p>

      <fieldset>
        <legend>Pet preference</legend>

        <p>
          <label><input type="radio" name="pet" value="cat" /> Cat</label>
        </p>
        <p>
          <label><input type="radio" name="pet" value="dog" /> Dog</label>
        </p>
      </fieldset>

      <fieldset>
        <legend>Owned vehicles</legend>

        <p>
          <label
 ><input type="checkbox" name="vehicle" value="Bike" />I have a
            bike</label
 >
        </p>
        <p>
          <label
 ><input type="checkbox" name="vehicle" value="Car" />I have a
            car</label
 >
        </p>
      </fieldset>

      <p><button>Submit</button></p>
    </form>
  </body>
</html>

```


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlformelement](https://html.spec.whatwg.org/multipage/forms.html#htmlformelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLFormElement` | 1 | 12 | 1 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `acceptCharset` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `action` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `autocomplete` | 14 | 12 | 4 | 10 | 15 | 6 | 4.4 | 18 | 4 | 14 | 6 | 1.0 |
| `checkValidity` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 |
| `elements` | 1 | 12 | 1 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `encoding` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `enctype` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `formdata_event` | 77 | 79 | 72 | No | 64 | 15 | 77 | 77 | 79 | 55 | 15 | 12.0 |
| `length` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `method` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `name` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `noValidate` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 |
| `rel` | 108 | 108 | No | No | 94 | 15.4 | 108 | 108 | No | 73 | 15.4 | No |
| `relList` | 108 | 108 | No | No | 94 | 15.4 | 108 | 108 | No | 73 | 15.4 | No |
| `reportValidity` | 40 | 17 | 49 | No | 27 | 10.1 | 40 | 40 | 49 | 27 | 10.3 | 4.0 |
| `requestSubmit` | 76 | 79 | 75 | No | 63 | 16 | 76 | 76 | 79 | 54 | 16 | 12.0 |
| `reset` | 1 | 12 | 1 | 5.5 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `reset_event` | 1 | 12 | 6 | 9 | ≤12.1 | 3 | ≤37 | 18 | 6 | ≤12.1 | 1 | 1.0 |
| `submit` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `submit_event` | 1 | 12 | 1 | 9 | 8 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `target` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement>

HTMLFrameSetElement
===================



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The `HTMLFrameSetElement` interface provides special properties (beyond those of the regular [`HTMLElement`](htmlelement) interface they also inherit) for manipulating [`<frameset>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/frameset) elements.


 EventTarget Node Element HTMLElement HTMLFrameSetElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
`HTMLFrameSetElement.cols`  Deprecated 
  A string structured as a comma-separated list specifying the width of each column inside a frameset.

  
`HTMLFrameSetElement.rows`  Deprecated 
  A string structured as a comma-separated list specifying the height of each column inside a frameset.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Event handlers
--------------



The [`HTMLElement`](htmlelement) events are inherited.

 The following [`Window`](window) `onXYZ` event handler properties are also available as aliases targeting the `window` object. However, it is advised to listen to them on the `window` object directly rather than on `HTMLFrameSetElement`.

  **Note:** Using `addEventListener()` on `HTMLFrameSetElement` will not work for the `onXYZ` event handlers listed below. Listen to the events on the [`window`](window) object instead.

   [`HTMLFrameSetElement.onafterprint`](window/afterprint_event)  Fired after the associated document has started printing or the print preview has been closed.

  [`HTMLFrameSetElement.onbeforeprint`](window/beforeprint_event)  Fired when the associated document is about to be printed or previewed for printing.

  [`HTMLFrameSetElement.onbeforeunload`](window/beforeunload_event)  Fired when the window, the document and its resources are about to be unloaded.

  [`HTMLFrameSetElement.ongamepadconnected`](window/gamepadconnected_event)  Fired when the browser detects that a gamepad has been connected or the first time a button/axis of the gamepad is used.

  [`HTMLFrameSetElement.ongamepaddisconnected`](window/gamepaddisconnected_event)  Fired when the browser detects that a gamepad has been disconnected.

  [`HTMLFrameSetElement.onhashchange`](window/hashchange_event)  Fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the `#` symbol).

  [`HTMLFrameSetElement.onlanguagechange`](window/languagechange_event)  Fired when the user's preferred language changes.

  [`HTMLFrameSetElement.onmessage`](window/message_event)  Fired when the window receives a message, for example from a call to [`Window.postMessage()`](window/postmessage) from another browsing context.

  [`HTMLFrameSetElement.onmessageerror`](window/messageerror_event)  Fired when the window receives a message that can't be deserialized.

  [`HTMLFrameSetElement.onoffline`](window/offline_event)  Fired when the browser has lost access to the network and the value of [`Navigator.onLine`](navigator/online) switches to `false`.

  [`HTMLFrameSetElement.ononline`](window/online_event)  Fired when the browser has gained access to the network and the value of [`Navigator.onLine`](navigator/online) switches to `true`.

  [`HTMLFrameSetElement.onpagehide`](window/pagehide_event)  Fired when the browser hides the current page in the process of presenting a different page from the session's history.

  [`HTMLFrameSetElement.onpageshow`](window/pageshow_event)  Fired when the browser displays the window's document due to navigation.

  [`HTMLFrameSetElement.onpopstate`](window/popstate_event)  Fired when the active history entry changes while the user navigates the session history.

  [`HTMLFrameSetElement.onrejectionhandled`](window/rejectionhandled_event)  Fired whenever a JavaScript [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) is rejected and the rejection has been handled.

  [`HTMLFrameSetElement.onstorage`](window/storage_event)  Fired when a storage area (`localStorage`) has been modified in the context of another document.

  [`HTMLFrameSetElement.onunhandledrejection`](window/unhandledrejection_event)  Fired whenever a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) is rejected but the rejection was not handled.

  [`HTMLFrameSetElement.onunload`](window/unload_event)  Fired when the document is being unloaded.

  

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlframesetelement](https://html.spec.whatwg.org/multipage/obsolete.html#htmlframesetelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLFrameSetElement` | 1 | 12 | 1 | 4 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `cols` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `rows` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* HTML element implementing this interface: [`<frameset>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/frameset)
* The equivalent of this element outside of frames: [`HTMLFrameSetElement`](htmlframesetelement).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLFrameSetElement>

HTMLHeadingElement
==================



The `HTMLHeadingElement` interface represents the different heading elements, [`<h1>` through `<h6>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements). It inherits methods and properties from the [`HTMLElement`](htmlelement) interface.


 EventTarget Node Element HTMLElement HTMLHeadingElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
`HTMLHeadingElement.align`  Deprecated 
  A string representing an enumerated attribute indicating alignment of the heading with respect to the surrounding context. The possible values are `"left"`, `"right"`, `"justify"`, and `"center"`.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlheadingelement](https://html.spec.whatwg.org/multipage/sections.html#htmlheadingelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLHeadingElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `align` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [h1](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements), [h2](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements), [h3](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements), [h4](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements), [h5](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements), and [h6](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLHeadingElement>

HTMLLabelElement
================



The `HTMLLabelElement` interface gives access to properties specific to [`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label) elements. It inherits methods and properties from the base [`HTMLElement`](htmlelement) interface.


 EventTarget Node Element HTMLElement HTMLLabelElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
[`HTMLLabelElement.control`](htmllabelelement/control) Read only 
  A [`HTMLElement`](htmlelement) representing the control with which the label is associated.

  
[`HTMLLabelElement.form`](htmllabelelement/form) Read only 
  A [`HTMLFormElement`](htmlformelement) object representing the form with which the labeled control is associated, or `null` if there is no associated control, or if that control isn't associated with a form. In other words, this is just a shortcut for `HTMLLabelElement.control.form`.

  [`HTMLLabelElement.htmlFor`](htmllabelelement/htmlfor)  A string containing the ID of the labeled control. This reflects the [`for`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label#for) attribute.

    **Note:** To programmatically set the `for` attribute, use [`htmlFor`](htmllabelelement/htmlfor).

 

Instance methods
----------------


*No specific methods; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmllabelelement](https://html.spec.whatwg.org/multipage/forms.html#htmllabelelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLLabelElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `control` | 6 | 18 | 4 | No | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `form` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `htmlFor` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label)
* [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form)
* [`HTMLFormElement`](htmlformelement)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLLabelElement>

HTMLLegendElement
=================



The `HTMLLegendElement` is an interface allowing to access properties of the [`<legend>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/legend) elements. It inherits properties and methods from the [`HTMLElement`](htmlelement) interface.


 EventTarget Node Element HTMLElement HTMLLegendElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
`HTMLLegendElement.form` Read only 
  A [`HTMLFormElement`](htmlformelement) representing the form that this legend belongs to. If the legend has a fieldset element as its parent, then this attribute returns the same value as the **form** attribute on the parent fieldset element. Otherwise, it returns null.

  `HTMLLegendElement.accessKey`  A string representing a single-character access key to give access to the element.

  
`HTMLLegendElement.align`  Deprecated 
  A string representing the alignment relative to the form set

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmllegendelement](https://html.spec.whatwg.org/multipage/form-elements.html#htmllegendelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLLegendElement` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `align` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `form` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<legend>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/legend)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLLegendElement>

HTMLLIElement
=============



The `HTMLLIElement` interface exposes specific properties and methods (beyond those defined by regular [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating list elements.


 EventTarget Node Element HTMLElement HTMLLIElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
`HTMLLIElement.type`  Deprecated 
  A string representing the type of the bullets, `"disc"`, `"square"` or `"circle"`. As the standard way of defining the list type is via the CSS [`list-style-type`](https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-type) property, use the CSSOM methods to set it via a script.

  `HTMLLIElement.value`  A `long` indicating the ordinal position of the *list element* inside a given [`<ol>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol). It reflects the [`value`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li#value) attribute of the HTML [`<li>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li) element, and can be smaller than `0`. If the [`<li>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li) element is not a child of an [`<ol>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol) element, the property has no meaning.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmllielement](https://html.spec.whatwg.org/multipage/grouping-content.html#htmllielement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLLIElement` | 1 | 12 | 1Before Firefox 10, Gecko incorrectly reflected negative value attributes to 0. | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4Before Firefox 10, Gecko incorrectly reflected negative value attributes to 0. | ≤12.1 | 1 | 1.0 |
| `type` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `value` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<li>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLLIElement>

HTMLLinkElement
===============



The `HTMLLinkElement` interface represents reference information for external resources and the relationship of those resources to a document and vice versa (corresponds to [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link) element; not to be confused with [`<a>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a), which is represented by [`HTMLAnchorElement`](htmlanchorelement)). This object inherits all of the properties and methods of the [`HTMLElement`](htmlelement) interface.


 EventTarget Node Element HTMLElement HTMLLinkElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  [`HTMLLinkElement.as`](htmllinkelement/as)  A string representing the type of content being loaded by the HTML link.

  `HTMLLinkElement.crossOrigin`  A string that corresponds to the CORS setting for this link element. See [CORS settings attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) for details.

  `HTMLLinkElement.disabled`  A boolean value which represents whether the link is disabled; currently only used with style sheet links.

  
[`HTMLLinkElement.fetchPriority`](htmllinkelement/fetchpriority)  Experimental 
  An optional string representing a hint given to the browser on how it should prioritize fetching of a preload relative to other resources of the same type. If this value is provided, it must be one of the possible permitted values: `high` to fetch at a higher priority, `low` to fetch at a lower priority, or `auto` to indicate no preference (which is the default).

  `HTMLLinkElement.href`  A string representing the URI for the target resource.

  `HTMLLinkElement.hreflang`  A string representing the language code for the linked resource.

  `HTMLLinkElement.media`  A string representing a list of one or more media formats to which the resource applies.

  [`HTMLLinkElement.referrerPolicy`](htmllinkelement/referrerpolicy)  A string that reflects the [`referrerpolicy`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#referrerpolicy) HTML attribute indicating which referrer to use.

  [`HTMLLinkElement.rel`](htmllinkelement/rel)  A string representing the forward relationship of the linked resource from the document to the resource.

  
[`HTMLLinkElement.relList`](htmllinkelement/rellist) Read only 
  A [`DOMTokenList`](domtokenlist) that reflects the [`rel`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#rel) HTML attribute, as a list of tokens.

  
`HTMLLinkElement.sizes` Read only 
  A [`DOMTokenList`](domtokenlist) that reflects the [`sizes`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#sizes) HTML attribute, as a list of tokens.

  
[`HTMLLinkElement.sheet`](htmllinkelement/sheet) Read only 
  Returns the [`StyleSheet`](stylesheet) object associated with the given element, or `null` if there is none.

  `HTMLLinkElement.type`  A string representing the MIME type of the linked resource.

  

### Obsolete properties


 
`HTMLLinkElement.charset`  Deprecated 
  A string representing the character encoding for the target resource.

  
`HTMLLinkElement.rev`  Deprecated 
  A string representing the reverse relationship of the linked resource from the resource to the document.

  **Note:** Currently the W3C HTML 5.2 spec states that `rev` is no longer obsolete, whereas the WHATWG living standard still has it labeled obsolete. Until this discrepancy is resolved, you should still assume it is obsolete.

   
`HTMLLinkElement.target`  Deprecated 
  A string representing the name of the target frame to which the resource applies.

  
Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmllinkelement](https://html.spec.whatwg.org/multipage/semantics.html#htmllinkelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLLinkElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `as` | 50 | 17 | 56 | No | 37 | 10 | 50 | 50 | 56 | 37 | 10 | 5.0 |
| `blocking` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `charset` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `crossOrigin` | 34 | 17 | 18 | No | 21 | 10 | 37 | 34 | 18 | 21 | 10 | 2.0 |
| `disabled` | 1In Chrome and other Blink-based browsers, adding the `disabled` attribute using JavaScript does not remove the stylesheet from `document.styleSheets`. | 12Since Edge 79, adding the `disabled` attribute using JavaScript does not remove the stylesheet from `document.styleSheets`. | 1 | 5.5 | ≤12.1In Chrome and other Blink-based browsers, adding the `disabled` attribute using JavaScript does not remove the stylesheet from `document.styleSheets`. | 1 | 1In Chrome and other Blink-based browsers, adding the `disabled` attribute using JavaScript does not remove the stylesheet from `document.styleSheets`. | 18In Chrome and other Blink-based browsers, adding the `disabled` attribute using JavaScript does not remove the stylesheet from `document.styleSheets`. | 4 | ≤12.1In Chrome and other Blink-based browsers, adding the `disabled` attribute using JavaScript does not remove the stylesheet from `document.styleSheets`. | 1 | 1.0In Chrome and other Blink-based browsers, adding the `disabled` attribute using JavaScript does not remove the stylesheet from `document.styleSheets`. |
| `fetchPriority` | 102101–102 | 102101–102 | No | No | 8887–88 | No | 102101–102 | 102101–102 | No | 70 | No | 19.0 |
| `href` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `hreflang` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `imageSizes` | 73 | 79 | 78 | No | 60 | No | 73 | 73 | 79 | 52 | No | 11.0 |
| `imageSrcset` | 73 | 79 | 78 | No | 60 | No | 73 | 73 | 79 | 52 | No | 11.0 |
| `integrity` | 45 | 17 | 43 | No | 32 | 11.1 | 45 | 45 | 43 | 32 | 11.3 | 5.0 |
| `media` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `referrerPolicy` | 58 | 79 | 50 | No | 45 | 14.1 | 58 | 58 | 50 | 43 | 14.5 | 7.0 |
| `rel` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `relList` | 50 | 17 | 30 | No | 37 | 9 | 50 | 50 | 30 | 37 | 9 | 5.0 |
| `rev` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `sheet` | 1 | 12 | 1 | 9 | 15 | 1 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `sizes` | 15Before Chrome 50, this property returned the deprecated child `DOMSettableTokenList` instead of `DOMTokenList`. | 79 | 31 | No | 15Before Opera 37, this property returned the deprecated child `DOMSettableTokenList` instead of `DOMTokenList`. | 6 | 4.4Before WebView 50, this property returned the deprecated child `DOMSettableTokenList` instead of `DOMTokenList`. | 18Before Chrome 50, this property returned the deprecated child `DOMSettableTokenList` instead of `DOMTokenList`. | 31 | 14Before Opera 37, this property returned the deprecated child `DOMSettableTokenList` instead of `DOMTokenList`. | 6 | 1.0Before Samsung Internet 5.0, this property returned the deprecated child `DOMSettableTokenList` instead of `DOMTokenList`. |
| `target` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `type` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLLinkElement>

HTMLMapElement
==============



The `HTMLMapElement` interface provides special properties and methods (beyond those of the regular object [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating the layout and presentation of map elements.


 EventTarget Node Element HTMLElement HTMLMapElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  `HTMLMapElement.name`  A string representing the [`<map>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/map) element for referencing it other context. If the `id` attribute is set, this must have the same value; and it cannot be `null` or empty.

  
`HTMLMapElement.areas` Read only 
  A live [`HTMLCollection`](htmlcollection) representing the [`<area>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area) elements associated to this [`<map>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/map).

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement) .*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlmapelement](https://html.spec.whatwg.org/multipage/image-maps.html#htmlmapelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLMapElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `areas` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `name` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* HTML element implementing this interface: [`<map>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/map).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLMapElement>

HTMLMarqueeElement
==================



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The `HTMLMarqueeElement` interface provides methods to manipulate [`<marquee>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/marquee) elements.

 It inherits properties and methods from the [`HTMLElement`](htmlelement) interface.


 EventTarget Node Element HTMLElement HTMLMarqueeElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
`HTMLMarqueeElement.behavior`  Deprecated 
  Sets how the text is scrolled within the marquee. Possible values are `scroll`, `slide` and `alternate`. If no value is specified, the default value is `scroll`.

  
`HTMLMarqueeElement.bgColor`  Deprecated 
  Sets the background color through color name or hexadecimal value.

  
`HTMLMarqueeElement.direction`  Deprecated 
  Sets the direction of the scrolling within the marquee. Possible values are `left`, `right`, `up` and `down`. If no value is specified, the default value is `left`.

  
`HTMLMarqueeElement.height`  Deprecated 
  Sets the height in pixels or percentage value.

  
`HTMLMarqueeElement.hspace`  Deprecated 
  Sets the horizontal margin.

  
`HTMLMarqueeElement.loop`  Deprecated 
  Sets the number of times the marquee will scroll. If no value is specified, the default value is −1, which means the marquee will scroll continuously.

  
`HTMLMarqueeElement.scrollAmount`  Deprecated 
  Sets the amount of scrolling at each interval in pixels. The default value is 6.

  
`HTMLMarqueeElement.scrollDelay`  Deprecated 
  Sets the interval between each scroll movement in milliseconds. The default value is 85. Note that any value smaller than 60 is ignored and the value 60 is used instead, unless `trueSpeed` is `true`.

  
`HTMLMarqueeElement.trueSpeed`  Deprecated 
  By default, `scrollDelay` values lower than 60 are ignored. If `trueSpeed` is `true`, then those values are not ignored.

  
`HTMLMarqueeElement.vspace`  Deprecated 
  Sets the vertical margin.

  
`HTMLMarqueeElement.width`  Deprecated 
  Sets the width in pixels or percentage value.

  

### Event handlers


 
`HTMLMarqueeElement.onbounce`  Deprecated 
  Fires when the marquee has reached the end of its scroll position. It can only fire when the behavior attribute is set to `alternate`.

  
`HTMLMarqueeElement.onfinish`  Deprecated 
  Fires when the marquee has finished the amount of scrolling that is set by the loop attribute. It can only fire when the loop attribute is set to some number that is greater than 0.

  
`HTMLMarqueeElement.onstart`  Deprecated 
  Fires when the marquee starts scrolling.

  
Instance methods
----------------



*Inherits methods from its parent, [`HTMLElement`](htmlelement).*

  
`HTMLMarqueeElement.start()`  Deprecated 
  Starts scrolling of the marquee.

  
`HTMLMarqueeElement.stop()`  Deprecated 
  Stops scrolling of the marquee.

  

Examples
--------




```
<marquee>This text will scroll from right to left</marquee>

<marquee direction="up">This text will scroll from bottom to top</marquee>

<marquee
 direction="down"
 width="250"
 height="200"
 behavior="alternate"
 style="border:solid">
  <marquee behavior="alternate"> This text will bounce </marquee>
</marquee>

```



Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlmarqueeelement](https://html.spec.whatwg.org/multipage/obsolete.html#htmlmarqueeelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLMarqueeElement` | 1 | 12 | 65Before Firefox 65, `<marquee>` implemented the `HTMLDivElement` interface. | 2 | 7.2 | 1.2 | 4.4 | 18 | 65Before Firefox 65, `<marquee>` implemented the `HTMLDivElement` interface. | 10.1 | 1 | 1.0 |
| `behavior` | 10 | 12 | 65 | 2 | 7.2 | 5.1 | 4.4 | 18 | 65 | 10.1 | 5 | 1.0 |
| `bgColor` | 10 | 12 | 65 | 2 | 7.2 | 5.1 | 4.4 | 18 | 65 | 10.1 | 5 | 1.0 |
| `bounce_event` | No | 12–79 | 65 | 5.5 | No | No | No | No | 65 | No | No | No |
| `direction` | 10 | 12 | 65 | 2 | 7.2 | 5.1 | 4.4 | 18 | 65 | 10.1 | 5 | 1.0 |
| `finish_event` | No | 12–79 | 65 | 5.5 | No | No | No | No | 65 | No | No | No |
| `height` | 10 | 12 | 65 | 2 | 7.2 | 5.1 | 4.4 | 18 | 65 | 10.1 | 5 | 1.0 |
| `hspace` | 10 | 12 | 65 | 5.5 | ≤12.1 | 5.1 | 4.4 | 18 | 65 | ≤12.1 | 5 | 1.0 |
| `loop` | 10 | 12 | 65 | 5.5 | ≤12.1 | 5.1 | 4.4 | 18 | 65 | ≤12.1 | 5 | 1.0 |
| `scrollAmount` | 10 | 12 | 65 | 2 | 7.2 | 5.1 | 4.4 | 18 | 65 | 10.1 | 5 | 1.0 |
| `scrollDelay` | 10 | 12 | 65 | 5.5 | ≤12.1 | 5.1 | 4.4 | 18 | 65 | ≤12.1 | 5 | 1.0 |
| `start` | 1 | 12 | 65 | 5.5 | ≤12.1 | 1.2 | 4.4 | 18 | 65 | ≤12.1 | 1 | 1.0 |
| `start_event` | No | 12–79 | 65 | 5.5 | No | No | No | No | 65 | No | No | No |
| `stop` | 1 | 12 | 65 | 5.5 | ≤12.1 | 1.2 | 4.4 | 18 | 65 | ≤12.1 | 1 | 1.0 |
| `trueSpeed` | 10 | 12 | 65 | 4 | 15 | 5.1 | 4.4 | 18 | 65 | 14 | 5 | 1.0 |
| `vspace` | 10 | 12 | 65 | 5.5 | ≤12.1 | 5.1 | 4.4 | 18 | 65 | ≤12.1 | 5 | 1.0 |
| `width` | 10 | 12 | 65 | 2 | 7.2 | 5.1 | 4.4 | 18 | 65 | 10.1 | 5 | 1.0 |


See also
--------


* [`<marquee>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/marquee)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLMarqueeElement>

HTMLMenuItemElement
===================



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.


**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The `HTMLMenuItemElement` interface provides special properties (beyond those defined on the regular [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating [`<menuitem>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/menuitem) elements.



Specifications
--------------


This feature is not part of any current specification. It is no longer on track to become a standard.


Browser compatibility
---------------------


See also
--------


* [`HTMLMenuElement`](htmlmenuelement)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLMenuItemElement>

HTMLMetaElement
===============



 The `HTMLMetaElement` interface contains descriptive metadata about a document provided in HTML as [`<meta>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta) elements. This interface inherits all of the properties and methods described in the [`HTMLElement`](htmlelement) interface. 


 EventTarget Node Element HTMLElement HTMLMetaElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  [`HTMLMetaElement.charset`](htmlmetaelement/charset)  The character encoding for a HTML document.

  [`HTMLMetaElement.content`](htmlmetaelement/content)  The 'value' part of the name-value pairs of the document metadata.

  [`HTMLMetaElement.httpEquiv`](htmlmetaelement/httpequiv)  The name of the pragma directive, the HTTP response header, for a document.

  [`HTMLMetaElement.media`](htmlmetaelement/media)  The media context for a `theme-color` metadata property.

  [`HTMLMetaElement.name`](htmlmetaelement/name)  The 'name' part of the name-value pairs defining the named metadata of a document.

  
[`HTMLMetaElement.scheme`](htmlmetaelement/scheme)  Deprecated 
   Defines the scheme of the value in the [`HTMLMetaElement.content`](htmlmetaelement/content) attribute. This is deprecated and should not be used on new web pages. 

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Examples
--------


 The following two examples show a general approach to using the `HTMLMetaElement` interface. For specific examples, see the pages for the individual properties as described in the [Instance properties](#instance_properties) section above. 


### Setting the page description metadata



 The following example creates a new `<meta>` element with a `name` attribute set to [`description`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta/name#standard_metadata_names_defined_in_the_html_specification). The `content` attribute sets a description of the document and is appended to the document `<head>`: 

 
```
let meta = document.createElement("meta");
meta.name = "description";
meta.content =
  "The <meta> element can be used to provide document metadata in terms of name-value pairs, with the name attribute giving the metadata name, and the content attribute giving the value.";
document.head.appendChild(meta);

```


### Setting the viewport metadata



 The following example shows how to create a new `<meta>` element with a `name` attribute set to [`viewport`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta/name#standard_metadata_names_defined_in_other_specifications). The `content` attribute sets the viewport size and is appended to the document `<head>`: 

 
```
var meta = document.createElement("meta");
meta.name = "viewport";
meta.content = "width=device-width, initial-scale=1";
document.head.appendChild(meta);

```
 For more information on setting the viewport, see [Viewport basics](https://developer.mozilla.org/en-US/docs/Web/HTML/Viewport_meta_tag#viewport_basics).



Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlmetaelement](https://html.spec.whatwg.org/multipage/semantics.html#htmlmetaelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLMetaElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `content` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `httpEquiv` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `media` | 93 | 93 | 106 | No | 79 | 15 | 93 | 93 | 106 | 66 | 15 | 17.0 |
| `name` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `scheme` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<meta>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLMetaElement>

HTMLMeterElement
================



The HTML [`<meter>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meter) elements expose the `HTMLMeterElement` interface, which provides special properties and methods (beyond the [`HTMLElement`](htmlelement) object interface they also have available to them by inheritance) for manipulating the layout and presentation of [`<meter>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meter) elements.


 EventTarget Node Element HTMLElement HTMLMeterElement

Instance properties
-------------------



*Also inherits properties from its parent, [`HTMLElement`](htmlelement).*

  `HTMLMeterElement.high`  A `double` representing the value of the high boundary, reflecting the [`high`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meter#high) attribute.

  `HTMLMeterElement.low`  A `double` representing the value of the low boundary, reflecting the [`low`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meter#low)attribute.

  `HTMLMeterElement.max`  A `double` representing the maximum value, reflecting the [`max`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meter#max) attribute.

  `HTMLMeterElement.min`  A `double` representing the minimum value, reflecting the [`min`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meter#min) attribute.

  `HTMLMeterElement.optimum`  A `double` representing the optimum, reflecting the [`optimum`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meter#optimum) attribute.

  `HTMLMeterElement.value`  A `double` representing the current value, reflecting the [`value`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meter#value) attribute.

  
[`HTMLMeterElement.labels`](htmlmeterelement/labels) Read only 
  A [`NodeList`](nodelist) of [`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label) elements that are associated with the element.

  

Instance methods
----------------


*This interface does not implement any specific methods but inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlmeterelement](https://html.spec.whatwg.org/multipage/form-elements.html#htmlmeterelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLMeterElement` | 6 | 12 | 16 | No | 11 | 6 | 4.4 | 18 | 16 | 11 | 6 | 1.0 |
| `high` | 6 | 13 | 16 | No | 11 | 6 | 4.4 | 18 | 16 | 11 | 6 | 1.0 |
| `labels` | 6 | 18 | 56 | No | ≤12.1 | 6 | 4.4 | 18 | 56 | ≤12.1 | 6 | 1.0 |
| `low` | 6 | 13 | 16 | No | 11 | 6 | 4.4 | 18 | 16 | 11 | 6 | 1.0 |
| `max` | 6 | 13 | 16 | No | 11 | 6 | 4.4 | 18 | 16 | 11 | 6 | 1.0 |
| `min` | 6 | 13 | 16 | No | 11 | 6 | 4.4 | 18 | 16 | 11 | 6 | 1.0 |
| `optimum` | 6 | 13 | 16 | No | 11 | 6 | 4.4 | 18 | 16 | 11 | 6 | 1.0 |
| `value` | 6 | 13 | 16 | No | 11 | 6 | 4.4 | 18 | 16 | 11 | 6 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<meter>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meter)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLMeterElement>

HTMLModElement
==============



The `HTMLModElement` interface provides special properties (beyond the regular methods and properties available through the [`HTMLElement`](htmlelement) interface they also have available to them by inheritance) for manipulating modification elements, that is [`<del>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/del) and [`<ins>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ins).


 EventTarget Node Element HTMLElement HTMLModElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  `HTMLModElement.cite`  A string reflecting the [`cite`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/del#cite) HTML attribute, containing a URI of a resource explaining the change.

  `HTMLModElement.dateTime`  A string reflecting the [`datetime`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/del#datetime) HTML attribute, containing a date-and-time string representing a timestamp for the change.

  

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlmodelement](https://html.spec.whatwg.org/multipage/edits.html#htmlmodelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLModElement` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `cite` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `dateTime` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* HTML elements implementing this interface: [`<ins>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ins), [`<del>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/del).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLModElement>

HTMLOListElement
================



The `HTMLOListElement` interface provides special properties (beyond those defined on the regular [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating ordered list elements.


 EventTarget Node Element HTMLElement HTMLOListElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  `HTMLOListElement.reversed`  A boolean value reflecting the [`reversed`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol#reversed) and defining if the numbering is descending, that is its value is `true`, or ascending (`false`).

  `HTMLOListElement.start`  A `long` value reflecting the [`start`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol#start) and defining the value of the first number of the first element of the list.

  `HTMLOListElement.type`  A string value reflecting the [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol#type) and defining the kind of marker to be used to display. It can have the following values:

 * `'1'` meaning that decimal numbers are used: `1`, `2`, `3`, `4`, `5`, …
* `'a'` meaning that the lowercase latin alphabet is used: `a`, `b`, `c`, `d`, `e`, …
* `'A'` meaning that the uppercase latin alphabet is used: `A`, `B`, `C`, `D`, `E`, …
* `'i'` meaning that the lowercase latin numerals are used: `i`, `ii`, `iii`, `iv`, `v`, …
* `'I'` meaning that the uppercase latin numerals are used: `I`, `II`, `III`, `IV`, `V`, …

  
`HTMLOListElement.compact`  Deprecated 
  A boolean value indicating that spacing between list items should be reduced. This property reflects the [`compact`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol#compact) attribute only, it doesn't consider the [`line-height`](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height) CSS property used for that behavior in modern pages.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlolistelement](https://html.spec.whatwg.org/multipage/grouping-content.html#htmlolistelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLOListElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `compact` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `reversed` | 18 | 79 | 18 | No | ≤12.1 | 6 | 4.4 | 18 | 18 | ≤12.1 | 6 | 1.0 |
| `start` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `type` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<ol>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLOListElement>

HTMLOptGroupElement
===================



The `HTMLOptGroupElement` interface provides special properties and methods (beyond the regular [`HTMLElement`](htmlelement) object interface they also have available to them by inheritance) for manipulating the layout and presentation of [`<optgroup>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup) elements.


 EventTarget Node Element HTMLElement HTMLOptGroupElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  `HTMLOptGroupElement.disabled`  A boolean value representing whether or not the whole list of children [`<option>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option) is disabled (true) or not (false).

  `HTMLOptGroupElement.label`  A string representing the label for the group.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmloptgroupelement](https://html.spec.whatwg.org/multipage/form-elements.html#htmloptgroupelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLOptGroupElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `disabled` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `label` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<optgroup>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLOptGroupElement>

HTMLOptionElement
=================



The `HTMLOptionElement` interface represents [`<option>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option) elements and inherits all properties and methods of the [`HTMLElement`](htmlelement) interface.


 EventTarget Node Element HTMLElement HTMLOptionElement

Constructor
-----------


 [`Option()`](htmloptionelement/option)  Returns a newly created `HTMLOptionElement` object. It has four parameters: the text to display, `text`, the value associated, `value`, the value of `defaultSelected`, and the value of `selected`. The last three parameters are optional.

  
Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  `HTMLOptionElement.defaultSelected`  Has a value of either `true` or `false` that shows the initial value of the [`selected`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option#selected) HTML attribute, indicating whether the option is selected by default or not.

  `HTMLOptionElement.disabled`  Has a value of either `true` or `false` representing the value of the [`disabled`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option#disabled) HTML attribute, which indicates that the option is unavailable to be selected. An option can also be disabled if it is a child of an [`<optgroup>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup) element that is disabled.

  
`HTMLOptionElement.form` Read only 
  A [`HTMLFormElement`](htmlformelement) representing the same value as the `form` of the corresponding [`<select>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select) element, if the option is a descendant of a [`<select>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select) element, or null if none is found.

  
`HTMLOptionElement.index` Read only 
  A `long` representing the position of the option within the list of options it belongs to, in tree-order. If the option is not part of a list of options, like when it is part of the [`<datalist>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist) element, the value is `0`.

  
`HTMLOptionElement.label` Read only 
  A string that reflects the value of the [`label`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option#label) HTML attribute, which provides a label for the option. If this attribute isn't specifically set, reading it returns the element's text content.

  `HTMLOptionElement.selected`  Has a value of either `true` or `false` that indicates whether the option is currently selected.

  `HTMLOptionElement.text`  A string that contains the text content of the element.

  `HTMLOptionElement.value`  A string that reflects the value of the [`value`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option#value) HTML attribute, if it exists; otherwise reflects value of the [`Node.textContent`](node/textcontent) property.

  

Instance methods
----------------


*Doesn't implement any specific method, but inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmloptionelement](https://html.spec.whatwg.org/multipage/form-elements.html#htmloptionelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Option` | 1 | 12 | 1 | 5.5Before Internet Explorer 9, the `outerHTML` of elements lose their text when constructing with `new Option()`. | ≤12.1 | 1.2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `HTMLOptionElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1.2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `defaultSelected` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `disabled` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `form` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `index` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `label` | 1 | 12 | 71–7Before Firefox 7 the `label` property incorrectly returned an empty string if not defined instead of returning the element's text content. | 6 | ≤12.1 | 3 | 4.4 | 18 | 74–7Before Firefox 7 the `label` property incorrectly returned an empty string if not defined instead of returning the element's text content. | ≤12.1 | 1 | 1.0 |
| `selected` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `text` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `value` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<option>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option).
* The [`HTMLOptionsCollection`](htmloptionscollection) interface.


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLOptionElement>

HTMLMediaElement
================



The `HTMLMediaElement` interface adds to [`HTMLElement`](htmlelement) the properties and methods needed to support basic media-related capabilities that are common to audio and video.

 The [`HTMLVideoElement`](htmlvideoelement) and [`HTMLAudioElement`](htmlaudioelement) elements both inherit this interface.


 EventTarget Node Element HTMLElement HTMLMediaElement

Instance properties
-------------------



*This interface also inherits properties from its ancestors [`HTMLElement`](htmlelement), [`Element`](element), [`Node`](node), and [`EventTarget`](eventtarget).*

  [`HTMLMediaElement.audioTracks`](htmlmediaelement/audiotracks)  An [`AudioTrackList`](audiotracklist) that lists the [`AudioTrack`](audiotrack) objects contained in the element.

  [`HTMLMediaElement.autoplay`](htmlmediaelement/autoplay)  A boolean value that reflects the [`autoplay`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#autoplay) HTML attribute, indicating whether playback should automatically begin as soon as enough media is available to do so without interruption.

  **Note:** Automatically playing audio when the user doesn't expect or desire it is a poor user experience and should be avoided in most cases, though there are exceptions. See the [Autoplay guide for media and Web Audio APIs](https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide) for more information. Keep in mind that browsers may ignore autoplay requests, so you should ensure that your code isn't dependent on autoplay working.

   
[`HTMLMediaElement.buffered`](htmlmediaelement/buffered) Read only 
  Returns a [`TimeRanges`](timeranges) object that indicates the ranges of the media source that the browser has buffered (if any) at the moment the `buffered` property is accessed.

  [`HTMLMediaElement.controls`](htmlmediaelement/controls)  A boolean that reflects the [`controls`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#controls) HTML attribute, indicating whether user interface items for controlling the resource should be displayed.

  
[`HTMLMediaElement.controlsList`](htmlmediaelement/controlslist) Read only 
  Returns a [`DOMTokenList`](domtokenlist) that helps the user agent select what controls to show on the media element whenever the user agent shows its own set of controls. The `DOMTokenList` takes one or more of three possible values: `nodownload`, `nofullscreen`, and `noremoteplayback`.

  [`HTMLMediaElement.crossOrigin`](htmlmediaelement/crossorigin)  A string indicating the [CORS setting](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) for this media element.

  
[`HTMLMediaElement.currentSrc`](htmlmediaelement/currentsrc) Read only 
  Returns a string with the absolute URL of the chosen media resource.

  [`HTMLMediaElement.currentTime`](htmlmediaelement/currenttime)  A double-precision floating-point value indicating the current playback time in seconds; if the media has not started to play and has not been seeked, this value is the media's initial playback time. Setting this value seeks the media to the new time. The time is specified relative to the media's timeline.

  [`HTMLMediaElement.defaultMuted`](htmlmediaelement/defaultmuted)  A boolean that reflects the [`muted`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#muted) HTML attribute, which indicates whether the media element's audio output should be muted by default.

  [`HTMLMediaElement.defaultPlaybackRate`](htmlmediaelement/defaultplaybackrate)  A `double` indicating the default playback rate for the media.

  [`HTMLMediaElement.disableRemotePlayback`](htmlmediaelement/disableremoteplayback)  A boolean that sets or returns the remote playback state, indicating whether the media element is allowed to have a remote playback UI.

  
[`HTMLMediaElement.duration`](htmlmediaelement/duration) Read only 
  A read-only double-precision floating-point value indicating the total duration of the media in seconds. If no media data is available, the returned value is `NaN`. If the media is of indefinite length (such as streamed live media, a WebRTC call's media, or similar), the value is `+Infinity`.

  
[`HTMLMediaElement.ended`](htmlmediaelement/ended) Read only 
  Returns a boolean that indicates whether the media element has finished playing.

  
[`HTMLMediaElement.error`](htmlmediaelement/error) Read only 
  Returns a [`MediaError`](mediaerror) object for the most recent error, or `null` if there has not been an error.

  [`HTMLMediaElement.loop`](htmlmediaelement/loop)  A boolean that reflects the [`loop`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#loop) HTML attribute, which indicates whether the media element should start over when it reaches the end.

  
[`HTMLMediaElement.mediaKeys`](htmlmediaelement/mediakeys) Read only 
  Returns a [`MediaKeys`](mediakeys) object, that is a set of keys that the element can use for decryption of media data during playback. If no key is available, it can be `null`.

  [`HTMLMediaElement.muted`](htmlmediaelement/muted)  A boolean that determines whether audio is muted. `true` if the audio is muted and `false` otherwise.

  
[`HTMLMediaElement.networkState`](htmlmediaelement/networkstate) Read only 
  Returns a `unsigned short` (enumeration) indicating the current state of fetching the media over the network.

  
[`HTMLMediaElement.paused`](htmlmediaelement/paused) Read only 
  Returns a boolean that indicates whether the media element is paused.

  [`HTMLMediaElement.playbackRate`](htmlmediaelement/playbackrate)  A `double` that indicates the rate at which the media is being played back.

  
`HTMLMediaElement.played` Read only 
  Returns a [`TimeRanges`](timeranges) object that contains the ranges of the media source that the browser has played, if any.

  `HTMLMediaElement.preload`  A string that reflects the [`preload`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#preload) HTML attribute, indicating what data should be preloaded, if any. Possible values are: `none`, `metadata`, `auto`.

  [`HTMLMediaElement.preservesPitch`](htmlmediaelement/preservespitch)  A boolean value that determines if the pitch of the sound will be preserved. If set to `false`, the pitch will adjust to the speed of the audio.

  
[`HTMLMediaElement.readyState`](htmlmediaelement/readystate) Read only 
  Returns a `unsigned short` (enumeration) indicating the readiness state of the media.

  
[`HTMLMediaElement.seekable`](htmlmediaelement/seekable) Read only 
  Returns a [`TimeRanges`](timeranges) object that contains the time ranges that the user is able to seek to, if any.

  
`HTMLMediaElement.seeking` Read only 
  Returns a boolean that indicates whether the media is in the process of seeking to a new position.

  
[`HTMLMediaElement.sinkId`](htmlmediaelement/sinkid) Read only   Experimental 
  Returns a string that is the unique ID of the audio device delivering output, or an empty string if it is using the user agent default. This ID should be one of the `MediaDeviceInfo.deviceid` values returned from [`MediaDevices.enumerateDevices()`](mediadevices/enumeratedevices), `id-multimedia`, or `id-communications`.

  [`HTMLMediaElement.src`](htmlmediaelement/src)  A string that reflects the [`src`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#src) HTML attribute, which contains the URL of a media resource to use.

  [`HTMLMediaElement.srcObject`](htmlmediaelement/srcobject)  A [`MediaStream`](mediastream) representing the media to play or that has played in the current `HTMLMediaElement`, or `null` if not assigned.

  
[`HTMLMediaElement.textTracks`](htmlmediaelement/texttracks) Read only 
  Returns a [`TextTrackList`](texttracklist) object containing the list of [`TextTrack`](texttrack) objects contained in the element.

  
[`HTMLMediaElement.videoTracks`](htmlmediaelement/videotracks) Read only 
  Returns a [`VideoTrackList`](videotracklist) object containing the list of [`VideoTrack`](videotrack) objects contained in the element.

  [`HTMLMediaElement.volume`](htmlmediaelement/volume)  A `double` indicating the audio volume, from 0.0 (silent) to 1.0 (loudest).

  

### Event handlers


 [`HTMLMediaElement.onencrypted`](htmlmediaelement)  Sets the event handler called when the media is encrypted.

  [`HTMLMediaElement.onwaitingforkey`](htmlmediaelement)  Sets the event handler called when playback is blocked while waiting for an encryption key.

  
Obsolete properties
-------------------



These properties are obsolete and should not be used, even if a browser still supports them.

  
[`HTMLMediaElement.controller`](htmlmediaelement/controller)  Deprecated   Non-standard 
  A `MediaController` object that represents the media controller assigned to the element, or `null` if none is assigned.

  
[`HTMLMediaElement.mediaGroup`](htmlmediaelement/mediagroup)  Deprecated   Non-standard 
  A string that reflects the [`mediagroup`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#mediagroup) HTML attribute, which indicates the name of the group of elements it belongs to. A group of media elements shares a common `MediaController`.

  
`HTMLMediaElement.mozAudioCaptured` Read only   Non-standard   Deprecated 
  Returns a boolean. Related to audio stream capture.

  
`HTMLMediaElement.mozFragmentEnd`  Non-standard   Deprecated 
  A `double` that provides access to the fragment end time if the media element has a fragment URI for `currentSrc`, otherwise it is equal to the media duration.

  

Instance methods
----------------



*This interface also inherits methods from its ancestors [`HTMLElement`](htmlelement), [`Element`](element), [`Node`](node), and [`EventTarget`](eventtarget).*

  `HTMLMediaElement.addTextTrack()`  Adds a new [`TextTrack`](texttrack) object (such as a track for subtitles) to a media element. This is a programmatic interface only and does not affect the DOM.

  [`HTMLMediaElement.captureStream()`](htmlmediaelement/capturestream)  Returns [`MediaStream`](mediastream), captures a stream of the media content.

  [`HTMLMediaElement.canPlayType()`](htmlmediaelement/canplaytype)  Given a string specifying a MIME media type (potentially with the [`codecs` parameter](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/codecs_parameter) included), `canPlayType()` returns the string `probably` if the media should be playable, `maybe` if there's not enough information to determine whether the media will play or not, or an empty string if the media cannot be played.

  [`HTMLMediaElement.fastSeek()`](htmlmediaelement/fastseek)  Quickly seeks to the given time with low precision.

  [`HTMLMediaElement.load()`](htmlmediaelement/load)  Resets the media to the beginning and selects the best available source from the sources provided using the [`src`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#src) attribute or the [`<source>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/source) element.

  [`HTMLMediaElement.pause()`](htmlmediaelement/pause)  Pauses the media playback.

  [`HTMLMediaElement.play()`](htmlmediaelement/play)  Begins playback of the media.

  
[`HTMLMediaElement.seekToNextFrame()`](htmlmediaelement/seektonextframe)  Deprecated 
  Seeks to the next frame in the media. This non-standard, experimental method makes it possible to manually drive reading and rendering of media at a custom speed, or to move through the media frame-by-frame to perform filtering or other operations.

  [`HTMLMediaElement.setMediaKeys()`](htmlmediaelement/setmediakeys)  Returns [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). Sets the [`MediaKeys`](mediakeys) keys to use when decrypting media during playback.

  [`HTMLMediaElement.setSinkId()`](htmlmediaelement/setsinkid)  Sets the ID of the audio device to use for output and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). This only works when the application is authorized to use the specified device.

  

Obsolete methods
----------------



*These methods are obsolete and should not be used, even if a browser still supports them.*

  
`HTMLMediaElement.mozCaptureStream()`  Non-standard 
  [enter description]

  
`HTMLMediaElement.mozCaptureStreamUntilEnded()`  Non-standard   Deprecated 
  [enter description]

  
`HTMLMediaElement.mozGetMetadata()`  Non-standard   Deprecated 
  Returns [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object), which contains properties that represent metadata from the playing media resource as `{key: value}` pairs. A separate copy of the data is returned each time the method is called. This method must be called after the [loadedmetadata](htmlmediaelement/loadedmetadata_event) event fires.

  

Events
------



*Inherits methods from its parent, [`HTMLElement`](htmlelement)*. Listen to these events using [`addEventListener()`](eventtarget/addeventlistener) or by assigning an event listener to the `oneventname` property of this interface.

  [`abort`](htmlmediaelement/abort_event)  Fired when the resource was not fully loaded, but not as the result of an error.

  [`canplay`](htmlmediaelement/canplay_event)  Fired when the user agent can play the media, but estimates that **not** enough data has been loaded to play the media up to its end without having to stop for further buffering of content.

  [`canplaythrough`](htmlmediaelement/canplaythrough_event)  Fired when the user agent can play the media, and estimates that enough data has been loaded to play the media up to its end without having to stop for further buffering of content.

  [`durationchange`](htmlmediaelement/durationchange_event)  Fired when the duration property has been updated.

  [`emptied`](htmlmediaelement/emptied_event)  Fired when the media has become empty; for example, when the media has already been loaded (or partially loaded), and the [`HTMLMediaElement.load()`](htmlmediaelement/load) method is called to reload it.

  [`ended`](htmlmediaelement/ended_event)  Fired when playback stops when end of the media (<audio> or <video>) is reached or because no further data is available.

  [`error`](htmlmediaelement/error_event)  Fired when the resource could not be loaded due to an error.

  [`loadeddata`](htmlmediaelement/loadeddata_event)  Fired when the first frame of the media has finished loading.

  [`loadedmetadata`](htmlmediaelement/loadedmetadata_event)  Fired when the metadata has been loaded.

  [`loadstart`](htmlmediaelement/loadstart_event)  Fired when the browser has started to load a resource.

  [`pause`](htmlmediaelement/pause_event)  Fired when a request to pause play is handled and the activity has entered its paused state, most commonly occurring when the media's [`HTMLMediaElement.pause()`](htmlmediaelement/pause) method is called.

  [`play`](htmlmediaelement/play_event)  Fired when the `paused` property is changed from `true` to `false`, as a result of the [`HTMLMediaElement.play()`](htmlmediaelement/play) method, or the `autoplay` attribute.

  [`playing`](htmlmediaelement/playing_event)  Fired when playback is ready to start after having been paused or delayed due to lack of data.

  [`progress`](htmlmediaelement/progress_event)  Fired periodically as the browser loads a resource.

  [`ratechange`](htmlmediaelement/ratechange_event)  Fired when the playback rate has changed.

  `resize`  Fired when one or both of the `videoWidth` and `videoHeight` properties have just been updated.

  [`seeked`](htmlmediaelement/seeked_event)  Fired when a seek operation completes.

  [`seeking`](htmlmediaelement/seeking_event)  Fired when a seek operation begins.

  [`stalled`](htmlmediaelement/stalled_event)  Fired when the user agent is trying to fetch media data, but data is unexpectedly not forthcoming.

  [`suspend`](htmlmediaelement/suspend_event)  Fired when the media data loading has been suspended.

  [`timeupdate`](htmlmediaelement/timeupdate_event)  Fired when the time indicated by the [`currentTime`](htmlmediaelement/currenttime) property has been updated.

  [`volumechange`](htmlmediaelement/volumechange_event)  Fired when the volume has changed.

  [`waiting`](htmlmediaelement/waiting_event)  Fired when playback has stopped because of a temporary lack of data.

  

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlmediaelement](https://html.spec.whatwg.org/multipage/media.html#htmlmediaelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLMediaElement` | 3 | 12 | 3.5 | 5.5 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `abort_event` | 3 | 12 | 9 | 9 | ≤12.1 | 3.1 | 4.4 | 18 | 9 | ≤12.1 | 3 | 1.0 |
| `addTextTrack` | 2623 | 12 | 31 | 11 | ≤12.1 | 6 | ≤374.4 | 2625 | 31 | ≤12.1 | 6 | 1.51.5 |
| `audioTracks` | 37 | 7912–79 | 33 | 10 | 24 | 7 | No | 37 | No | No | 7 | No |
| `autoplay` | 3 | 12 | 3.5 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 3 | 1.0 |
| `buffered` | 3 | 12 | 4 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 3 | 1.0 |
| `canPlayType` | 3["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 12["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 3.5["Before Firefox 28, `canPlayType()` returned `probably` when asked about WebM audio or video files without the `codecs` parameter. Since multiple codecs are supported, this is not enough information to determine if a file can be played, so `maybe` is now correctly returned.", "Before Firefox 101, `canPlayType()` ignored `codecs` parameter options for `av01` codecs (treating them as `av1`)."] | 9 | ≤12.1["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 4 | ≤37["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 18["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 4["Before Firefox 28, `canPlayType()` returned `probably` when asked about WebM audio or video files without the `codecs` parameter. Since multiple codecs are supported, this is not enough information to determine if a file can be played, so `maybe` is now correctly returned.", "Before Firefox 101, `canPlayType()` ignored `codecs` parameter options for `av01` codecs (treating them as `av1`)."] | ≤12.1["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 3 | 1.0["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] |
| `canplay_event` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `canplaythrough_event` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `captureStream` | 62 | 79 | 15 | No | 49 | No | 62 | 62 | 15 | 46 | No | 8.0 |
| `controller` | 17–36 | No | NoFirefox doesn't implement this yet. See [bug 847377](https://bugzil.la/847377). | No | 15–23 | 6 | 4.4–37 | 18–36 | NoFirefox doesn't implement this yet. See [bug 847377](https://bugzil.la/847377). | 14–24 | 6 | 1.0–3.0 |
| `controls` | 3 | 12 | 3.5 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 3 | 1.0 |
| `controlsList` | 58 | 79 | No | No | 45 | No | 58 | 58 | No | 43 | No | 7.0 |
| `crossOrigin` | 33 | 13 | 2212–22 | No | 20 | 10 | 4.4.3 | 33 | 2214–22 | 20 | 10 | 2.0 |
| `currentSrc` | 3 | 12 | 3.5 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 3 | 1.0 |
| `currentTime` | 3 | 12 | 3.5 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 3 | 1.0 |
| `defaultMuted` | 15 | 12 | 11 | No | ≤12.1 | 6 | 4.4 | 18 | 14 | ≤12.1 | 6 | 1.0 |
| `defaultPlaybackRate` | 3 | 12 | 20 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 20 | ≤12.1 | 3 | 1.0 |
| `disableRemotePlayback` | 49 | 79 | No | No | 36 | 13.1 | NoSee [bug 521319](https://crbug.com/521319). | 49 | No | 36 | 13 | 5.0 |
| `duration` | 3 | 12 | 3.5 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 3 | 1.0 |
| `durationchange_event` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `emptied_event` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `encrypted_event` | 42 | 13 | 38 | No | 29 | 12.1 | 42 | 42 | 38 | 29 | 12.2 | 4.0 |
| `ended` | 3 | 12 | 3.5 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 3 | 1.0 |
| `ended_event` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `error` | 3 | 12 | 3.5 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 3 | 1.0 |
| `error_event` | 3 | 12 | 6 | 9 | 11.6 | 3.1 | 4.4 | 18 | 6 | 12 | 3 | 1.0 |
| `fastSeek` | NoSee [bug 648207](https://crbug.com/648207). | NoSee [bug 648207](https://crbug.com/648207). | 31 | No | NoSee [bug 648207](https://crbug.com/648207). | 8 | NoSee [bug 648207](https://crbug.com/648207). | NoSee [bug 648207](https://crbug.com/648207). | 31 | NoSee [bug 648207](https://crbug.com/648207). | 8 | NoSee [bug 648207](https://crbug.com/648207). |
| `getStartDate` | No | No | No | No | No | 9 | No | No | No | No | 9 | No |
| `load` | 3 | 12 | 3.5 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 3 | 1.0 |
| `loadeddata_event` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `loadedmetadata_event` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `loadstart_event` | 3 | 12 | 6 | 9 | ≤12.1 | 4 | 4.4 | 18 | 6 | ≤12.1 | 3 | 1.0 |
| `loop` | 3 | 12 | 11 | 9 | ≤12.1 | 4 | ≤37 | 18 | 14 | ≤12.1 | 3 | 1.0 |
| `mediaGroup` | 17–36 | No | NoFirefox doesn't implement this yet. See [bug 847377](https://bugzil.la/847377). | No | 15–23 | 6 | 4.4–37 | 18–36 | NoFirefox doesn't implement this yet. See [bug 847377](https://bugzil.la/847377). | 14–24 | 6 | 1.0–3.0 |
| `mediaKeys` | 42 | 13 | 38 | No | 29 | 12.1 | 42 | 42 | 38 | 29 | 12.2 | 4.0 |
| `mozAudioCaptured` | No | No | 15 | No | No | No | No | No | 15 | No | No | No |
| `mozCaptureStreamUntilEnded` | No | No | 15 | No | No | No | No | No | 15 | No | No | No |
| `mozFragmentEnd` | No | No | 9 | No | No | No | No | No | 9 | No | No | No |
| `mozGetMetadata` | No | No | 17 | No | No | No | No | No | 17 | No | No | No |
| `muted` | 3 | 12 | 3.5 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 3 | 1.0 |
| `networkState` | 3 | 12 | 3.5The `NETWORK_LOADED` state was removed to align with the HTML spec in Firefox 4. | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 3 | 1.0 |
| `pause` | 3 | 12 | 3.5 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 3 | 1.0 |
| `pause_event` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `paused` | 3 | 12 | 3.5 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 3 | 1.0 |
| `play` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `play_event` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `playbackRate` | 3 | 12 | 20 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 20 | ≤12.1 | 3 | 1.0 |
| `played` | 3 | 12 | 15 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 15 | ≤12.1 | 3 | 1.0 |
| `playing_event` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `preload` | 5 | 12 | 4 | 9 | ≤12.1 | 5 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `preservesPitch` | 86 | 86 | 10120May be removed in a future release, see [bug 1765201](https://bugzil.la/1765201). | No | 72 | 4See [bug 214922](https://webkit.org/b/214922). | 86 | 86 | 10120May be removed in a future release, see [bug 1765201](https://bugzil.la/1765201). | 61 | 4See [bug 214922](https://webkit.org/b/214922). | 14.0 |
| `progress_event` | 3 | 12 | 6 | 9 | ≤12.1 | 3.1 | 4.4 | 18 | 6 | ≤12.1 | 3 | 1.0 |
| `ratechange_event` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `readyState` | 3 | 12 | 3.5 | 5.5 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 3 | 1.0 |
| `remote` | 56 | 79 | No | No | 43 | 13.1 | NoSee [bug 521319](https://crbug.com/521319). | 56 | No | 43 | 13.4 | 6.0 |
| `seekToNextFrame` | No | No | 56 | No | No | No | No | No | 56 | No | No | No |
| `seekable` | 3 | 12 | 8 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 8 | ≤12.1 | 3 | 1.0 |
| `seeked_event` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `seeking` | 3 | 12 | 3.5 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 3 | 1.0 |
| `seeking_event` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `setMediaKeys` | 42 | 13 | 38 | No | 29 | 12.1 | 42 | 42 | 38 | 29 | 12.2 | 4.0 |
| `setSinkId` | 49 | 17 | 64preview | No | 36 | No | NoNot available due to [a limitation in Android](https://crbug.com/648286). | NoNot available due to [a limitation in Android](https://crbug.com/648286). | No | NoNot available due to [a limitation in Android](https://crbug.com/648286). | No | NoNot available due to [a limitation in Android](https://crbug.com/648286). |
| `sinkId` | 49 | 17 | 64preview | No | 36 | No | NoNot available due to [a limitation in Android](https://crbug.com/648286). | NoNot available due to [a limitation in Android](https://crbug.com/648286). | No | NoNot available due to [a limitation in Android](https://crbug.com/648286). | No | NoNot available due to [a limitation in Android](https://crbug.com/648286). |
| `src` | 3 | 12 | 3.5 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 3 | 1.0 |
| `srcObject` | 108Support added for `MediaSourceHandle` objects transferred from dedicated workers where they were obtained from `MediaSource.handle` (see [bug 878133](https://crbug.com/878133)).52Support added for `MediaStream` objects (see [bug 506273](https://crbug.com/506273)). | 108Support added for `MediaSourceHandle` objects transferred from dedicated workers where they were obtained from `MediaSource.handle` (see [bug 878133](https://crbug.com/878133)).79Support added for `MediaStream` objects (see [bug 506273](https://crbug.com/506273)). | 42Only supports `MediaStream` objects (see [bug 886194](https://bugzil.la/886194)).18–58 | No | 94Support added for `MediaSourceHandle` objects transferred from dedicated workers where they were obtained from `MediaSource.handle` (see [bug 878133](https://crbug.com/878133)).39Support added for `MediaStream` objects (see [bug 506273](https://crbug.com/506273)). | 11 | 108Support added for `MediaSourceHandle` objects transferred from dedicated workers where they were obtained from `MediaSource.handle` (see [bug 878133](https://crbug.com/878133)).52Support added for `MediaStream` objects (see [bug 506273](https://crbug.com/506273)). | 108Support added for `MediaSourceHandle` objects transferred from dedicated workers where they were obtained from `MediaSource.handle` (see [bug 878133](https://crbug.com/878133)).52Support added for `MediaStream` objects (see [bug 506273](https://crbug.com/506273)). | 42Only supports `MediaStream` objects (see [bug 886194](https://bugzil.la/886194)).18–58 | 73Support added for `MediaSourceHandle` objects transferred from dedicated workers where they were obtained from `MediaSource.handle` (see [bug 878133](https://crbug.com/878133)).41Support added for `MediaStream` objects (see [bug 506273](https://crbug.com/506273)). | 11 | 6.0Support added for `MediaStream` objects (see [bug 506273](https://crbug.com/506273)). |
| `stalled_event` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `suspend_event` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `textTracks` | 23 | 12 | 31 | 10 | ≤12.1 | 6 | 4.4 | 25 | 31 | ≤12.1 | 6 | 1.0 |
| `timeupdate_event` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `videoTracks` | 37 | 7912–79 | 33 | No | 24 | 7 | No | 37 | No | No | 7 | No |
| `volume` | 3 | 12 | 3.5 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 3`volume` returns a value and is writable; however, the value is always 1, and setting a value has no effect on the volume of the media object. | 1.0 |
| `volumechange_event` | 3 | 12 | 6 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 6 | ≤12.1 | 3 | 1.0 |
| `waiting_event` | 3 | 12 | 6 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 6 | ≤12.1 | 3 | 1.0 |
| `waitingforkey_event` | 55 | 79 | 52 | No | 42 | 12.1 | 55 | 55 | 52 | 42 | 12.2 | 6.0 |


See also
--------


### References


* [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) and [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) HTML elements
* [`HTMLVideoElement`](htmlvideoelement) and [`HTMLAudioElement`](htmlaudioelement) interfaces, derived from `HTMLMediaElement`

### Guides


* [Web media technologies](https://developer.mozilla.org/en-US/docs/Web/Media)
* Learning area: [Video and audio content](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content)
* [Media type and format guide](https://developer.mozilla.org/en-US/docs/Web/Media/Formats)
* [Handling media support issues in web content](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Support_issues)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement>

HTMLMenuElement
===============



The `HTMLMenuElement` interface provides special properties (beyond those defined on the regular [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating [`<menu>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/menu) elements.


 EventTarget Node Element HTMLElement HTMLMenuElement

Constructor
-----------


 `HTMLMenuElement()`  Returns a newly constructed `HTMLMenuElement`.

  
Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement), and its ancestors.*

  
`compact`  Deprecated 
  A Boolean value determining if the menu displays in a compact way.

  
`type`  Deprecated   Non-standard 
   Returns `context` if the menu is a context menu. This use of the [`<menu>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/menu) element has never been implemented widely and is now deprecated. 

  
`label`  Deprecated   Non-standard 
   A string associating the menu with a name, displayed when the menu is used as a context menu. This use of the [`<menu>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/menu) element has never been implemented widely and is now deprecated. 

  

Instance methods
----------------



*Inherits methods from its parent, [`HTMLElement`](htmlelement), and its ancestors.*

 *`HTMLMenuElement` doesn't implement specific methods.*



Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlmenuelement](https://html.spec.whatwg.org/multipage/grouping-content.html#htmlmenuelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLMenuElement` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `compact` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* [`HTMLMenuItemElement`](htmlmenuitemelement)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLMenuElement>

HTMLObjectElement
=================



The `HTMLObjectElement` interface provides special properties and methods (beyond those on the [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating the layout and presentation of [`<object>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object) element, representing external resources.


 EventTarget Node Element HTMLElement HTMLObjectElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
`HTMLObjectElement.align`  Deprecated 
  A string representing an enumerated property indicating alignment of the element's contents with respect to the surrounding context. The possible values are `"left"`, `"right"`, `"justify"`, and `"center"`.

  
`HTMLObjectElement.archive`  Deprecated 
  A string that reflects the [`archive`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object#archive) HTML attribute, containing a list of archives for resources for this object.

  
`HTMLObjectElement.border`  Deprecated 
  A string that reflects the [`border`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object#border) HTML attribute, specifying the width of a border around the object.

  
`HTMLObjectElement.code`  Deprecated 
  A string representing the name of an applet class file, containing either the applet's subclass, or the path to get to the class, including the class file itself.

  
`HTMLObjectElement.codeBase`  Deprecated 
  A string that reflects the [`codebase`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object#codebase) HTML attribute, specifying the base path to use to resolve relative URIs.

  
`HTMLObjectElement.codeType`  Deprecated 
  A string that reflects the [`codetype`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object#codetype) HTML attribute, specifying the content type of the data.

  
[`HTMLObjectElement.contentDocument`](htmlobjectelement/contentdocument) Read only 
  Returns a [`Document`](document) representing the active document of the object element's nested browsing context, if any; otherwise `null`.

  
[`HTMLObjectElement.contentWindow`](htmlobjectelement/contentwindow) Read only 
  Returns a [WindowProxy](https://developer.mozilla.org/en-US/docs/Glossary/WindowProxy) representing the window proxy of the object element's nested browsing context, if any; otherwise `null`.

  [`HTMLObjectElement.data`](htmlobjectelement/data)  Returns a string that reflects the [`data`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object#data) HTML attribute, specifying the address of a resource's data.

  
`HTMLObjectElement.declare`  Deprecated 
  A boolean value that reflects the [`declare`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object#declare) HTML attribute, indicating that this is a declaration, not an instantiation, of the object.

  
[`HTMLObjectElement.form`](htmlobjectelement/form) Read only 
  Returns a [`HTMLFormElement`](htmlformelement) representing the object element's form owner, or null if there isn't one.

  [`HTMLObjectElement.height`](htmlobjectelement/height)  Returns a string that reflects the [`height`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object#height) HTML attribute, specifying the displayed height of the resource in CSS pixels.

  
`HTMLObjectElement.hspace`  Deprecated 
  A `long` representing the horizontal space in pixels around the control.

  [`HTMLObjectElement.name`](htmlobjectelement/name)  Returns a string that reflects the [`name`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object#name) HTML attribute, specifying the name of the browsing context.

  
`HTMLObjectElement.standby`  Deprecated 
  A string that reflects the [`standby`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object#standby) HTML attribute, specifying a message to display while the object loads.

  [`HTMLObjectElement.type`](htmlobjectelement/type)  A string that reflects the [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object#type) HTML attribute, specifying the MIME type of the resource.

  [`HTMLObjectElement.useMap`](htmlobjectelement/usemap)  A string that reflects the [`usemap`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object#usemap) HTML attribute, specifying a [`<map>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/map) element to use.

  
[`HTMLObjectElement.validationMessage`](htmlobjectelement/validationmessage) Read only 
  Returns a string representing a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation (`willValidate` is `false`), or it satisfies its constraints.

  
[`HTMLObjectElement.validity`](htmlobjectelement/validity) Read only 
  Returns a [`ValidityState`](validitystate) with the validity states that this element is in.

  
`HTMLObjectElement.vspace`  Deprecated 
  A `long` representing the horizontal space in pixels around the control.

  [`HTMLObjectElement.width`](htmlobjectelement/width)  A string that reflects the [`width`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object#width) HTML attribute, specifying the displayed width of the resource in CSS pixels.

  
[`HTMLObjectElement.willValidate`](htmlobjectelement/willvalidate) Read only 
  Returns a boolean value that indicates whether the element is a candidate for constraint validation. Always `false` for `HTMLObjectElement` objects.

  

Instance methods
----------------



*Inherits methods from its parent, [`HTMLElement`](htmlelement).*

  [`HTMLObjectElement.checkValidity()`](htmlobjectelement/checkvalidity)  Returns a boolean value that always is `true`, because `object` objects are never candidates for constraint validation.

  [`HTMLObjectElement.setCustomValidity()`](htmlobjectelement/setcustomvalidity)  Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate.

  

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlobjectelement](https://html.spec.whatwg.org/multipage/iframe-embed-object.html#htmlobjectelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLObjectElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `align` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `archive` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `border` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `checkValidity` | 10 | 12 | 4 | 10 | ≤12.1 | 5.1 | ≤37 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `code` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `codeBase` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `codeType` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `contentDocument` | 1 | 12 | 1 | 8 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `contentWindow` | 53 | 17 | 22 | No | 40 | 13 | 53 | 53 | 22 | 41 | 13 | 6.0 |
| `data` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `declare` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `form` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `getSVGDocument` | 1 | 12 | 3.5 | 9 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `height` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `hspace` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `name` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `reportValidity` | 40 | 18 | 49 | No | 27 | 10.1 | 40 | 40 | 49 | 27 | 10.3 | 4.0 |
| `setCustomValidity` | 10 | 12 | 4 | 10 | ≤12.1 | 5.1 | ≤37 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `standby` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `type` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `useMap` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `validationMessage` | 10 | 12 | 4 | 10 | ≤12.1 | 5.1 | ≤37 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `validity` | 10 | 12 | 4 | 10 | ≤12.1 | 5.1 | ≤37 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `vspace` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `width` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `willValidate` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<object>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement>

HTMLOptionsCollection
=====================



The `HTMLOptionsCollection` interface represents a collection of [`<option>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option) HTML elements (in document order) and offers methods and properties for selecting from the list as well as optionally altering its items. This object is returned only by the `options` property of [select](htmlselectelement).


 HTMLCollection HTMLOptionsCollection

Instance properties
-------------------


 `length`  `unsigned long`. As optionally allowed by the spec, this property isn't read-only. You can either remove options from the end by lowering the value, or add blank options at the end by raising the value. Mozilla allows this, while other implementations could potentially throw a [DOMException](domexception).

  
Instance methods
----------------


*This interface inherits the methods of its parent, [`HTMLCollection`](htmlcollection).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-htmloptionscollection-interface](https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#the-htmloptionscollection-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLOptionsCollection` | 1 | 12 | 1 | ≤6 | ≤12.1 | 3 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `add` | 1 | 12 | 1 | ≤6 | ≤12.1 | 3 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `length` | 1 | 12 | 1 | ≤6 | ≤12.1 | 3 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `remove` | 1 | 12 | 4 | ≤6 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `selectedIndex` | 1 | 12 | 1 | ≤6 | ≤12.1 | 3 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* [HTMLCollection](htmlcollection)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLOptionsCollection>

HTMLPictureElement
==================



The `HTMLPictureElement` interface represents a [`<picture>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture) HTML element. It doesn't implement specific properties or methods.


 EventTarget Node Element HTMLElement HTMLPictureElement

Instance properties
-------------------


*No specific property, but inherits properties from its parent, [`HTMLElement`](htmlelement).*


Instance methods
----------------


*No specific method, but inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlpictureelement](https://html.spec.whatwg.org/multipage/embedded-content.html#htmlpictureelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLPictureElement` | 38 | 13 | 38 | No | 25 | 9.1 | 38 | 38 | 38 | 25 | 9.3 | 3.0 |


See also
--------


* The [`<picture>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture) HTML element that implements it.
* The [`HTMLImageElement`](htmlimageelement) and [`HTMLSourceElement`](htmlsourceelement) interfaces, often used in conjunction with a [`<picture>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture) element.


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLPictureElement>

HTMLProgressElement
===================



The `HTMLProgressElement` interface provides special properties and methods (beyond the regular [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating the layout and presentation of [`<progress>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress) elements.


 EventTarget Node Element HTMLElement HTMLProgressElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  `HTMLProgressElement.max`  A `double` value reflecting the content attribute of the same name, limited to numbers greater than zero. Its default value is `1.0`.

  
`HTMLProgressElement.position` Read only 
  Returns a `double` value returning the result of dividing the current value (`value`) by the maximum value (`max`); if the progress bar is an indeterminate progress bar, it returns `-1`.

  `HTMLProgressElement.value`  A `double` value that reflects the current value; if the progress bar is an indeterminate progress bar, it returns `0`.

  
[`HTMLProgressElement.labels`](htmlprogresselement/labels) Read only 
  Returns [`NodeList`](nodelist) containing the list of [`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label) elements that are labels for this element.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlprogresselement](https://html.spec.whatwg.org/multipage/form-elements.html#htmlprogresselement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLProgressElement` | 6 | 12 | 6 | 10 | ≤12.1 | 6 | 4.4 | 18 | 6 | ≤12.1 | 6 | 1.0 |
| `labels` | 6 | 18 | 56 | No | ≤12.1 | 6 | 4.4 | 18 | 56 | ≤12.1 | 6 | 1.0 |
| `max` | 6 | 12 | 6 | 10 | ≤12.1 | 6 | 4.4 | 18 | 6 | ≤12.1 | 6 | 1.0 |
| `position` | 6 | 12 | 6 | 10 | ≤12.1 | 6 | 4.4 | 18 | 6 | ≤12.1 | 6 | 1.0 |
| `value` | 6 | 12 | 6 | 10 | ≤12.1 | 6 | 4.4 | 18 | 6 | ≤12.1 | 6 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<progress>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLProgressElement>

HTMLOutputElement
=================



The `HTMLOutputElement` interface provides properties and methods (beyond those inherited from [`HTMLElement`](htmlelement)) for manipulating the layout and presentation of [`<output>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/output) elements.


 EventTarget Node Element HTMLElement HTMLOutputElement

Instance properties
-------------------



*This interface also inherits properties from its parent, [`HTMLElement`](htmlelement).*

  `HTMLOutputElement.defaultValue`  A string representing the default value of the element, initially the empty string.

  
`HTMLOutputElement.form` Read only 
  An [`HTMLFormElement`](htmlformelement) indicating the form associated with the control, reflecting the [`form`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/output#form) HTML attribute if it is defined.

  
`HTMLOutputElement.htmlFor` Read only 
  A [`DOMTokenList`](domtokenlist) reflecting the [`for`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/output#for) HTML attribute, containing a list of IDs of other elements in the same document that contribute to (or otherwise affect) the calculated `value`.

  
[`HTMLOutputElement.labels`](htmloutputelement/labels) Read only 
  A [`NodeList`](nodelist) of [`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label) elements associated with the element.

  `HTMLOutputElement.name`  A string reflecting the [`name`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/output#name) HTML attribute, containing the name for the control that is submitted with form data.

  
`HTMLOutputElement.type` Read only 
  The string "`output`".

  
`HTMLOutputElement.validationMessage` Read only 
  A string representing a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation (`willValidate` is `false`), or it satisfies its constraints.

  
`HTMLOutputElement.validity` Read only 
  A [`ValidityState`](validitystate) representing the validity states that this element is in.

  `HTMLOutputElement.value`  A string representing the value of the contents of the elements. Behaves like the [`Node.textContent`](node/textcontent) property.

  
`HTMLOutputElement.willValidate` Read only 
  A boolean value indicating whether the element is a candidate for constraint validation.

  

Instance methods
----------------



*This interface also inherits methods from its parent, [`HTMLElement`](htmlelement).*

  `HTMLOutputElement.checkValidity()`  Checks the validity of the element and returns a boolean value holding the check result.

  `HTMLOutputElement.reportValidity()`  This method reports the problems with the constraints on the element, if any, to the user. If there are problems, fires an [`invalid`](htmlinputelement/invalid_event) event at the element, and returns `false`; if there are no problems, it returns `true`.

 When the problem is reported, the user agent may focus the element and change the scrolling position of the document or perform some other action that brings the element to the user's attention. User agents may report more than one constraint violation if this element suffers from multiple problems at once. If the element is not rendered, then the user agent may report the error for the running script instead of notifying the user.

  `HTMLOutputElement.setCustomValidity()`  Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate.

  

Modes
-----


This element behaves in one of two modes: *default* mode and *value* mode.


### Default mode



Initially, the element is in default mode, and so the contents of the element represent both the value of the element and its default value.

 If the element is in default mode when the descendants of the element are changed in any way, the `defaultValue` property is set to the value of the [`textContent`](node/textcontent) property.

 Resetting the form puts the element into default mode, and sets the [`textContent`](node/textcontent) property to the value of the `defaultValue` property.



### Value mode


The element goes into value mode when the contents of the `value` property are set. The `value` property otherwise behaves like the [`textContent`](node/textcontent) property. When the element is in value mode, the default value is accessible only through the `defaultValue` property.


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmloutputelement](https://html.spec.whatwg.org/multipage/form-elements.html#htmloutputelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLOutputElement` | No | No | No | No | No | 15 | No | No | No | No | 15 | No |
| `HTMLOutputElement` | 9 | 14 | 4 | No | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `checkValidity` | 9 | 14 | 4 | No | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `defaultValue` | 9 | 14 | 4 | No | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `form` | 9 | 14 | 4 | No | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `htmlFor` | 9Before Chrome 50, this property returned the deprecated child `DOMSettableTokenList` instead of `DOMTokenList`. | 14 | 4 | No | 15Before Opera 37, this property returned the deprecated child `DOMSettableTokenList` instead of `DOMTokenList`. | 5.1 | 3Before Chrome 50, this property returned the deprecated child `DOMSettableTokenList` instead of `DOMTokenList`. | 18Before Chrome 50, this property returned the deprecated child `DOMSettableTokenList` instead of `DOMTokenList`. | 4 | 14Before Opera 37, this property returned the deprecated child `DOMSettableTokenList` instead of `DOMTokenList`. | 5 | 1.0Before Samsung Internet 5.0, this property returned the deprecated child `DOMSettableTokenList` instead of `DOMTokenList`. |
| `labels` | 9 | 18 | 56 | No | ≤12.1 | 5.1 | 3 | 18 | 56 | ≤12.1 | 5 | 1.0 |
| `name` | 9 | 14 | 4 | No | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `reportValidity` | 40 | 14 | 49 | No | 27 | 10.1 | 40 | 40 | 49 | 27 | 10.3 | 4.0 |
| `setCustomValidity` | 9 | 14 | 4 | No | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `type` | 9 | 14 | 4 | No | 15 | 5.1 | 3 | 18 | 4 | 14 | 5 | 1.0 |
| `validationMessage` | 9 | 14 | 4 | No | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `validity` | 9 | 14 | 4 | No | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `value` | 9 | 14 | 4 | No | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `willValidate` | 9 | 14 | 4 | No | ≤12.1 | 5.1 | 3 | 18 | 4 | ≤12.1 | 5 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<output>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/output).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLOutputElement>

HTMLParagraphElement
====================



The `HTMLParagraphElement` interface provides special properties (beyond those of the regular [`HTMLElement`](htmlelement) object interface it inherits) for manipulating [`<p>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p) elements.


 EventTarget Node Element HTMLElement HTMLParagraphElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
`HTMLParagraphElement.align`  Deprecated 
  A string representing an enumerated property indicating alignment of the element's contents with respect to the surrounding context. The possible values are `"left"`, `"right"`, `"justify"`, and `"center"`.

  

Instance methods
----------------


*No specific methods, inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlparagraphelement](https://html.spec.whatwg.org/multipage/grouping-content.html#htmlparagraphelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLParagraphElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `align` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<p>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLParagraphElement>

HTMLParamElement
================



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The `HTMLParamElement` interface provides special properties (beyond those of the regular [`HTMLElement`](htmlelement) object interface it inherits) for manipulating [`<param>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/param) elements, representing a pair of a key and a value that acts as a parameter for an [`<object>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object) element.


 EventTarget Node Element HTMLElement HTMLParamElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
`HTMLParamElement.name`  Deprecated 
  A string representing the name of the parameter. It reflects the [`name`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/param#name) attribute.

  
`HTMLParamElement.value`  Deprecated 
  A string representing the value associated to the parameter. It reflects the [`value`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/param#value) attribute.

  
`HTMLParamElement.type`  Deprecated 
  A string containing the type of the parameter when `valueType` has the `"ref"` value. It reflects the [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/param#type) attribute.

  
`HTMLParamElement.valueType`  Deprecated 
  A string containing the type of the `value`. It reflects the [valuetype](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/param#valuetype) attribute and has one of the values: `"data"`, `"ref"`, or `"object"`.

  

Instance methods
----------------


*No specific methods, inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlparamelement](https://html.spec.whatwg.org/multipage/obsolete.html#htmlparamelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLParamElement` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `name` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `type` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `value` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `valueType` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<param>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/param).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLParamElement>

HTMLPreElement
==============



The `HTMLPreElement` interface exposes specific properties and methods (beyond those of the [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating a block of preformatted text ([`<pre>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre)).


 EventTarget Node Element HTMLElement HTMLPreElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
`HTMLPreElement.width`  Deprecated 
  A `long` value reflecting the obsolete [`width`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre#width) attribute, containing a fixed-size length for the [`<pre>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre) element.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlpreelement](https://html.spec.whatwg.org/multipage/grouping-content.html#htmlpreelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLPreElement` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `width` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<pre>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLPreElement>

HTMLQuoteElement
================



The `HTMLQuoteElement` interface provides special properties and methods (beyond the regular [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating quoting elements, like [`<blockquote>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote) and [`<q>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q), but not the [`<cite>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/cite) element.


 EventTarget Node Element HTMLElement HTMLQuoteElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  `HTMLQuoteElement.cite`  A string reflecting the [`cite`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote#cite) HTML attribute, containing a URL for the source of the quotation.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlquoteelement](https://html.spec.whatwg.org/multipage/grouping-content.html#htmlquoteelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLQuoteElement` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `cite` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML elements implementing this interface: [`<blockquote>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote) and [`<q>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q), but not [`<cite>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/cite).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLQuoteElement>

HTMLScriptElement
=================



HTML [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) elements expose the `HTMLScriptElement` interface, which provides special properties and methods for manipulating the behavior and execution of `<script>` elements (beyond the inherited [`HTMLElement`](htmlelement) interface).

 JavaScript files should be served with the `application/javascript` [MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types), but browsers are lenient and block them only if the script is served with an image type (`image/*`), video type (`video/*`), audio type (`audio/*`), or `text/csv`. If the script is blocked, its element receives an [`error`](element/error_event) event; otherwise, it receives a [`load`](window/load_event) event.


 EventTarget Node Element HTMLElement HTMLScriptElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  `HTMLScriptElement.type`  A string representing the MIME type of the script. It reflects the [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#type) attribute.

  `HTMLScriptElement.src`  A string representing the URL of an external script. It reflects the [`src`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#src) attribute.

  
`HTMLScriptElement.event`  Deprecated 
  A string; an obsolete way of registering event handlers on elements in an HTML document.

  
`HTMLScriptElement.charset`  Deprecated 
  A string representing the character encoding of an external script. It reflects the [`charset`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#charset) attribute.

  
`HTMLScriptElement.async`, `HTMLScriptElement.defer`
  The `async` and `defer` attributes are boolean attributes that control how the script should be executed. **The `defer` and `async` attributes must not be specified if the `src` attribute is absent.**

 There are three possible execution modes:

 1. If the `async` attribute is present, then the script will be executed asynchronously as soon as it downloads.
2. If the `async` attribute is absent but the `defer` attribute is present, then the script is executed when [the page has finished parsing](window/domcontentloaded_event).
3. If neither attribute is present, then the script is fetched and executed immediately, blocking further parsing of the page.

 The `defer` attribute may be specified with the `async` attribute, so legacy browsers that only support `defer` (and not `async`) fall back to the `defer` behavior instead of the default blocking behavior.

  **Note:** The exact processing details for these attributes are complex, involving many different aspects of HTML, and therefore are scattered throughout the specification. [These algorithms](https://html.spec.whatwg.org/multipage/scripting.html) describe the core ideas, but they rely on the parsing rules for [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) [start](https://html.spec.whatwg.org/multipage/syntax.html#start-tags) and [end](https://html.spec.whatwg.org/multipage/syntax.html#end-tags) tags in HTML, [in foreign content](https://html.spec.whatwg.org/multipage/syntax.html#foreign-elements), and [in XML](https://html.spec.whatwg.org/multipage/xhtml.html); the rules for the [`document.write()`](document/write) method; the handling of [scripting](https://html.spec.whatwg.org/multipage/webappapis.html); and so on.

   `HTMLScriptElement.crossOrigin`  A string reflecting the [CORS setting](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin) for the script element. For scripts from other [origins](https://developer.mozilla.org/en-US/docs/Glossary/Origin), this controls if error information will be exposed.

  `HTMLScriptElement.text`  A string that joins and returns the contents of all [`Text` nodes](text) inside the [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) element (ignoring other nodes like comments) in tree order. On setting, it acts the same way as the [`textContent`](node/textcontent) IDL attribute.

  **Note:** When inserted using the [`document.write()`](document/write) method, [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) elements execute (typically synchronously), but when inserted using [`innerHTML`](element/innerhtml) or [`outerHTML`](element/outerhtml), they do not execute at all.

   
`HTMLScriptElement.fetchPriority`  Experimental 
  An optional string representing a hint given to the browser on how it should prioritize fetching of an external script relative to other external scripts. If this value is provided, it must be one of the possible permitted values: `high` to fetch at a high priority, `low` to fetch at a low priority, or `auto` to indicate no preference (which is the default).

  `HTMLScriptElement.noModule`  A boolean value that if true, stops the script's execution in browsers that support [ES modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) — used to run fallback scripts in older browsers that do *not* support JavaScript modules.

  [`HTMLScriptElement.referrerPolicy`](htmlscriptelement/referrerpolicy)  A string that reflects the [`referrerPolicy`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#referrerpolicy) HTML attribute indicating which referrer to use when fetching the script, and fetches done by that script.

  

Static methods
--------------


 [`HTMLScriptElement.supports()`](htmlscriptelement/supports)   Returns `true` if the browser supports scripts of the specified type and `false` otherwise. This method provides a simple and unified method for script-related feature detection. 

  
Instance methods
----------------


*No specific methods; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Events
------


*No specific events; inherits events from its parent, [`HTMLElement`](htmlelement).*


Examples
--------


### Dynamically importing scripts



 Let's create a function that imports new scripts within a document creating a [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) node *immediately before* the [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) that hosts the following code (through [`document.currentScript`](document/currentscript)). These scripts will be **asynchronously** executed. For more details, see the [`defer`](#defer_property) and [`async`](#async_property) properties. 

 
```
function loadError(oError) {
  throw new URIError(`The script ${oError.target.src} didn't load correctly.`);
}

function prefixScript(url, onloadFunction) {
  const newScript = document.createElement("script");
  newScript.onerror = loadError;
  if (onloadFunction) {
    newScript.onload = onloadFunction;
  }
  document.currentScript.parentNode.insertBefore(
    newScript,
    document.currentScript
  );
  newScript.src = url;
}

```
 This next function, instead of prepending the new scripts immediately before the [`document.currentScript`](document/currentscript) element, appends them as children of the [`<head>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head) tag.

 
```
function loadError(oError) {
  throw new URIError(`The script ${oError.target.src} didn't load correctly.`);
}

function affixScriptToHead(url, onloadFunction) {
  const newScript = document.createElement("script");
  newScript.onerror = loadError;
  if (onloadFunction) {
    newScript.onload = onloadFunction;
  }
  document.head.appendChild(newScript);
  newScript.src = url;
}

```
 Sample usage:

 
```
affixScriptToHead("myScript1.js");
affixScriptToHead("myScript2.js", () => {
  alert('The script "myScript2.js" has been correctly loaded.');
});

```


### Checking if a script type is supported



[`HTMLScriptElement.supports()`](htmlscriptelement/supports) provides a unified mechanism for checking whether a browser supports particular types of scripts.

 The example below shows how to check for module support, using the existence of the `noModule` attribute as a fallback.

 
```
function checkModuleSupport() {
  if ("supports" in HTMLScriptElement) {
    return HTMLScriptElement.supports("module");
  }
  return "noModule" in document.createElement("script");
}

```
 Classic scripts are assumed to be supported on all browsers.



Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlscriptelement](https://html.spec.whatwg.org/multipage/scripting.html#htmlscriptelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLScriptElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `async` | 6 | 12 | 3.6 | 10 | 15 | 5.1 | 3 | 18 | 4 | 14 | 5 | 1.0 |
| `blocking` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `charset` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `crossOrigin` | 19 | 14 | 14 | 11 | 15 | 6 | 4.4 | 25 | 14 | 14 | 6 | 1.5 |
| `defer` | 1 | 12 | 3.5 | 10Before Internet Explorer 10, it implemented `defer` by a proprietary specification. Since version 10 it conforms to the W3C specification. | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `event` | 1 | 12 | 1 | 5.5 | 15 | 3 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `fetchPriority` | 102101–102 | 102101–102 | No | No | 8887–88 | No | 102101–102 | 102101–102 | No | 70 | No | 19.0 |
| `htmlFor` | 1 | 12 | 1 | 5.5 | 15 | 3 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `integrity` | 45 | 17 | 43 | No | 32 | 11.1 | 43 | 45 | 43 | 32 | 11.3 | 5.0 |
| `noModule` | 61 | 16 | 60 | No | 48 | 11 | 61 | 61 | 60 | 45 | 11 | 8.0 |
| `referrerPolicy` | 70 | 79 | 65 | No | 57 | 14 | 70 | 70 | 65 | 49 | 14 | 10.0 |
| `src` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `supports` | 96 | 96 | 94 | No | 82 | 16 | 96 | 96 | 94 | 67 | 16 | 17.0 |
| `text` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `type` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* HTML [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) element
* HTML [`<noscript>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/noscript) element
* [`document.currentScript`](document/currentscript)
* [Web Workers](web_workers_api/using_web_workers) (code snippets similar to scripts but executed in [another global context](dedicatedworkerglobalscope))


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement>

HTMLSlotElement
===============



The `HTMLSlotElement` interface of the [Shadow DOM API](web_components/using_shadow_dom) enables access to the name and assigned nodes of an HTML [`<slot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot) element.


 EventTarget Node Element HTMLElement HTMLSlotElement

Instance properties
-------------------


 [`HTMLSlotElement.name`](htmlslotelement/name)  A string used to get and set the slot's name.

  
Instance methods
----------------


 [`HTMLSlotElement.assign()`](htmlslotelement/assign)  Sets the manually assigned nodes for this slot to the given nodes.

  [`HTMLSlotElement.assignedNodes()`](htmlslotelement/assignednodes)  Returns a sequence of the nodes assigned to this slot. If the `flatten` option is set to `true`, it returns a sequence of both the nodes assigned to this slot, and the nodes assigned to any other slots that are descendants of this slot. If no assigned nodes are found, it returns the slot's fallback content.

  [`HTMLSlotElement.assignedElements()`](htmlslotelement/assignedelements)  Returns a sequence of the elements assigned to this slot (and no other nodes). If the `flatten` option is set to `true`, it returns a sequence of both the elements assigned to this slot, and the elements assigned to any other slots that are descendants of this slot. If no assigned elements are found, it returns the slot's fallback content.

  
Events
------


 [`slotchange`](htmlslotelement/slotchange_event)  Fired on an `HTMLSlotElement` instance ([`<slot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot) element) when the node(s) contained in that slot change.

  
Examples
--------



The following snippet is taken from our [slotchange example](https://github.com/mdn/web-components-examples/tree/main/slotchange) ([see it live also](https://mdn.github.io/web-components-examples/slotchange/)).

 
```
let slots = this.shadowRoot.querySelectorAll("slot");
slots[1].addEventListener("slotchange", (e) => {
  let nodes = slots[1].assignedNodes();
  console.log(
    `Element in Slot "${slots[1].name}" changed to "${nodes[0].outerHTML}".`
  );
});

```
 Here we grab references to all the slots, then add a slotchange event listener to the 2nd slot in the template — which is the one that keeps having its contents changed in the example.

 Every time the element inserted in the slot changes, we log a report to the console saying which slot has changed, and what the new node inside the slot is.



Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlslotelement](https://html.spec.whatwg.org/multipage/scripting.html#htmlslotelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLSlotElement` | 53 | 79 | 63 | No | 40 | 10 | 53 | 53 | 63 | 41 | 10 | 6.0 |
| `assign` | 86 | 86 | 92 | No | 72 | 16.4 | 86 | 86 | 92 | 61 | 16.4 | 14.0 |
| `assignedElements` | 65 | 79 | 66 | No | 52 | 12.1 | 65 | 65 | 66 | 47 | 12.2 | 9.0 |
| `assignedNodes` | 53 | 79 | 63 | No | 40 | 10 | 53 | 53 | 63 | 41 | 10 | 6.0 |
| `name` | 53 | 79 | 63 | No | 40 | 10 | 53 | 53 | 63 | 41 | 10 | 6.0 |
| `slotchange_event` | 53 | 79 | 63 | No | 40 | 10.1 | 53 | 53 | 63 | 41 | 10.3 | 6.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLSlotElement>

HTMLSpanElement
===============



The `HTMLSpanElement` interface represents a [`<span>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span) element and derives from the [`HTMLElement`](htmlelement) interface, but without implementing any additional properties or methods.


 EventTarget Node Element HTMLElement HTMLSpanElement

Instance properties
-------------------


*This interface has no properties, but inherits properties from: [`HTMLElement`](htmlelement).*


Instance methods
----------------


*This interface has no methods, but inherits methods from: [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlspanelement](https://html.spec.whatwg.org/multipage/text-level-semantics.html#htmlspanelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLSpanElement` | 15 | 12 | 1 | 5.5 | 15 | 6 | 4.4 | 18 | 4 | 14 | 6 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<span>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLSpanElement>

HTMLTableCaptionElement
=======================



The `HTMLTableCaptionElement` interface provides special properties (beyond the regular [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating table [`<caption>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption) elements.


 EventTarget Node Element HTMLElement HTMLTableCaptionElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
`HTMLTableCaptionElement.align`  Deprecated 
  A string which represents an enumerated attribute indicating alignment of the caption with respect to the table.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement)*.


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmltablecaptionelement](https://html.spec.whatwg.org/multipage/tables.html#htmltablecaptionelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLTableCaptionElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `align` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<caption>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCaptionElement>

HTMLSelectElement
=================



The `HTMLSelectElement` interface represents a [`<select>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select) HTML Element. These elements also share all of the properties and methods of other HTML elements via the [`HTMLElement`](htmlelement) interface.


 EventTarget Node Element HTMLElement HTMLSelectElement

Instance properties
-------------------



*This interface inherits the properties of [`HTMLElement`](htmlelement), and of [`Element`](element) and [`Node`](node).*

  [`HTMLSelectElement.autofocus`](htmlselectelement/autofocus)  A boolean value reflecting the [`autofocus`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#autofocus) HTML attribute, which indicates whether the control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form-associated element in a document can have this attribute specified.

  [`HTMLSelectElement.disabled`](htmlselectelement/disabled)  A boolean value reflecting the [`disabled`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#disabled) HTML attribute, which indicates whether the control is disabled. If it is disabled, it does not accept clicks.

  
[`HTMLSelectElement.form`](htmlselectelement/form) Read only 
  An [`HTMLFormElement`](htmlformelement) referencing the form that this element is associated with. If the element is not associated with of a [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) element, then it returns `null`.

  
[`HTMLSelectElement.labels`](htmlselectelement/labels) Read only 
  A [`NodeList`](nodelist) of [`<label>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label) elements associated with the element.

  `HTMLSelectElement.length`  An `unsigned long` The number of [`<option>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option) elements in this `select` element.

  `HTMLSelectElement.multiple`  A boolean value reflecting the [`multiple`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#multiple) HTML attribute, which indicates whether multiple items can be selected.

  `HTMLSelectElement.name`  A string reflecting the [`name`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#name) HTML attribute, containing the name of this control used by servers and DOM search functions.

  
[`HTMLSelectElement.options`](htmlselectelement/options) Read only 
  An [`HTMLOptionsCollection`](htmloptionscollection) representing the set of [`<option>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option) ([`HTMLOptionElement`](htmloptionelement)) elements contained by this element.

  `HTMLSelectElement.required`  A boolean value reflecting the [`required`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#required) HTML attribute, which indicates whether the user is required to select a value before submitting the form.

  [`HTMLSelectElement.selectedIndex`](htmlselectelement/selectedindex)  A `long` reflecting the index of the first selected [`<option>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option) element. The value `-1` indicates no element is selected.

  
[`HTMLSelectElement.selectedOptions`](htmlselectelement/selectedoptions) Read only 
  An [`HTMLCollection`](htmlcollection) representing the set of [`<option>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option) elements that are selected.

  `HTMLSelectElement.size`  A `long` reflecting the [`size`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select#size) HTML attribute, which contains the number of visible items in the control. The default is 1, unless `multiple` is `true`, in which case it is 4.

  
[`HTMLSelectElement.type`](htmlselectelement/type) Read only 
  A string representing the form control's type. When `multiple` is `true`, it returns `"select-multiple"`; otherwise, it returns `"select-one"`.

  
`HTMLSelectElement.validationMessage` Read only 
  A string representing a localized message that describes the validation constraints that the control does not satisfy (if any). This attribute is the empty string if the control is not a candidate for constraint validation (`willValidate` is false), or it satisfies its constraints.

  
`HTMLSelectElement.validity` Read only 
  A [`ValidityState`](validitystate) reflecting the validity state that this control is in.

  `HTMLSelectElement.value`  A string reflecting the value of the form control. Returns the `value` property of the first selected option element if there is one, otherwise the empty string.

  
`HTMLSelectElement.willValidate` Read only 
  A boolean value that indicates whether the button is a candidate for constraint validation. It is `false` if any conditions bar it from constraint validation.

  

Instance methods
----------------



*This interface inherits the methods of [`HTMLElement`](htmlelement), and of [`Element`](element) and [`Node`](node).*

  [`HTMLSelectElement.add()`](htmlselectelement/add)  Adds an element to the collection of `option` elements for this `select` element.

  
`HTMLSelectElement.blur()`  Deprecated 
  Removes input focus from this element. *This method is now implemented on [`HTMLElement`](htmlelement)*.

  [`HTMLSelectElement.checkValidity()`](htmlselectelement/checkvalidity)  Checks whether the element has any constraints and whether it satisfies them. If the element fails its constraints, the browser fires a cancelable [`invalid`](htmlinputelement/invalid_event) event at the element (and returns `false`).

  
`HTMLSelectElement.focus()`  Deprecated 
  Gives input focus to this element. *This method is now implemented on [`HTMLElement`](htmlelement)*.

  [`HTMLSelectElement.item()`](htmlselectelement/item)  Gets an item from the options collection for this [`<select>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select) element. You can also access an item by specifying the index in array-style brackets or parentheses, without calling this method explicitly.

  [`HTMLSelectElement.namedItem()`](htmlselectelement/nameditem)  Gets the item in the options collection with the specified name. The name string can match either the `id` or the `name` attribute of an option node. You can also access an item by specifying the name in array-style brackets or parentheses, without calling this method explicitly.

  [`HTMLSelectElement.remove()`](htmlselectelement/remove)  Removes the element at the specified index from the options collection for this `select` element.

  `HTMLSelectElement.reportValidity()`  This method reports the problems with the constraints on the element, if any, to the user. If there are problems, it fires a cancelable [`invalid`](htmlinputelement/invalid_event) event at the element, and returns `false`; if there are no problems, it returns `true`.

  [`HTMLSelectElement.setCustomValidity()`](htmlselectelement/setcustomvalidity)  Sets the custom validity message for the selection element to the specified message. Use the empty string to indicate that the element does *not* have a custom validity error.

  

Events
------



Listen to these events using [`addEventListener()`](eventtarget/addeventlistener) or by assigning an event listener to the `oneventname` property of this interface:

  
[`change`](htmlelement/change_event) event  Fires when the user selects an option.

  
[`input`](htmlelement/input_event) event  Fires when the `value` of an [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input), [`<select>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select), or [`<textarea>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea) element has been changed.

  

Example
-------


### Get information about the selected option




```
/\* assuming we have the following HTML
<select id='s'>
 <option>First</option>
 <option selected>Second</option>
 <option>Third</option>
</select>
\*/

const select = document.getElementById("s");

// return the index of the selected option
console.log(select.selectedIndex); // 1

// return the value of the selected option
console.log(select.options[select.selectedIndex].value); // Second

```
 A better way to track changes to the user's selection is to watch for the [`change`](htmlelement/change_event) event to occur on the `<select>`. This will tell you when the value changes, and you can then update anything you need to. See [the example provided](htmlelement/change_event#select_element) in the documentation for the `change` event for details.



Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlselectelement](https://html.spec.whatwg.org/multipage/form-elements.html#htmlselectelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLSelectElement` | 1 | 12 | 1You should watch for [change](https://developer.mozilla.org/docs/Web/Events/change) events on [`<select>`](https://developer.mozilla.org/docs/Web/HTML/Element/select) instead of watching `<option>` elements for events. See [bug 1090602](https://bugzil.la/1090602) and [Multiprocess Firefox Web content compatibility](https://developer.mozilla.org/docs/Mozilla/Firefox/Multiprocess_Firefox/Web_content_compatibility) for details. | 1 | 2 | 1 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 |
| `add` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `autocomplete` | 66 | 79 | 59 | No | 53≤12.1–15 | 9.1 | 66 | 66 | 59 | 47≤12.1–14 | 9.3 | 9.0 |
| `checkValidity` | 4 | 12 | 4 | 10 | 9 | 5 | ≤37 | 18 | 4 | 10.1 | 4 | 1.0 |
| `disabled` | 1 | 12 | 1 | 5.5 | 9 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `form` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `item` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `labels` | 6 | 18 | 56 | No | ≤12.1 | 5.1 | 3 | 18 | 56 | ≤12.1 | 5 | 1.0 |
| `length` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `multiple` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `name` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `namedItem` | 1 | 12`namedItem` does not appear to take the `name` attribute into account (only the `id` attribute) on Internet Explorer and Edge. There is a [bug report](https://connect.microsoft.com/IE/feedbackdetail/view/2414092/) to Microsoft about this. | 1 | 6`namedItem` does not appear to take the `name` attribute into account (only the `id` attribute) on Internet Explorer and Edge. There is a [bug report](https://connect.microsoft.com/IE/feedbackdetail/view/2414092/) to Microsoft about this. | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `options` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `remove` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `reportValidity` | 40 | 17 | 49 | No | 27 | 10.1 | 40 | 40 | 64 | 27 | 10.3 | 4.0 |
| `required` | 10 | 12 | 4 | 10 | ≤12.1 | 5.1 | ≤37 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `selectedIndex` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `selectedOptions` | 19 | 12 | 26 | No | 9 | 6 | 4.4 | 25 | 26 | 10.1 | 6 | 1.5 |
| `setCustomValidity` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 |
| `size` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `type` | 1 | 12 | 1 | 1 | 2 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `validationMessage` | 5 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 |
| `validity` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 |
| `value` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `willValidate` | 2 | 12 | 4 | 10 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3 | 1.0 |


See also
--------


* The [`<select>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select) HTML element, which implements this interface.


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement>

HTMLSourceElement
=================



The `HTMLSourceElement` interface provides special properties (beyond the regular [`HTMLElement`](htmlelement) object interface it also has available to it by inheritance) for manipulating [`<source>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/source) elements.


 EventTarget Node Element HTMLElement HTMLSourceElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  `HTMLSourceElement.media`  A string reflecting the [`media`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/source#media) HTML attribute, containing the intended type of the media resource.

  `HTMLSourceElement.sizes`  A string representing image sizes between breakpoints

  `HTMLSourceElement.src`  A string reflecting the [`src`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/source#src) HTML attribute, containing the URL for the media resource. The `HTMLSourceElement.src` property has a meaning only when the associated [`<source>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/source) element is nested in a media element that is a [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) or an [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) element. It has no meaning and is ignored when it is nested in a [`<picture>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture) element.

  **Note:** If the `src` property is updated (along with any siblings), the parent [`HTMLMediaElement`](htmlmediaelement)'s `load` method should be called when done, since `<source>` elements are not re-scanned automatically.

   `HTMLSourceElement.srcset`  A string reflecting the [`srcset`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/source#srcset) HTML attribute, containing a list of candidate images, separated by a comma (`',', U+002C COMMA`). A candidate image is a URL followed by a `'w'` with the width of the images, or an `'x'` followed by the pixel density.

  `HTMLSourceElement.type`  A string reflecting the [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/source#type) HTML attribute, containing the type of the media resource.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlsourceelement](https://html.spec.whatwg.org/multipage/embedded-content.html#htmlsourceelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLSourceElement` | 3 | 12 | 3.5 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 2 | 1.0 |
| `height` | 90 | 90 | 108 | No | 76 | 15 | 90 | 90 | 108 | 64 | 15 | 15.0 |
| `media` | 3 | 12 | 15 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 15 | ≤12.1 | 2 | 1.0 |
| `sizes` | 38 | 13 | 38 | No | 25 | 10.1The [`sizes`](https://developer.mozilla.org/docs/Web/HTML/Element/source#attr-sizes) attribute is supported since Safari 9.1. | 38 | 38 | 38 | 25 | 10.3The [`sizes`](https://developer.mozilla.org/docs/Web/HTML/Element/source#attr-sizes) attribute is supported since Safari 9.1. | 3.0 |
| `src` | 3 | 12 | 3.5 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 2 | 1.0 |
| `srcset` | 38 | 13 | 38 | No | 25 | 10.1The [`srcset`](https://developer.mozilla.org/docs/Web/HTML/Element/source#attr-srcset) attribute is supported since Safari 9.1. | 38 | 38 | 38 | 25 | 10.3The [`srcset`](https://developer.mozilla.org/docs/Web/HTML/Element/source#attr-srcset) attribute is supported since Safari 9.1. | 3.0 |
| `type` | 3 | 12 | 3.5 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 2 | 1.0 |
| `width` | 90 | 90 | 108 | No | 76 | 15 | 90 | 90 | 108 | 64 | 15 | 15.0 |


See also
--------


* The HTML element implementing this interface: [`<source>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/source).
* The HTML DOM APIs of the elements that can contain a [`<source>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/source) element: [`HTMLVideoElement`](htmlvideoelement), [`HTMLAudioElement`](htmlaudioelement), [`HTMLPictureElement`](htmlpictureelement).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLSourceElement>

HTMLStyleElement
================



The `HTMLStyleElement` interface represents a [`<style>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style) element. It inherits properties and methods from its parent, [`HTMLElement`](htmlelement).

 This interface doesn't allow to manipulate the CSS it contains (in most case). To manipulate CSS, see [Using dynamic styling information](css_object_model/using_dynamic_styling_information) for an overview of the objects used to manipulate specified CSS properties using the DOM.


 EventTarget Node Element HTMLElement HTMLStyleElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  [`HTMLStyleElement.media`](htmlstyleelement/media)  A string reflecting the HTML attribute representing the intended destination medium for style information.

  
[`HTMLStyleElement.type`](htmlstyleelement/type)  Deprecated 
  A string reflecting the HTML attribute representing the type of style being applied by this statement.

  [`HTMLStyleElement.disabled`](htmlstyleelement/disabled)  A boolean value indicating whether or not the associated stylesheet is disabled.

  
[`HTMLStyleElement.sheet`](htmlstyleelement/sheet) Read only 
  Returns the [`CSSStyleSheet`](cssstylesheet) object associated with the given element, or `null` if there is none.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlstyleelement](https://html.spec.whatwg.org/multipage/semantics.html#htmlstyleelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLStyleElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `blocking` | 105 | 105 | No | No | 91 | No | 105 | 105 | No | 72 | No | 20.0 |
| `disabled` | 1 | 13 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `media` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `sheet` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `type` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<style>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style).
* [Using dynamic styling information](css_object_model/using_dynamic_styling_information) to see how to manipulate CSS.


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLStyleElement>

HTMLTableCellElement
====================



The `HTMLTableCellElement` interface provides special properties and methods (beyond the regular [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating the layout and presentation of table cells, either header cells ([`<th>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/th))) or data cells ([`<td>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td)), in an HTML document.


 EventTarget Node Element HTMLElement HTMLTableCellElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  `HTMLTableCellElement.abbr`  A string which can be used on `<th>` elements (not on [`<td>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td)), specifying an alternative label for the header cell. This alternate label can be used in other contexts, such as when describing the headers that apply to a data cell. This is used to offer a shorter term for use by screen readers in particular, and is a valuable accessibility tool. Usually the value of `abbr` is an abbreviation or acronym, but can be any text that's appropriate contextually.

  
`HTMLTableCellElement.cellIndex` Read only 
  A long integer representing the cell's position in the `cells` collection of the [`<tr>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr) the cell is contained within. If the cell doesn't belong to a `<tr>`, it returns `-1`.

  `HTMLTableCellElement.colSpan`  An unsigned long integer indicating the number of columns this cell must span; this lets the cell occupy space across multiple columns of the table. It reflects the [`colspan`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td#colspan) attribute.

  
`HTMLTableCellElement.headers` Read only 
  A [`DOMTokenList`](domtokenlist) describing a list of `id` of [`<th>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/th) elements that represents headers associated with the cell. It reflects the [`headers`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td#headers) attribute.

  `HTMLTableCellElement.rowSpan`  An unsigned long integer indicating the number of rows this cell must span; this lets a cell occupy space across multiple rows of the table. It reflects the [`rowspan`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td#rowspan) attribute.

  `HTMLTableCellElement.scope`  A string indicating the scope of a [`<th>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/th) cell. Header cells can be configured, using the `scope` property, the apply to a specified row or column, or to the not-yet-scoped cells within the current row group (that is, the same ancestor [`<thead>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/thead), [`<tbody>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tbody), or [`<tfoot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tfoot) element). If no value is specified for `scope`, the header is not associated directly with cells in this way. Permitted values for `scope` are:

  `col`  The header cell applies to the following cells in the same column (or columns, if `colspan` is used as well), until either the end of the column or another `<th>` in the column establishes a new scope.

  `colgroup`  The header cell applies to all cells in the current column group that do not already have a scope applied to them. This value is only allowed if the cell is in a column group.

  `row`  The header cell applies to the following cells in the same row (or rows, if `rowspan` is used as well), until either the end of the row or another `<th>` in the same row establishes a new scope.

  `rowgroup`  The header cell applies to all cells in the current row group that do not already have a scope applied to them. This value is only allowed if the cell is in a row group.

  The empty string (`""`)  The header cell has no predefined scope; the user agent will establish the scope based on contextual clues.

    

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement)*.


Deprecated properties
---------------------



 **Warning:** These properties have been deprecated and should no longer be used. They are documented primarily to help understand older code bases.

   
`HTMLTableCellElement.align`  Deprecated 
  A string containing an enumerated value reflecting the [`align`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td#align) attribute. It indicates the alignment of the element's contents with respect to the surrounding context. The possible values are `"left"`, `"right"`, and `"center"`.

  
`HTMLTableCellElement.axis`  Deprecated 
  A string containing a name grouping cells in virtual. It reflects the obsolete [`axis`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td#axis) attribute.

  
`HTMLTableCellElement.bgColor`  Deprecated 
  A string containing the background color of the cells. It reflects the obsolete [`bgColor`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td#bgcolor) attribute.

  
`HTMLTableCellElement.ch`  Deprecated 
  A string containing one single character. This character is the one to align all the cell of a column on. It reflects the [`char`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td#char) and default to the decimal points associated with the language, e.g. `'.'` for English, or `','` for French. This property was optional and was not very well supported.

  
`HTMLTableCellElement.chOff`  Deprecated 
  A string containing an integer indicating how many characters must be left at the right (for left-to-right scripts; or at the left for right-to-left scripts) of the character defined by `HTMLTableCellElement.ch`. This property was optional and was not very well supported.

  
`HTMLTableCellElement.height`  Deprecated 
  A string containing a length of pixel of the hinted height of the cell. It reflects the obsolete [`height`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td#height) attribute.

  
`HTMLTableCellElement.noWrap`  Deprecated 
  A boolean value reflecting the [`nowrap`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td#nowrap) attribute and indicating if cell content can be broken in several lines.

  
`HTMLTableCellElement.vAlign`  Deprecated 
  A string representing an enumerated value indicating how the content of the cell must be vertically aligned. It reflects the [`valign`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td#valign) attribute and can have one of the following values: `"top"`, `"middle"`, `"bottom"`, or `"baseline"`. Use the CSS [`vertical-align`](https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align) property instead.

  
`HTMLTableCellElement.width`  Deprecated 
  A string specifying the number of pixels wide the cell should be drawn, if possible. This property reflects the also obsolete [`width`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td#width) attribute. Use the CSS [`width`](https://developer.mozilla.org/en-US/docs/Web/CSS/width) property instead.

  

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmltablecellelement](https://html.spec.whatwg.org/multipage/tables.html#htmltablecellelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLTableCellElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `abbr` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `align` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `axis` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `bgColor` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `cellIndex` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `ch` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `chOff` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `colSpan` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `headers` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `height` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `noWrap` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `rowSpan` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `scope` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `vAlign` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `width` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML elements implementing this interface: [`<th>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/th) and [`<td>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCellElement>

HTMLTableColElement
===================



The `HTMLTableColElement` interface provides properties for manipulating single or grouped table column elements.


 EventTarget Node Element HTMLElement HTMLTableColElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement)*.

  
`HTMLTableColElement.align`  Deprecated 
  A string that indicates the horizontal alignment of the cell data in the column.

  
`HTMLTableColElement.ch`  Deprecated 
  A string representing the alignment character for cell data.

  
`HTMLTableColElement.chOff`  Deprecated 
  A string representing the offset for the alignment character.

  `HTMLTableColElement.span`  An `unsigned long` that reflects the [`span`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/col#span) HTML attribute, indicating the number of columns to apply this object's attributes to. Must be a positive integer.

  
`HTMLTableColElement.vAlign`  Deprecated 
  A string that indicates the vertical alignment of the cell data in the column.

  
`HTMLTableColElement.width`  Deprecated 
  A string representing the default column width.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement)*.


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmltablecolelement](https://html.spec.whatwg.org/multipage/tables.html#htmltablecolelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLTableColElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `align` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `ch` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `chOff` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `span` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `vAlign` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `width` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<col>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/col) and [`<colgroup>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/colgroup).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableColElement>

HTMLTableElement
================



The `HTMLTableElement` interface provides special properties and methods (beyond the regular [`HTMLElement`](htmlelement) object interface it also has available to it by inheritance) for manipulating the layout and presentation of tables in an HTML document.


 EventTarget Node Element HTMLElement HTMLTableElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  [`HTMLTableElement.caption`](htmltableelement/caption)  A [`HTMLTableCaptionElement`](htmltablecaptionelement) representing the first [`<caption>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption) that is a child of the element, or `null` if none is found. When set, if the object doesn't represent a `<caption>`, a [`DOMException`](domexception) with the `HierarchyRequestError` name is thrown. If a correct object is given, it is inserted in the tree as the first child of this element and the first `<caption>` that is a child of this element is removed from the tree, if any.

  [`HTMLTableElement.tHead`](htmltableelement/thead)  A [`HTMLTableSectionElement`](htmltablesectionelement) representing the first [`<thead>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/thead) that is a child of the element, or `null` if none is found. When set, if the object doesn't represent a `<thead>`, a [`DOMException`](domexception) with the `HierarchyRequestError` name is thrown. If a correct object is given, it is inserted in the tree immediately before the first element that is neither a [`<caption>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption), nor a [`<colgroup>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/colgroup), or as the last child if there is no such element, and the first `<thead>` that is a child of this element is removed from the tree, if any.

  [`HTMLTableElement.tFoot`](htmltableelement/tfoot)  A [`HTMLTableSectionElement`](htmltablesectionelement) representing the first [`<tfoot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tfoot) that is a child of the element, or `null` if none is found. When set, if the object doesn't represent a `<tfoot>`, a [`DOMException`](domexception) with the `HierarchyRequestError` name is thrown. If a correct object is given, it is inserted in the tree immediately before the first element that is neither a [`<caption>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption), a [`<colgroup>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/colgroup), nor a [`<thead>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/thead), or as the last child if there is no such element, and the first `<tfoot>` that is a child of this element is removed from the tree, if any.

  
[`HTMLTableElement.rows`](htmltableelement/rows) Read only 
  Returns a live [`HTMLCollection`](htmlcollection) containing all the rows of the element, that is all [`<tr>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr) that are a child of the element, or a child of one of its [`<thead>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/thead), [`<tbody>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tbody) and [`<tfoot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tfoot) children. The rows members of a `<thead>` appear first, in tree order, and those members of a `<tbody>` last, also in tree order. The `HTMLCollection` is live and is automatically updated when the `HTMLTableElement` changes.

  
[`HTMLTableElement.tBodies`](htmltableelement/tbodies) Read only 
  Returns a live [`HTMLCollection`](htmlcollection) containing all the [`<tbody>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tbody) of the element. The `HTMLCollection` is live and is automatically updated when the `HTMLTableElement` changes.

  

### Obsolete Properties



 **Warning:** The following properties are obsolete. You should avoid using them.

   
[`HTMLTableElement.align`](htmltableelement/align)  Deprecated 
  A string containing an enumerated value reflecting the [`align`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table#align) attribute. It indicates the alignment of the element's contents with respect to the surrounding context. The possible values are `"left"`, `"right"`, and `"center"`.

  
[`HTMLTableElement.bgColor`](htmltableelement/bgcolor)  Deprecated 
  A string containing the background color of the cells. It reflects the obsolete [`bgColor`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table#bgcolor) attribute.

  
[`HTMLTableElement.border`](htmltableelement/border)  Deprecated 
  A string containing the width in pixels of the border of the table. It reflects the obsolete [`border`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table#border) attribute.

  
[`HTMLTableElement.cellPadding`](htmltableelement/cellpadding)  Deprecated 
  A string containing the width in pixels of the horizontal and vertical space between cell content and cell borders. It reflects the obsolete [`cellpadding`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table#cellpadding) attribute.

  
[`HTMLTableElement.cellSpacing`](htmltableelement/cellspacing)  Deprecated 
  A string containing the width in pixels of the horizontal and vertical separation between cells. It reflects the obsolete [`cellspacing`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table#cellspacing) attribute.

  
[`HTMLTableElement.frame`](htmltableelement/frame)  Deprecated 
  A string containing the type of the external borders of the table. It reflects the obsolete [`frame`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table#frame) attribute and can take one of the following values: `"void"`, `"above"`, `"below"`, `"hsides"`, `"vsides"`, `"lhs"`, `"rhs"`, `"box"`, or `"border"`.

  
[`HTMLTableElement.rules`](htmltableelement/rules)  Deprecated 
  A string containing the type of the internal borders of the table. It reflects the obsolete [`rules`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table#rules) attribute and can take one of the following values: `"none"`, `"groups"`, `"rows"`, `"cols"`, or `"all"`.

  
[`HTMLTableElement.summary`](htmltableelement/summary)  Deprecated 
  A string containing a description of the purpose or the structure of the table. It reflects the obsolete [`summary`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table#summary) attribute.

  
[`HTMLTableElement.width`](htmltableelement/width)  Deprecated 
  A string containing the length in pixels or in percentage of the desired width of the entire table. It reflects the obsolete [`width`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table#width) attribute.

  

Instance methods
----------------



*Inherits methods from its parent, [`HTMLElement`](htmlelement)*.

  [`HTMLTableElement.createTHead()`](htmltableelement/createthead)  Returns an [`HTMLTableSectionElement`](htmltablesectionelement) representing the first [`<thead>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/thead) that is a child of the element. If none is found, a new one is created and inserted in the tree immediately before the first element that is neither a [`<caption>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption), nor a [`<colgroup>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/colgroup), or as the last child if there is no such element.

  [`HTMLTableElement.deleteTHead()`](htmltableelement/deletethead)  Removes the first [`<thead>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/thead) that is a child of the element.

  [`HTMLTableElement.createTFoot()`](htmltableelement/createtfoot)  Returns an [`HTMLTableSectionElement`](htmltablesectionelement) representing the first [`<tfoot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tfoot) that is a child of the element. If none is found, a new one is created and inserted in the tree as the last child.

  [`HTMLTableElement.deleteTFoot()`](htmltableelement/deletetfoot)  Removes the first [`<tfoot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tfoot) that is a child of the element.

  [`HTMLTableElement.createTBody()`](htmltableelement/createtbody)  Returns a [`HTMLTableSectionElement`](htmltablesectionelement) representing a new [`<tbody>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tbody) that is a child of the element. It is inserted in the tree after the last element that is a [`<tbody>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tbody), or as the last child if there is no such element.

  [`HTMLTableElement.createCaption()`](htmltableelement/createcaption)  Returns an [`HTMLElement`](htmlelement) representing the first [`<caption>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption) that is a child of the element. If none is found, a new one is created and inserted in the tree as the first child of the [`<table>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table) element.

  [`HTMLTableElement.deleteCaption()`](htmltableelement/deletecaption)  Removes the first [`<caption>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption) that is a child of the element.

  [`HTMLTableElement.insertRow()`](htmltableelement/insertrow)  Returns an [`HTMLTableRowElement`](htmltablerowelement) representing a new row of the table. It inserts it in the rows collection immediately before the [`<tr>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr) element at the given `index` position. If necessary a [`<tbody>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tbody) is created. If the `index` is `-1`, the new row is appended to the collection. If the `index` is smaller than `-1` or greater than the number of rows in the collection, a [`DOMException`](domexception) with the value `IndexSizeError` is raised.

  [`HTMLTableElement.deleteRow()`](htmltableelement/deleterow)  Removes the row corresponding to the `index` given in parameter. If the `index` value is `-1` the last row is removed; if it is smaller than `-1` or greater than the amount of rows in the collection, a [`DOMException`](domexception) with the value `IndexSizeError` is raised.

  

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmltableelement](https://html.spec.whatwg.org/multipage/tables.html#htmltableelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLTableElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `align` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `bgColor` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `border` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `caption` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `cellPadding` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `cellSpacing` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `createCaption` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `createTBody` | 20 | 12 | 25 | 9 | 15 | 6 | 4.4 | 25 | 25 | 14 | 6 | 1.5 |
| `createTFoot` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `createTHead` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `deleteCaption` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `deleteRow` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `deleteTFoot` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `deleteTHead` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `frame` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `insertRow` | 1 | 12 | 1Starting with Firefox 20, the `index` parameter has been made optional and defaults to -1 as per HTML specification. | 5.5 | 10 | 4 | ≤37 | 18 | 4Starting with Firefox 20, the `index` parameter has been made optional and defaults to -1 as per HTML specification. | 10.1 | 3 | 1.0 |
| `rows` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `rules` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `summary` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `tBodies` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `tFoot` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `tHead` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `width` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<table>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement>

HTMLTableSectionElement
=======================



The `HTMLTableSectionElement` interface provides special properties and methods (beyond the [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating the layout and presentation of sections, that is headers, footers and bodies ([`<thead>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/thead), [`<tfoot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tfoot), and [`<tbody>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tbody), respectively) in an HTML table.


 EventTarget Node Element HTMLElement HTMLTableSectionElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
`HTMLTableSectionElement.align`  Deprecated 
  A string containing an enumerated value reflecting the [`align`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr#align) attribute. It indicates the alignment of the element's contents with respect to the surrounding context. The possible values are `"left"`, `"right"`, and `"center"`.

  
`HTMLTableSectionElement.rows` Read only 
  Returns a live [`HTMLCollection`](htmlcollection) containing the rows in the section. The `HTMLCollection` is live and is automatically updated when rows are added or removed.

  
`HTMLTableSectionElement.ch`  Deprecated 
  A string containing one single character. This character is the one to align all the cell of a column on. It reflects the [`char`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr#char) and default to the decimal points associated with the language, e.g. `'.'` for English, or `','` for French. This property was optional and was not very well supported.

  
`HTMLTableSectionElement.chOff`  Deprecated 
  A string containing an integer indicating how many characters must be left at the right (for left-to-right scripts; or at the left for right-to-left scripts) of the character defined by `HTMLTableRowElement.ch`. This property was optional and was not very well supported.

  
`HTMLTableSectionElement.vAlign`  Deprecated 
  A string representing an enumerated value indicating how the content of the cell must be vertically aligned. It reflects the [`valign`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr#valign) attribute and can have one of the following values: `"top"`, `"middle"`, `"bottom"`, or `"baseline"`.

  

Instance methods
----------------



*Inherits methods from its parent, [`HTMLElement`](htmlelement)*.

  `HTMLTableSectionElement.deleteRow()`  Removes the row, corresponding to the `index` given in parameter, in the section. If the `index` value is `-1` the last row is removed; if it smaller than `-1` or greater than the amount of rows in the collection, a [`DOMException`](domexception) with the value `IndexSizeError` is raised.

  `HTMLTableSectionElement.insertRow()`  Returns an [`HTMLTableRowElement`](htmltablerowelement) representing a new row of the section. It inserts it in the rows collection immediately before the [`<tr>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr) element at the given `index` position. If the `index` is `-1`, the new row is appended to the collection. If the `index` is smaller than `-1` or greater than the number of rows in the collection, a [`DOMException`](domexception) with the value `IndexSizeError` is raised.

  

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmltablesectionelement](https://html.spec.whatwg.org/multipage/tables.html#htmltablesectionelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLTableSectionElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `align` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `ch` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `chOff` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `deleteRow` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `insertRow` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `rows` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `vAlign` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML elements implementing this interface: [`<tfoot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tfoot), [`<thead>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/thead), and [`<tbody>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tbody).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableSectionElement>

HTMLTemplateElement
===================



The `HTMLTemplateElement` interface enables access to the contents of an HTML [`<template>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template) element.


 EventTarget Node Element HTMLElement HTMLTemplateElement

Instance properties
-------------------



*This interface inherits the properties of [`HTMLElement`](htmlelement).*

  
[`content`](htmltemplateelement/content) Read only 
  A read-only [`DocumentFragment`](documentfragment) which contains the DOM subtree representing the [`<template>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template) element's template contents.

  

Instance methods
----------------


*This interface inherits the methods of [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmltemplateelement](https://html.spec.whatwg.org/multipage/scripting.html#htmltemplateelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLTemplateElement` | 26 | 13 | 22 | No | 15 | 8 | 4.4 | 26 | 22 | 14 | 8 | 1.5 |
| `content` | 26 | 13 | 22 | No | 15 | 8 | 4.4 | 26 | 22 | 14 | 8 | 1.5 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLTemplateElement>

HTMLTableRowElement
===================



The `HTMLTableRowElement` interface provides special properties and methods (beyond the [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating the layout and presentation of rows in an HTML table.


 EventTarget Node Element HTMLElement HTMLTableRowElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
`HTMLTableRowElement.cells` Read only 
  Returns a live [`HTMLCollection`](htmlcollection) containing the cells in the row. The `HTMLCollection` is live and is automatically updated when cells are added or removed.

  
[`HTMLTableRowElement.rowIndex`](htmltablerowelement/rowindex) Read only 
  Returns a `long` value which gives the logical position of the row within the entire table. If the row is not part of a table, returns `-1`.

  
`HTMLTableRowElement.sectionRowIndex` Read only 
  Returns a `long` value which gives the logical position of the row within the table section it belongs to. If the row is not part of a section, returns `-1`.

  

Instance methods
----------------



*Inherits methods from its parent, [`HTMLElement`](htmlelement)*.

  `deleteCell(index)`  Removes the cell corresponding to `index`. If `index` is `-1`, the last cell of the row is removed. If `index` is less than `-1` or greater than the amount of cells in the collection, a [`DOMException`](domexception) with the value `IndexSizeError` is raised.

  [`insertCell(index)`](htmltablerowelement/insertcell)  Returns an [`HTMLTableCellElement`](htmltablecellelement) representing a new cell of the row. The cell is inserted in the collection of cells immediately before the given `index` position in the row. If `index` is `-1`, the new cell is appended to the collection. If `index` is less than `-1` or greater than the number of cells in the collection, a [`DOMException`](domexception) with the value `IndexSizeError` is raised.

  

Deprecated properties
---------------------



 **Warning:** These properties have been deprecated and should no longer be used. They are documented primarily to help understand older code bases.

   
`HTMLTableRowElement.align`  Deprecated 
  A string containing an enumerated value reflecting the [`align`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr#align) attribute. It indicates the alignment of the element's contents with respect to the surrounding context. The possible values are `"left"`, `"right"`, and `"center"`.

  
`HTMLTableRowElement.bgColor`  Deprecated 
  A string containing the background color of the cells. It reflects the obsolete [`bgColor`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr#bgcolor) attribute.

  
`HTMLTableRowElement.ch`  Deprecated 
  A string containing one single character. This character is the one to align all the cell of a column on. It reflects the [`char`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr#char) and default to the decimal points associated with the language, e.g. `'.'` for English, or `','` for French. This property was optional and was not very well supported.

  
`HTMLTableRowElement.chOff`  Deprecated 
  A string containing an integer indicating how many characters must be left at the right (for left-to-right scripts; or at the left for right-to-left scripts) of the character defined by `HTMLTableRowElement.ch`. This property was optional and was not very well supported.

  
`HTMLTableRowElement.vAlign`  Deprecated 
  A string representing an enumerated value indicating how the content of the cell must be vertically aligned. It reflects the [`valign`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr#valign) attribute and can have one of the following values: `"top"`, `"middle"`, `"bottom"`, or `"baseline"`.

  

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmltablerowelement](https://html.spec.whatwg.org/multipage/tables.html#htmltablerowelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLTableRowElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `align` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `bgColor` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `cells` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `ch` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `chOff` | 1 | 12 | 1 | 6 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `deleteCell` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `insertCell` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `rowIndex` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `sectionRowIndex` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `vAlign` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<tr>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement>

HTMLTextAreaElement
===================



The `HTMLTextAreaElement` interface provides special properties and methods for manipulating the layout and presentation of [`<textarea>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea) elements.


 EventTarget Node Element HTMLElement HTMLTextAreaElement

Instance properties
-------------------





|  |  |
| --- | --- |
| `accessKey` | `*string*:` Returns / Sets the element's [`accesskey`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#accesskey) attribute.  |
| `autocapitalize`  Experimental  | `*string*:` Returns / Sets the element's capitalization behavior for user input. Valid values are: `none`, `off`, `characters`, `words`, `sentences`.  |
| `autocomplete`  Experimental  |  |
| `autofocus` | `*boolean*:` Returns / Sets the element's [`autofocus`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#autofocus) attribute, indicating that the control should have input focus when the page loads  |
| `cols` | `*unsigned long*:` Returns / Sets the element's [`cols`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#cols) attribute, indicating the visible width of the text area.  |
| `defaultValue` | `*string*:` Returns / Sets the control's default value, which behaves like the [`Node.textContent`](node/textcontent) property.  |
| `disabled` | `*boolean*:` Returns / Sets the element's [`disabled`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#disabled) attribute, indicating that the control is not available for interaction.  |
| `form` Read only  | `*object*:` Returns a reference to the parent form element. If this element is not contained in a form element, it can be the [`id`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#id) attribute of any [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) element in the same document or the value `null`.  |
| `inputMode`  Experimental  |  |
| `maxLength` | `*long*:` Returns / Sets the element's [`maxlength`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#maxlength) attribute, indicating the maximum number of characters the user can enter. This constraint is evaluated only when the value changes.  |
| `minLength` | `*long*:` Returns / Sets the element's [`minlength`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#minlength) attribute, indicating the minimum number of characters the user can enter. This constraint is evaluated only when the value changes.  |
| `name` | `*string*:` Returns / Sets the element's [`name`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#name) attribute, containing the name of the control.  |
| `placeholder` | `*string*:` Returns / Sets the element's [`placeholder`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#placeholder) attribute, containing a hint to the user about what to enter in the control.  |
| `readOnly` | `*boolean*:` Returns / Sets the element's [`readonly`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#readonly) attribute, indicating that the user cannot modify the value of the control.  |
| `required` | `*boolean*:` Returns / Sets the element's [`required`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#required)) attribute, indicating that the user must specify a value before submitting the form.  |
| `rows` | `*unsigned long*:` Returns / Sets the element's [forward" if selection was performed in the start-to-end direction of the current locale, or "`backward`" for the opposite direction. This can also be "`none`" if the direction is unknown.](#) |
| `selectionEnd` | `*unsigned long*:` Returns / Sets the index of the end of selected text. If no text is selected, contains the index of the character that follows the input cursor. On being set, the control behaves as if `setSelectionRange()` had been called with this as the second argument, and `selectionStart` as the first argument.  |
| `selectionStart` | `*unsigned long*:` Returns / Sets the index of the beginning of selected text. If no text is selected, contains the index of the character that follows the input cursor. On being set, the control behaves as if `setSelectionRange()` had been called with this as the first argument, and `selectionEnd` as the second argument.  |
| `tabIndex` | `*long*:` Returns / Sets the position of the element in the tabbing navigation order for the current document.  |
| `textLength` Read only  | `*long*:` Returns the codepoint length of the control's `value`. Same as reading `value.length` |
| `type` Read only  | `*string*:` Returns the string `textarea`. |
| `validationMessage` Read only  | `*string*:` Returns a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation (`willValidate` is `false`), or it satisfies its constraints.  |
| `validity` Read only  | `*[`ValidityState`](validitystate) object*:` Returns the validity states that this element is in.  |
| `value` | `*string*:` Returns / Sets the raw value contained in the control.  |
| `willValidate` Read only  |  `*boolean*:` Returns whether the element is a candidate for constraint validation. `false` if any conditions bar it from constraint validation, including its `readOnly` or `disabled` property is `true`.  |
| `wrap` | `*string*:` Returns / Sets the [`wrap`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#wrap) HTML attribute, indicating how the control wraps text.  |
| [`HTMLTextAreaElement.labels`](htmltextareaelement/labels) Read only  | [`NodeList`](nodelist): Returns a list of label elements associated with this element.  |

 The two properties `tabIndex` and `accessKey` are inherited from [`HTMLElement`](htmlelement).



Instance methods
----------------





|  |  |
| --- | --- |
| [`blur()`](htmlelement/blur) | Removes focus from the control; keystrokes will subsequently go nowhere. |
| [`focus()`](htmlelement/focus) |  Gives focus to the control; keystrokes will subsequently go to this element.  |
| [`select()`](htmlinputelement/select) | Selects the contents of the control. |
| [`setRangeText()`](htmlinputelement/setrangetext) | Replaces a range of text in the element with new text. |
| [`setSelectionRange()`](htmlinputelement/setselectionrange) | Selects a range of text in the element (but does not focus it). |
| `checkValidity()` |  Returns `false` if the element is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires a cancelable `invalid` event at the control. It returns `true` if the control is not a candidate for constraint validation, or if it satisfies its constraints.  |
| `reportValidity()` |  This method reports the problems with the constraints on the element, if any, to the user. If there are problems, it fires a cancelable `invalid` event at the element, and returns `false`; if there are no problems, it returns `true`.  |
| `setCustomValidity(DOMstring)` |  Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate.  |

 The two methods `blur()` and `focus()` are inherited from [`HTMLElement`](htmlelement).



Events
------



Listen to these events using [`addEventListener()`](eventtarget/addeventlistener) or by assigning an event listener to the `oneventname` property of this interface:

  
[`input`](htmlelement/input_event) event  Fires when the `value` of an [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input), [`<select>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select), or [`<textarea>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea) element has been changed.

  
[`selectionchange`](htmltextareaelement/selectionchange_event) event  Experimental 
  Fires when the text selection in a [`<textarea>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea) element has been changed.

  

Examples
--------


### Autogrowing textarea example



Make a textarea autogrow while typing:

 #### JavaScript

 
```
function autoGrow(oField) {
  if (oField.scrollHeight > oField.clientHeight) {
    oField.style.height = `${oField.scrollHeight}px`;
  }
}

```
 #### CSS

 
```
textarea.noscrollbars {
  overflow: hidden;
  width: 300px;
  height: 100px;
}

```
 #### HTML

 
```
<form>
  <fieldset>
    <legend>Your comments</legend>
    <p><textarea class="noscrollbars" onkeyup="autoGrow(this);"></textarea></p>
    <p><input type="submit" value="Send" /></p>
  </fieldset>
</form>

```



### Insert HTML tags example



Insert some HTML tags in a textarea.

 #### JavaScript

 
```
function insert(startTag, endTag) {
  const textArea = document.myForm.myTxtArea;
  const selectionStart = textArea.selectionStart;
  const selectionEnd = textArea.selectionEnd;
  const oldText = textArea.value;

  const prefix = oldText.substring(0, selectionStart);
  const inserted =
    startTag + oldText.substring(selectionStart, selectionEnd) + endTag;
  const suffix = oldText.substring(selectionEnd);
  textArea.value = `${prefix}${inserted}${suffix}`;

  const newSelectionStart = selectionStart + startTag.length;
  const newSelectionEnd = selectionEnd + startTag.length;
  textArea.setSelectionRange(newSelectionStart, newSelectionEnd);

  textArea.focus();
}

function insertURL() {
  const newURL = prompt("Enter the full URL for the link");
  if (newURL) {
    insert(`<a href="${newURL}">`, "</a>");
  } else {
    document.myForm.myTxtArea.focus();
  }
}

const strong = document.querySelector("#format-strong");
const em = document.querySelector("#format-em");
const link = document.querySelector("#format-link");
const code = document.querySelector("#format-code");

strong.addEventListener("click", (e) => insert("<strong>", "</strong>"));
em.addEventListener("click", (e) => insert("<em>", "</em>"));
link.addEventListener("click", (e) => insertURL());
code.addEventListener("click", (e) => insert("\n<code>\n", "\n</code>\n"));

```
 #### CSS

 CSS to decorate the internal span to behave like a link:

 
```
.intLink {
  cursor: pointer;
  text-decoration: underline;
  color: #0000ff;
}

```
 HTML:

 
```
<form name="myForm">
  <p>
    [&nbsp;
    <span class="intLink" id="format-strong"><strong>Bold</strong></span> |
    <span class="intLink" id="format-em"><em>Italic</em></span> |
    <span class="intLink" id="format-link">URL</span> |
    <span class="intLink" id="format-code">code</span> &nbsp;]
  </p>

  <p>
    <textarea name="myTxtArea" rows="10" cols="50">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut facilisis, arcu vitae adipiscing placerat, nisl lectus accumsan nisi, vitae iaculis sem neque vel lectus. Praesent tristique commodo lorem quis fringilla. Sed ac tellus eros. Sed consectetur eleifend felis vitae luctus. Praesent sagittis, est eget bibendum tincidunt, ligula diam tincidunt augue, a fermentum odio velit eget mi. Phasellus mattis, elit id fringilla semper, orci magna cursus ligula, non venenatis lacus augue sit amet dui. Pellentesque lacinia odio id nisi pulvinar commodo tempus at odio. Ut consectetur eros porttitor nunc mollis ultrices. Aenean porttitor, purus sollicitudin viverra auctor, neque erat blandit sapien, sit amet tincidunt massa mi ac nibh. Proin nibh sem, bibendum ut placerat nec, cursus et lacus. Phasellus vel augue turpis. Nunc eu mauris eu leo blandit mollis interdum eget lorem.
    </textarea>
  </p>
</form>

```



### Maximum length and number of lines example



Create a textarea with a maximum number of characters per line and a maximum number of lines:

 First, create a function that takes the text field and a key event as input and determines if any of the limits have been reached. If the limit has not been reached, it will return the key.

 
```
function checkRows(oField, oKeyEvent) {
  let nKey = (
      oKeyEvent ||
      /\* old IE \*/ window.event || /\* check is not supported! \*/ { keyCode: 38 }
    ).keyCode,
    // put here the maximum number of characters per line:
    nCols = 30,
    // put here the maximum number of lines:
    nRows = 5,
    nSelS = oField.selectionStart,
    nSelE = oField.selectionEnd,
    sVal = oField.value,
    nLen = sVal.length,
    nBackward = nSelS >= nCols ? nSelS - nCols : 0,
    nDeltaForw =
      sVal
        .substring(nBackward, nSelS)
        .search(new RegExp(`\\n(?!.{0,${String(nCols - 2)}}\\n)`)) + 1,
    nRowStart = nBackward + nDeltaForw,
    aReturns = (
      sVal.substring(0, nSelS) + sVal.substring(nSelE, sVal.length)
    ).match(/\n/g),
    nRowEnd = nSelE + nRowStart + nCols - nSelS,
    sRow =
      sVal.substring(nRowStart, nSelS) +
      sVal.substring(nSelE, nRowEnd > nLen ? nLen : nRowEnd),
    bKeepCols =
      nKey === 13 ||
      nLen + 1 < nCols ||
      /\n/.test(sRow) ||
      ((nRowStart === 0 || nDeltaForw > 0 || nKey > 0) &&
        (sRow.length < nCols ||
          (nKey > 0 && (nLen === nRowEnd || sVal.charAt(nRowEnd) === "\n"))));

  return (
    (nKey !== 13 || (aReturns ? aReturns.length + 1 : 1) < nRows) &&
    ((nKey > 32 && nKey < 41) || bKeepCols)
  );
}

```
 In the HTML we just need to hook our function to the `onkeypress` event and specify that our textarea does not accept pasting:

 
```
<form>
  <p>
    Textarea with fixed number of characters per line:<br />
    <textarea
 cols="50"
 rows="10"
 onkeypress="return checkRows(this, event);"
 onpaste="return false;"></textarea>
  </p>
</form>

```



Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmltextareaelement](https://html.spec.whatwg.org/multipage/form-elements.html#htmltextareaelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLTextAreaElement` | 1 | 12 | 1 | 5 | 8 | 1 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 |
| `autocapitalize` | 43 | 79 | No | No | 30 | No | No | 43 | No | 30 | ≤3 | 4.0 |
| `autocomplete` | 66 | 79 | 59 | No | 53 | 9.1 | 66 | 66 | 59 | 47 | 9.3 | 9.0 |
| `checkValidity` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `cols` | 1 | 12 | 1 | 5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `defaultValue` | 1 | 12 | 1 | 5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `dirName` | 17 | 79 | No | No | ≤12.1 | 6 | 4.4 | 18 | No | ≤12.1 | 6 | 1.0 |
| `disabled` | 1 | 12 | 1 | 5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `form` | 1 | 12 | 1 | 5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `labels` | 6 | 18 | 56 | No | ≤12.1 | 5.1 | 3 | 18 | 56 | ≤12.1 | 5 | 1.0 |
| `maxLength` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `minLength` | 40 | 17 | 51 | No | 27 | 10.1 | 40 | 40 | 51 | 27 | 10.3 | 4.0 |
| `name` | 1 | 12 | 1 | 5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `placeholder` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `readOnly` | 1 | 12 | 1 | 5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `reportValidity` | 40 | 17 | 49 | No | 27 | 10.1 | 40 | 40 | 64 | 27 | 10.3 | 4.0 |
| `required` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `rows` | 1 | 12 | 1 | 5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `select` | 1 | 12 | 1 | 5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `select_event` | 1 | 12 | 6 | 9 | ≤12.1 | 1 | 4.4 | 18 | 6 | ≤12.1 | 1 | 1.0 |
| `selectionDirection` | 15 | 79 | 8 | No | ≤12.1 | 6 | 4.4 | 18 | 8 | ≤12.1 | 6 | 1.0 |
| `selectionEnd` | 1 | 12 | 1 | 9 | ≤12.1 | 1.3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `selectionStart` | 1 | 12 | 1 | 9 | ≤12.1 | 1.3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `selectionchange_event` | NoA `selectionchange` event is fired on `Document`, see [`Document`'s `selectionchange` event](https://developer.mozilla.org/docs/Web/API/Document/selectionchange_event). See [bug 1327098](https://crbug.com/1327098) for firing the event on `<textarea>` elements. | NoA `selectionchange` event is fired on `Document`, see [`Document`'s `selectionchange` event](https://developer.mozilla.org/docs/Web/API/Document/selectionchange_event). See [bug 1327098](https://crbug.com/1327098) for firing the event on `<textarea>` elements. | 92 | No | NoA `selectionchange` event is fired on `Document`, see [`Document`'s `selectionchange` event](https://developer.mozilla.org/docs/Web/API/Document/selectionchange_event). See [bug 1327098](https://crbug.com/1327098) for firing the event on `<textarea>` elements. | NoSee [bug 234348](https://webkit.org/b/234348). | NoA `selectionchange` event is fired on `Document`, see [`Document`'s `selectionchange` event](https://developer.mozilla.org/docs/Web/API/Document/selectionchange_event). See [bug 1327098](https://crbug.com/1327098) for firing the event on `<textarea>` elements. | NoA `selectionchange` event is fired on `Document`, see [`Document`'s `selectionchange` event](https://developer.mozilla.org/docs/Web/API/Document/selectionchange_event). See [bug 1327098](https://crbug.com/1327098) for firing the event on `<textarea>` elements. | 92 | NoA `selectionchange` event is fired on `Document`, see [`Document`'s `selectionchange` event](https://developer.mozilla.org/docs/Web/API/Document/selectionchange_event). See [bug 1327098](https://crbug.com/1327098) for firing the event on `<textarea>` elements. | NoSee [bug 234348](https://webkit.org/b/234348). | NoA `selectionchange` event is fired on `Document`, see [`Document`'s `selectionchange` event](https://developer.mozilla.org/docs/Web/API/Document/selectionchange_event). See [bug 1327098](https://crbug.com/1327098) for firing the event on `<textarea>` elements. |
| `setCustomValidity` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `setRangeText` | 24 | 79 | 27 | No | 15 | 7 | 4.4 | 25 | 27 | 14 | 7 | 1.5 |
| `setSelectionRange` | 1 | 12 | 1 | 9 | ≤12.1 | 1.3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `textLength` | 4 | 17 | 1 | No | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 |
| `type` | 1 | 12 | 1 | 5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `validationMessage` | 5 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `validity` | 4 | 12 | 4 | 10 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 5 | 1.0 |
| `value` | 1 | 12 | 1 | 5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `willValidate` | 2 | 12 | 4 | 10 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `wrap` | 16 | 12 | 4 | 5 | ≤12.1 | 6 | 4.4 | 18 | 4 | ≤12.1 | 6 | 1.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLTextAreaElement>

HTMLTimeElement
===============



The `HTMLTimeElement` interface provides special properties (beyond the regular [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating [`<time>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/time) elements.


 EventTarget Node Element HTMLElement HTMLTimeElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  [`HTMLTimeElement.dateTime`](htmltimeelement/datetime)  A string that reflects the [`datetime`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/time#datetime) HTML attribute, containing a machine-readable form of the element's date and time value.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmltimeelement](https://html.spec.whatwg.org/multipage/text-level-semantics.html#htmltimeelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLTimeElement` | 62 | 14 | 22 | No | 4911.5–15 | 10 | 62 | 62 | 22 | 4611.5–14 | 10 | 8.0 |
| `dateTime` | 62 | 14 | 22 | No | 4911.5–15 | 10 | 62 | 62 | 22 | 4611.5–14 | 10 | 8.0 |


See also
--------


* The HTML element implementing this interface: [`<time>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/time).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLTimeElement>

HTMLTrackElement
================



The `HTMLTrackElement` interface represents an [HTML](https://developer.mozilla.org/en-US/docs/Glossary/HTML) [`<track>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track) element within the [DOM](https://developer.mozilla.org/en-US/docs/Glossary/DOM). This element can be used as a child of either [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) or [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) to specify a text track containing information such as closed captions or subtitles.


 EventTarget Node Element HTMLElement HTMLTrackElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  `HTMLTrackElement.kind`  A string that reflects the [`kind`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track#kind) HTML attribute, indicating how the text track is meant to be used. Possible values are: `subtitles`, `captions`, `descriptions`, `chapters`, or `metadata`.

  [`HTMLTrackElement.src`](htmltrackelement/src)  A string that reflects the [`src`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track#src) HTML attribute, indicating the address of the text track data.

  `HTMLTrackElement.srclang`  A string that reflects the [`srclang`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track#srclang) HTML attribute, indicating the language of the text track data.

  `HTMLTrackElement.label`  A string that reflects the [`label`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track#label) HTML attribute, indicating a user-readable title for the track.

  `HTMLTrackElement.default`  A boolean value reflecting the [`default`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track#default) attribute, indicating that the track is to be enabled if the user's preferences do not indicate that another track would be more appropriate.

  
`HTMLTrackElement.readyState` Read only 
  Returns an `unsigned short` that show the readiness state of the track:

 

| Constant | Value | Description |
| --- | --- | --- |
| `NONE` | 0 | Indicates that the text track's cues have not been obtained. |
| `LOADING` | 1 | Indicates that the text track is loading and there have been no fatal errors encountered so far. Further cues might still be added to the track by the parser. |
| `LOADED` | 2 | Indicates that the text track has been loaded with no fatal errors. |
| `ERROR` | 3 | Indicates that the text track was enabled, but when the user agent attempted to obtain it, this failed in some way. Some or all of the cues are likely missing and will not be obtained. |

  
`HTMLTrackElement.track` Read only 
  Returns [`TextTrack`](texttrack) is the track element's text track data.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Events
------



*The following events may be fired on a [`<track>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track) element, in addition to any that may be fired at its parent, [`HTMLElement`](htmlelement).*

  [`cuechange`](htmltrackelement/cuechange_event)   Sent when the underlying [`TextTrack`](texttrack) has changed the currently-presented cues. This event is always sent to the `TextTrack` but is *also* sent to the `HTMLTrackElement` if one is associated with the track. You may also use the `oncuechange` event handler to establish a handler for this event. 

  

Usage notes
-----------


### Loading of the track's text resource


The WebVTT or TTML data describing the actual cues for the text track isn't loaded if the track's [`mode`](texttrack/mode) is initially in the `disabled` state. If you need to be able to perform any processing on the track after the `<track>` is set up, you should instead ensure that the track's `mode` is either `hidden` (if you don't want it to start out being presented to the user) or `showing` (to initially display the track). You can then change the mode as desired later.


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmltrackelement](https://html.spec.whatwg.org/multipage/media.html#htmltrackelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLTrackElement` | 23 | 12 | 31Before Firefox 50, text tracks would only load if the `<track>` element is in a document. | 10 | 12 | 6 | 4.4 | 25 | 31Before Firefox 50, text tracks would only load if the `<track>` element is in a document. | 12 | 6 | 1.5 |
| `cuechange_event` | 3223The `oncuechange` event handler property is not supported. | 14 | 68 | No | 1915The `oncuechange` event handler property is not supported.12–15 | 106The `oncuechange` event handler property is not supported. | ≤37The `oncuechange` event handler property is not supported.4.4.3 | 3225The `oncuechange` event handler property is not supported. | 68 | 1914The `oncuechange` event handler property is not supported.12–14 | 106The `oncuechange` event handler property is not supported. | 2.01.5The `oncuechange` event handler property is not supported. |
| `default` | 23 | 12 | 31 | 10 | 12 | 6 | 4.4 | 25 | 31 | 12 | 6 | 1.5 |
| `kind` | 23 | 12 | 31 | 10 | 12 | 6 | 4.4 | 25 | 31 | 12 | 6 | 1.5 |
| `label` | 23 | 12 | 31 | 10 | 12 | 6 | 4.4 | 25 | 31 | 12 | 6 | 1.5 |
| `readyState` | 23 | 12 | 31 | 10 | 12 | 6 | 4.4 | 25 | 31 | 12 | 6 | 1.5 |
| `src` | 23 | 12 | 31Before Firefox 50, setting the `src` property did not work properly. | 10 | 12 | 6 | 4.4 | 25 | 31Before Firefox 50, setting the `src` property did not work properly. | 12 | 6 | 1.5 |
| `srclang` | 23 | 12 | 31 | 10 | 12 | 6 | 4.4 | 25 | 31 | 12 | 6 | 1.5 |
| `track` | 23 | 12 | 31 | 10 | 12 | 6 | 4.4 | 25 | 31 | 12 | 6 | 1.5 |


See also
--------


* The HTML element implementing this interface: [`<track>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLTrackElement>

HTMLUListElement
================



The `HTMLUListElement` interface provides special properties (beyond those defined on the regular [`HTMLElement`](htmlelement) interface it also has available to it by inheritance) for manipulating unordered list ([`<ul>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul)) elements.


 EventTarget Node Element HTMLElement HTMLUListElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  
`HTMLUListElement.type`  Deprecated 
  A string value reflecting the [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul#type) and defining the kind of marker to be used to display. The values are browser dependent and have never been standardized.

  
`HTMLUListElement.compact`  Deprecated 
  A boolean value indicating that spacing between list items should be reduced. This property reflects the [`compact`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul#compact) attribute only, it doesn't consider the [`line-height`](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height) CSS property used for that behavior in modern pages.

  

Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlulistelement](https://html.spec.whatwg.org/multipage/grouping-content.html#htmlulistelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLUListElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `compact` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `type` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<ul>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLUListElement>

HTMLUnknownElement
==================



The `HTMLUnknownElement` interface represents an invalid HTML element and derives from the [`HTMLElement`](htmlelement) interface, but without implementing any additional properties or methods.


 EventTarget Node Element HTMLElement HTMLUnknownElement

Instance properties
-------------------


*No specific property; inherits properties from its parent, [`HTMLElement`](htmlelement).*


Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlunknownelement](https://html.spec.whatwg.org/multipage/dom.html#htmlunknownelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLUnknownElement` | 15 | 12 | 1 | 9 | ≤12.1 | 6 | 4.4 | 18 | 4 | ≤12.1 | 6 | 1.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLUnknownElement>

HTMLVideoElement
================



Implemented by the [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) element, the `HTMLVideoElement` interface provides special properties and methods for manipulating video objects. It also inherits properties and methods of [`HTMLMediaElement`](htmlmediaelement) and [`HTMLElement`](htmlelement).

 The list of [supported media formats](https://developer.mozilla.org/en-US/docs/Web/Media/Formats) varies from one browser to the other. You should either provide your video in a single format that all the relevant browsers supports, or provide multiple video sources in enough different formats that all the browsers you need to support are covered.


 EventTarget Node Element HTMLElement HTMLMediaElement HTMLVideoElement

Instance properties
-------------------



*Inherits properties from its ancestor interfaces, [`HTMLMediaElement`](htmlmediaelement), and [`HTMLElement`](htmlelement).*

  `HTMLVideoElement.height`  A string that reflects the [`height`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#height) HTML attribute, which specifies the height of the display area, in CSS pixels.

  `HTMLVideoElement.poster`  A string that reflects the [`poster`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#poster) HTML attribute, which specifies an image to show while no video data is available.

  
[`HTMLVideoElement.videoHeight`](htmlvideoelement/videoheight) Read only 
  Returns an unsigned integer value indicating the intrinsic height of the resource in CSS pixels, or 0 if no media is available yet.

  
[`HTMLVideoElement.videoWidth`](htmlvideoelement/videowidth) Read only 
  Returns an unsigned integer value indicating the intrinsic width of the resource in CSS pixels, or 0 if no media is available yet.

  `HTMLVideoElement.width`  A string that reflects the [`width`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#width) HTML attribute, which specifies the width of the display area, in CSS pixels.

  [`HTMLVideoElement.disablePictureInPicture`](htmlvideoelement/disablepictureinpicture)  The `disablePictureInPicture` property will hint the user agent to not suggest the picture-in-picture to users or to request it automatically

  

### Gecko-specific properties


 
`HTMLVideoElement.mozParsedFrames`  Non-standard  Read only   Deprecated 
  Returns an `unsigned long` with the count of video frames that have been parsed from the media resource.

  
`HTMLVideoElement.mozDecodedFrames`  Non-standard  Read only   Deprecated 
  Returns an `unsigned long` with the count of parsed video frames that have been decoded into images.

  
`HTMLVideoElement.mozPresentedFrames`  Non-standard  Read only   Deprecated 
  Returns an `unsigned long` with the count of decoded frames that have been presented to the rendering pipeline for painting.

  
`HTMLVideoElement.mozPaintedFrames`  Non-standard  Read only   Deprecated 
  Returns an `unsigned long` with the count of presented frames which were painted on the screen.

  
`HTMLVideoElement.mozFrameDelay`  Non-standard  Read only   Deprecated 
  Returns an `double` with the time which the last painted video frame was late by, in seconds.

  
`HTMLVideoElement.mozHasAudio`  Non-standard  Read only   Deprecated 
  Returns a boolean indicating if there is some audio associated with the video.

  
Instance methods
----------------



*Inherits methods from its parent, [`HTMLMediaElement`](htmlmediaelement), and from its ancestor [`HTMLElement`](htmlelement).*

  [`HTMLVideoElement.getVideoPlaybackQuality()`](htmlvideoelement/getvideoplaybackquality)  Returns a [`VideoPlaybackQuality`](videoplaybackquality) object that contains the current playback metrics. This information includes things like the number of dropped or corrupted frames, as well as the total number of frames.

  [`HTMLVideoElement.requestPictureInPicture()`](htmlvideoelement/requestpictureinpicture)  Requests that the user agent make video enters picture-in-picture mode

  

Events
------



*Inherits events from its parent, [`HTMLMediaElement`](htmlmediaelement), and from its ancestor [`HTMLElement`](htmlelement).* Listen to these events using [`addEventListener()`](eventtarget/addeventlistener) or by assigning an event listener to the `oneventname` property of this interface.

  [`enterpictureinpicture`](htmlvideoelement/enterpictureinpicture_event)  Sent to a [`HTMLVideoElement`](htmlvideoelement) when it enters Picture-in-Picture mode.

  [`leavepictureinpicture`](htmlvideoelement/leavepictureinpicture_event)  Sent to a [`HTMLVideoElement`](htmlvideoelement) when it leaves Picture-in-Picture mode.

  

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmlvideoelement](https://html.spec.whatwg.org/multipage/media.html#htmlvideoelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLVideoElement` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `cancelVideoFrameCallback` | 83 | 83 | No | No | 69 | 15.4 | 83 | 83 | No | 59 | 15.4 | 13.0 |
| `disablePictureInPicture` | 69 | 79 | No | No | 56 | 13.1 | No | 105 | No | 72 | 13.4 | 20.0 |
| `enterpictureinpicture_event` | 69 | 79 | No | No | 56 | 13.1 | No | 105 | No | 72 | 13.4 | 20.0 |
| `getVideoPlaybackQuality` | 80 | 12 | 42 | 11Only works on Windows 8+. | 67 | 8 | 80 | 80 | 42 | 57 | 8 | 13.0 |
| `height` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `leavepictureinpicture_event` | 69 | 79 | No | No | 56 | 13.1 | No | 105 | No | 72 | 13.4 | 20.0 |
| `mozDecodedFrames` | No | No | 5 | No | No | No | No | No | 5 | No | No | No |
| `mozFrameDelay` | No | No | 5 | No | No | No | No | No | 5 | No | No | No |
| `mozHasAudio` | No | No | 15 | No | No | No | No | No | 15 | No | No | No |
| `mozPaintedFrames` | No | No | 5 | No | No | No | No | No | 5 | No | No | No |
| `mozParsedFrames` | No | No | 5 | No | No | No | No | No | 5 | No | No | No |
| `mozPresentedFrames` | No | No | 5 | No | No | No | No | No | 5 | No | No | No |
| `playsInline` | 75 | 79 | No | No | 62 | 10 | 75 | 75 | No | 54 | 10 | 11.0 |
| `poster` | 3 | 12 | 3.6 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `requestPictureInPicture` | 69 | 79 | No | No | 56 | 13.1 | No | 105 | No | 72 | 13.4 | 20.0 |
| `requestVideoFrameCallback` | 83 | 83 | No | No | 69 | 15.4 | 83 | 83 | No | 59 | 15.4 | 13.0 |
| `resize_event` | 3 | 7912–79The `onresize` event handler property is not supported. | 3.5 | 9The `onresize` event handler property is not supported. | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `videoHeight` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `videoWidth` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |
| `width` | 3 | 12 | 3.5 | 9 | 10.5 | 3.1 | ≤37 | 18 | 4 | 11 | 3 | 1.0 |


See also
--------


* HTML element implementing this interface: [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video).
* [Supported media formats](https://developer.mozilla.org/en-US/docs/Web/Media/Formats)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLVideoElement>

IDBCursor
=========



 **Note:** Not to be confused with [`IDBCursorWithValue`](idbcursorwithvalue) which is just an `IDBCursor` interface with an additional `value` property.

  The `IDBCursor` interface of the [IndexedDB API](indexeddb_api) represents a [cursor](indexeddb_api/basic_terminology#cursor) for traversing or iterating over multiple records in a database.

 The cursor has a source that indicates which index or object store it is iterating over. It has a position within the range, and moves in a direction that is increasing or decreasing in the order of record keys. The cursor enables an application to asynchronously process all the records in the cursor's range.

 You can have an unlimited number of cursors at the same time. You always get the same `IDBCursor` object representing a given cursor. Operations are performed on the underlying index or object store.


 **Note:** This feature is available in [Web Workers](web_workers_api)

 

Instance properties
-------------------



 **Note:** [`IDBCursorWithValue`](idbcursorwithvalue) is an `IDBCursor` interface with an additional `value` property.

   
[`IDBCursor.source`](idbcursor/source) Read only 
  Returns the [`IDBObjectStore`](idbobjectstore) or [`IDBIndex`](idbindex) that the cursor is iterating. This function never returns null or throws an exception, even if the cursor is currently being iterated, has iterated past its end, or its transaction is not active.

  
[`IDBCursor.direction`](idbcursor/direction) Read only 
  Returns the direction of traversal of the cursor. See [Constants](#const_next) for possible values.

  
[`IDBCursor.key`](idbcursor/key) Read only 
  Returns the key for the record at the cursor's position. If the cursor is outside its range, this is set to `undefined`. The cursor's key can be any data type.

  
[`IDBCursor.primaryKey`](idbcursor/primarykey) Read only 
  Returns the cursor's current effective primary key. If the cursor is currently being iterated or has iterated outside its range, this is set to `undefined`. The cursor's primary key can be any data type.

  
[`IDBCursor.request`](idbcursor/request) Read only 
  Returns the [`IDBRequest`](idbrequest) that was used to obtain the cursor.

  

Instance methods
----------------


 [`IDBCursor.advance()`](idbcursor/advance)  Sets the number of times a cursor should move its position forward.

  [`IDBCursor.continue()`](idbcursor/continue)  Advances the cursor to the next position along its direction, to the item whose key matches the optional `key` parameter.

  [`IDBCursor.continuePrimaryKey()`](idbcursor/continueprimarykey)  Sets the cursor to the given index key and primary key given as arguments.

  [`IDBCursor.delete()`](idbcursor/delete)  Returns an [`IDBRequest`](idbrequest) object, and, in a separate thread, deletes the record at the cursor's position, without changing the cursor's position. This can be used to delete specific records.

  [`IDBCursor.update()`](idbcursor/update)  Returns an [`IDBRequest`](idbrequest) object, and, in a separate thread, updates the value at the current position of the cursor in the object store. This can be used to update specific records.

  
Constants
---------



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

  **Warning:** These constants are no longer available — they were removed in Gecko 25. You should use the string constants directly instead. ([Firefox bug 891944](https://bugzil.la/891944))

  * `NEXT`: `"next"` : The cursor shows all records, including duplicates. It starts at the lower bound of the key range and moves upwards (monotonically increasing in the order of keys).
* `NEXTUNIQUE` : `"nextunique"` : The cursor shows all records, excluding duplicates. If multiple records exist with the same key, only the first one iterated is retrieved. It starts at the lower bound of the key range and moves upwards.
* `PREV`: `"prev"` : The cursor shows all records, including duplicates. It starts at the upper bound of the key range and moves downwards (monotonically decreasing in the order of keys).
* `PREVUNIQUE`: `"prevunique"` : The cursor shows all records, excluding duplicates. If multiple records exist with the same key, only the first one iterated is retrieved. It starts at the upper bound of the key range and moves downwards.



Examples
--------



In this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. The cursor does not require us to select the data based on a key; we can just grab all of it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using `cursor.value.foo`. For a complete working example, see our [IDBCursor example](https://github.com/mdn/dom-examples/tree/main/indexeddb-examples/idbcursor) ([view example live](https://mdn.github.io/dom-examples/indexeddb-examples/idbcursor/).)

 
```
function displayData() {
  const transaction = db.transaction(["rushAlbumList"], "readonly");
  const objectStore = transaction.objectStore("rushAlbumList");

  objectStore.openCursor().onsuccess = (event) => {
    const cursor = event.target.result;
    if (cursor) {
      const listItem = document.createElement("li");
      listItem.textContent = `${cursor.value.albumTitle}, ${cursor.value.year}`;
      list.appendChild(listItem);

      cursor.continue();
    } else {
      console.log("Entries all displayed.");
    }
  };
}

```


Specifications
--------------




| Specification |
| --- |
| [Indexed Database API 3.0 # cursor-interface](https://w3c.github.io/IndexedDB/#cursor-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `IDBCursor` | 2423–57 | 12 | 1610–16 | 10 | 4415–44 | 8 | ≤37–574.4 | 2525–57 | 22 | 4314–43 | 8 | 1.51.5–7.0 |
| `advance` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `continue` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `continuePrimaryKey` | 58 | 79 | 10 | No | 45 | 10.1 | 58 | 58 | 51 | 43 | 10.3 | 7.0 |
| `delete` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `direction` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `key` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `primaryKey` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `request` | 76 | 79 | 77 | No | 63 | 15 | 76 | 76 | 79 | 54 | 15 | 12.0 |
| `source` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `update` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `worker_support` | 23 | 12 | 37 | 10 | 15 | 10 | 4.4 | 25 | 37 | 14 | 10 | 1.5 |


See also
--------


* [Using IndexedDB](indexeddb_api/using_indexeddb)
* Starting transactions: [`IDBDatabase`](idbdatabase)
* Using transactions: [`IDBTransaction`](idbtransaction)
* Setting a range of keys: [`IDBKeyRange`](idbkeyrange)
* Retrieving and making changes to your data: [`IDBObjectStore`](idbobjectstore)
* Using cursors: [`IDBCursor`](idbcursor)
* Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([view example live](https://mdn.github.io/dom-examples/to-do-notifications/)).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor>

IDBCursorWithValue
==================



The `IDBCursorWithValue` interface of the [IndexedDB API](indexeddb_api) represents a [cursor](indexeddb_api/basic_terminology#cursor) for traversing or iterating over multiple records in a database. It is the same as the [`IDBCursor`](idbcursor), except that it includes the `value` property.

 The cursor has a source that indicates which index or object store it is iterating over. It has a position within the range, and moves in a direction that is increasing or decreasing in the order of record keys. The cursor enables an application to asynchronously process all the records in the cursor's range.

 You can have an unlimited number of cursors at the same time. You always get the same `IDBCursorWithValue` object representing a given cursor. Operations are performed on the underlying index or object store.


 **Note:** This feature is available in [Web Workers](web_workers_api)

   IDBCursor IDBCursorWithValue

Instance methods
----------------


Inherits methods from its parent interface, [`IDBCursor`](idbcursor).


Instance properties
-------------------



Inherits properties from its parent interface, [`IDBCursor`](idbcursor).

  
[`IDBCursorWithValue.value`](idbcursorwithvalue/value) Read only 
  Returns the value of the current cursor.

  

Example
-------



In this example we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. The cursor does not require us to select the data based on a key; we can just grab all of it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using `cursor.value.foo`. For a complete working example, see our [IDBCursor example](https://github.com/mdn/dom-examples/tree/main/indexeddb-examples/idbcursor) ([view example live](https://mdn.github.io/dom-examples/indexeddb-examples/idbcursor/).)

 
```
function displayData() {
  const transaction = db.transaction(["rushAlbumList"], "readonly");
  const objectStore = transaction.objectStore("rushAlbumList");

  objectStore.openCursor().onsuccess = (event) => {
    const cursor = event.target.result;
    if (cursor) {
      const listItem = document.createElement("li");
      listItem.textContent = `${cursor.value.albumTitle}, ${cursor.value.year}`;
      list.appendChild(listItem);

      cursor.continue();
    } else {
      console.log("Entries all displayed.");
    }
  };
}

```


Specifications
--------------




| Specification |
| --- |
| [Indexed Database API 3.0 # ref-for-idbcursorwithvalue②](#) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `IDBCursorWithValue` | 2423–57 | 12 | 1610–16 | 10 | 15 | 8 | ≤37–574.4 | 2525–57 | 22 | 14 | 8 | 1.51.5–7.0 |
| `value` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `worker_support` | 23 | 12 | 42 | 10 | 15 | 10 | 4.4 | 25 | 42 | 14 | 10 | 1.5 |


See also
--------


* [Using IndexedDB](indexeddb_api/using_indexeddb)
* Starting transactions: [`IDBDatabase`](idbdatabase)
* Using transactions: [`IDBTransaction`](idbtransaction)
* Setting a range of keys: [`IDBKeyRange`](idbkeyrange)
* Retrieving and making changes to your data: [`IDBObjectStore`](idbobjectstore)
* Using cursors: [`IDBCursor`](idbcursor)
* Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/IDBCursorWithValue>

IDBDatabase
===========



The `IDBDatabase` interface of the IndexedDB API provides a [connection to a database](indexeddb_api#database_connection); you can use an `IDBDatabase` object to open a [transaction](indexeddb_api/basic_terminology#transaction) on your database then create, manipulate, and delete objects (data) in that database. The interface provides the only way to get and manage versions of the database.


 **Note:** This feature is available in [Web Workers](web_workers_api)

   **Note:** Everything you do in IndexedDB always happens in the context of a [transaction](indexeddb_api/basic_terminology#transaction), representing interactions with data in the database. All objects in IndexedDB — including object stores, indexes, and cursors — are tied to a particular transaction. Thus, you cannot execute commands, access data, or open anything outside of a transaction.

 
 EventTarget IDBDatabase

Instance properties
-------------------


 
[`IDBDatabase.name`](idbdatabase/name) Read only 
  A string that contains the name of the connected database.

  
[`IDBDatabase.version`](idbdatabase/version) Read only 
  A 64-bit integer that contains the version of the connected database. When a database is first created, this attribute is an empty string.

  
[`IDBDatabase.objectStoreNames`](idbdatabase/objectstorenames) Read only 
  A [`DOMStringList`](domstringlist) that contains a list of the names of the [object stores](indexeddb_api/basic_terminology#object_store) currently in the connected database.

  
Instance methods
----------------



Inherits from: [EventTarget](eventtarget)

  [`IDBDatabase.close()`](idbdatabase/close)  Returns immediately and closes the connection to a database in a separate thread.

  [`IDBDatabase.createObjectStore()`](idbdatabase/createobjectstore)  Creates and returns a new object store or index.

  [`IDBDatabase.deleteObjectStore()`](idbdatabase/deleteobjectstore)  Destroys the object store with the given name in the connected database, along with any indexes that reference it.

  [`IDBDatabase.transaction()`](idbdatabase/transaction)  Immediately returns a transaction object ([`IDBTransaction`](idbtransaction)) containing the [`IDBTransaction.objectStore`](idbtransaction/objectstore) method, which you can use to access your object store. Runs in a separate thread.

  

Events
------



Listen to these events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface.

  [`close`](idbdatabase/close_event)  An event fired when the database connection is unexpectedly closed.

  [`versionchange`](idbdatabase/versionchange_event)  An event fired when a database structure change was requested.

   The following events are available to `IDBDatabase` via event bubbling from [`IDBTransaction`](idbtransaction):

  
`IDBTransaction` [`abort`](idbtransaction/abort_event)
  An event fired when a transaction is aborted.

  
`IDBTransaction` [`error`](idbtransaction/error_event)
  An event fired when a request returns an error and the event bubbles up to the connection object.

  

Example
-------



In the following code snippet, we open a database asynchronously ([`IDBFactory`](idbfactory)), handle success and error cases, and create a new object store in the case that an upgrade is needed ([`IDBdatabase`](idbdatabase)). For a complete working example, see our [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) app ([view example live](https://mdn.github.io/dom-examples/to-do-notifications/)).

 
```
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

// these two event handlers act on the IDBDatabase object,
// when the database is opened successfully, or not
DBOpenRequest.onerror = (event) => {
  note.innerHTML += "<li>Error loading database.</li>";
};

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db
  // variable. This is used a lot later on
  db = DBOpenRequest.result;

  // Run the displayData() function to populate the task
  // list with all the to-do list data already in the IDB
  displayData();
};

// This event handles the event whereby a new version of
// the database needs to be created Either one has not
// been created before, or a new version number has been
// submitted via the window.indexedDB.open line above

DBOpenRequest.onupgradeneeded = (event) => {
  const db = event.target.result;

  db.onerror = (event) => {
    note.innerHTML += "<li>Error loading database.</li>";
  };

  // Create an objectStore for this database using
  // IDBDatabase.createObjectStore

  const objectStore = db.createObjectStore("toDoList", {
    keyPath: "taskTitle",
  });

  // define what data items the objectStore will contain

  objectStore.createIndex("hours", "hours", { unique: false });
  objectStore.createIndex("minutes", "minutes", { unique: false });
  objectStore.createIndex("day", "day", { unique: false });
  objectStore.createIndex("month", "month", { unique: false });
  objectStore.createIndex("year", "year", { unique: false });

  objectStore.createIndex("notified", "notified", { unique: false });

  note.innerHTML += "<li>Object store created.</li>";
};

```
 This next line opens up a transaction on the Database, then opens an object store that we can then manipulate the data inside of.

 
```
const objectStore = db
  .transaction("toDoList", "readwrite")
  .objectStore("toDoList");

```


Specifications
--------------




| Specification |
| --- |
| [Indexed Database API 3.0 # database-interface](https://w3c.github.io/IndexedDB/#database-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `IDBDatabase` | 2423–57 | 12 | 1610–16 | 10 | 15 | 8 | ≤37–574.4 | 2525–57 | 22 | 14 | 8 | 1.51.5–7.0 |
| `close` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `close_event` | 30 | 79 | 50 | No | 17 | 10.1 | ≤37 | 30 | 50 | 18 | 10.3 | 2.0 |
| `createObjectStore` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `deleteObjectStore` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `name` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `objectStoreNames` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `transaction` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `version` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `versionchange_event` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `worker_support` | 23 | 12 | 37 | 10 | 15 | 10 | 4.4 | 25 | 37 | 14 | 10 | 1.5 |


See also
--------


* [Using IndexedDB](indexeddb_api/using_indexeddb)
* Starting transactions: [`IDBDatabase`](idbdatabase)
* Using transactions: [`IDBTransaction`](idbtransaction)
* Setting a range of keys: [`IDBKeyRange`](idbkeyrange)
* Retrieving and making changes to your data: [`IDBObjectStore`](idbobjectstore)
* Using cursors: [`IDBCursor`](idbcursor)
* Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase>

HTMLTitleElement
================



The `HTMLTitleElement` interface is implemented by a document's [`<title>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/title). This element inherits all of the properties and methods of the [`HTMLElement`](htmlelement) interface.


 EventTarget Node Element HTMLElement HTMLTitleElement

Instance properties
-------------------



*Inherits properties from its parent, [`HTMLElement`](htmlelement).*

  `HTMLTitleElement.text`  A string representing the text of the document's title, and only the text part. For example, consider this:

   
```
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <title>
      Hello world! <span class="highlight">Isn't this wonderful</span> really?
    </title>
  </head>
  <body></body>
</html>

```
 
```
const title = document.querySelector("title");
console.log(title.text); // yield: "Hello world! really?"

```
 As you can see, the tag `span` and its content were skipped.



Instance methods
----------------


*No specific method; inherits methods from its parent, [`HTMLElement`](htmlelement).*


Example
-------



Do not confuse: `document.title` with `document.querySelector('title')`

 The former is just a setter/getter method to set or get the inner text value of the document title, while the latter is the [`HTMLTitleElement`](htmltitleelement) object. So you cannot write: `document.title.text = "Hello world!";`

 Instead, you can simply write: `document.title = "Hello world!";` which is an equivalent to `document.querySelector('title').text = "Hello world!";`



Specifications
--------------




| Specification |
| --- |
| [HTML Standard # htmltitleelement](https://html.spec.whatwg.org/multipage/semantics.html#htmltitleelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `HTMLTitleElement` | 1 | 12 | 1 | 5.5 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `text` | 1 | 12 | 1 | 9 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* The HTML element implementing this interface: [`<title>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/title).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/HTMLTitleElement>

IDBFactory
==========



The `IDBFactory` interface of the [IndexedDB API](indexeddb_api) lets applications asynchronously access the indexed databases. The object that implements the interface is `window.indexedDB`. You open — that is, create and access — and delete a database with this object, and not directly with `IDBFactory`.


 **Note:** This feature is available in [Web Workers](web_workers_api)

 

Instance methods
----------------


 [`IDBFactory.open`](idbfactory/open)  The current method to request opening a [connection to a database](indexeddb_api/basic_terminology#database_connection).

  [`IDBFactory.deleteDatabase`](idbfactory/deletedatabase)  A method to request the deletion of a database.

  [`IDBFactory.cmp`](idbfactory/cmp)  A method that compares two keys and returns a result indicating which one is greater in value.

  [`IDBFactory.databases`](idbfactory/databases)  A method that returns a list of all available databases, including their names and versions.

  
Example
-------



In the following code snippet, we make a request to open a database, and include handlers for the success and error cases. For a full working example, see our [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) app ([view example live](https://mdn.github.io/dom-examples/to-do-notifications/)).

 
```
// Let us open version 4 of our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

// these two event handlers act on the database being opened successfully, or not
DBOpenRequest.onerror = (event) => {
  console.error("Error loading database.");
};

DBOpenRequest.onsuccess = (event) => {
  console.info("Database initialized.");

  // store the result of opening the database in the db variable. This is used a lot later on, for opening transactions and suchlike.
  db = DBOpenRequest.result;
};

```


Specifications
--------------




| Specification |
| --- |
| [Indexed Database API 3.0 # factory-interface](https://w3c.github.io/IndexedDB/#factory-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `IDBFactory` | 2423–57 | 12 | 1610–16 | 10 | 15 | 8 | ≤37–574.4 | 2525–57 | 22 | 14 | 8 | 1.51.5–7.0 |
| `cmp` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `databases` | 72 | 79 | NoSee [bug 934640](https://bugzil.la/934640). | No | 60 | 14 | 72 | 72 | NoSee [bug 934640](https://bugzil.la/934640). | 51 | 14 | 11.0 |
| `deleteDatabase` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `open` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `worker_support` | 23 | 12 | 37 | 10 | 15 | 10 | 4.4 | 25 | 37 | 14 | 10 | 1.5 |


See also
--------


* [Using IndexedDB](indexeddb_api/using_indexeddb)
* Starting transactions: [`IDBDatabase`](idbdatabase)
* Using transactions: [`IDBTransaction`](idbtransaction)
* Setting a range of keys: [`IDBKeyRange`](idbkeyrange)
* Retrieving and making changes to your data: [`IDBObjectStore`](idbobjectstore)
* Using cursors: [`IDBCursor`](idbcursor)
* Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory>

IDBKeyRange
===========



The `IDBKeyRange` interface of the [IndexedDB API](indexeddb_api) represents a continuous interval over some data type that is used for keys. Records can be retrieved from [`IDBObjectStore`](idbobjectstore) and [`IDBIndex`](idbindex) objects using keys or a range of keys. You can limit the range using lower and upper bounds. For example, you can iterate over all values of a key in the value range A–Z.

 A key range can be a single value or a range with upper and lower bounds or endpoints. If the key range has both upper and lower bounds, then it is *bounded*; if it has no bounds, it is *unbounded*. A bounded key range can either be open (the endpoints are excluded) or closed (the endpoints are included). To retrieve all keys within a certain range, you can use the following code constructs:

 

| Range | Code |
| --- | --- |
| All keys ≥ **x** | [`IDBKeyRange.lowerBound`](idbkeyrange/lowerbound) `(x)` |
| All keys > **x** | [`IDBKeyRange.lowerBound`](idbkeyrange/lowerbound) `(x, true)` |
| All keys ≤ **y** | [`IDBKeyRange.upperBound`](idbkeyrange/upperbound) `(y)` |
| All keys < **y** | [`IDBKeyRange.upperBound`](idbkeyrange/upperbound) `(y, true)` |
| All keys ≥ **x** && ≤ **y** | [`IDBKeyRange.bound`](idbkeyrange/bound) `(x, y)` |
| All keys > **x** &&< **y** | [`IDBKeyRange.bound`](idbkeyrange/bound) `(x, y, true, true)` |
| All keys > **x** && ≤ **y** | [`IDBKeyRange.bound`](idbkeyrange/bound) `(x, y, true, false)` |
| All keys ≥ **x** &&< **y** | [`IDBKeyRange.bound`](idbkeyrange/bound) `(x, y, false, true)` |
| The key = **z** | [`IDBKeyRange.only`](idbkeyrange/only) `(z)` |

 A key is in a key range if the following conditions are true:

 * The lower value of the key range is one of the following:
	+ `undefined`
	+ Less than key value
	+ Equal to key value if `lowerOpen` is `false`.
* The upper value of the key range is one of the following:
	+ `undefined`
	+ Greater than key value
	+ Equal to key value if `upperOpen` is `false`.


 **Note:** This feature is available in [Web Workers](web_workers_api)

 

Instance properties
-------------------


 
[`IDBKeyRange.lower`](idbkeyrange/lower) Read only 
  Lower bound of the key range.

  
[`IDBKeyRange.upper`](idbkeyrange/upper) Read only 
  Upper bound of the key range.

  
[`IDBKeyRange.lowerOpen`](idbkeyrange/loweropen) Read only 
  Returns false if the lower-bound value is included in the key range.

  
[`IDBKeyRange.upperOpen`](idbkeyrange/upperopen) Read only 
  Returns false if the upper-bound value is included in the key range.

  
Static methods
--------------


 [`IDBKeyRange.bound()`](idbkeyrange/bound)  Creates a new key range with upper and lower bounds.

  [`IDBKeyRange.only()`](idbkeyrange/only)  Creates a new key range containing a single value.

  [`IDBKeyRange.lowerBound()`](idbkeyrange/lowerbound)  Creates a new key range with only a lower bound.

  [`IDBKeyRange.upperBound()`](idbkeyrange/upperbound)  Creates a new upper-bound key range.

  
Instance methods
----------------


 [`IDBKeyRange.includes()`](idbkeyrange/includes)  Returns a boolean indicating whether a specified key is inside the key range.

  
Examples
--------



 The following example illustrates how you'd use a key range. Here we declare a `keyRangeValue` as a range between values of `"A"` and `"F"`. We open a transaction (using [`IDBTransaction`](idbtransaction)) and an object store, and open a cursor with [`IDBObjectStore.openCursor`](idbobjectstore/opencursor), declaring `keyRangeValue` as its optional key range value. This means that the cursor will only retrieve records with keys inside that range. This range includes the values `"A"` and `"F"`, as we haven't declared that they should be open bounds. If we used `IDBKeyRange.bound("A", "F", true, true);`, then the range would not include `"A"` and `"F"`, only the values between them. 

  **Note:** For a more complete example allowing you to experiment with key range, have a look at our [IDBKeyRange-example](https://github.com/mdn/dom-examples/tree/main/indexeddb-examples/idbkeyrange) repo ([view the example live too](https://mdn.github.io/dom-examples/indexeddb-examples/idbkeyrange/).)

  
```
function displayData() {
  const keyRangeValue = IDBKeyRange.bound("A", "F");

  const transaction = db.transaction(["fThings"], "readonly");
  const objectStore = transaction.objectStore("fThings");

  objectStore.openCursor(keyRangeValue).onsuccess = (event) => {
    const cursor = event.target.result;
    if (cursor) {
      const listItem = document.createElement("li");
      listItem.textContent = `${cursor.value.fThing}, ${cursor.value.fRating}`;
      list.appendChild(listItem);

      cursor.continue();
    } else {
      console.log("Entries all displayed.");
    }
  };
}

```


Specifications
--------------




| Specification |
| --- |
| [Indexed Database API 3.0 # keyrange](https://w3c.github.io/IndexedDB/#keyrange) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `IDBKeyRange` | 2423–57 | 12 | 1610–16 | 10 | 1515–44 | 8 | ≤37–574.4 | 2525–57 | 22 | 1414–44 | 8 | 1.51.5–7.0 |
| `bound` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `includes` | 52 | 79 | 47 | No | 39 | 10.1 | 52 | 52 | 47 | 41 | 10.3 | 6.0 |
| `lower` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `lowerBound` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `lowerOpen` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `only` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `upper` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `upperBound` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `upperOpen` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `worker_support` | 23 | 12 | 37 | 10 | 15 | 10 | 4.4 | 25 | 37 | 14 | 10 | 1.5 |


See also
--------


* [Using IndexedDB](indexeddb_api/using_indexeddb)
* Starting transactions: [`IDBDatabase`](idbdatabase)
* Using transactions: [`IDBTransaction`](idbtransaction)
* Setting a range of keys: [`IDBKeyRange`](idbkeyrange)
* Retrieving and making changes to your data: [`IDBObjectStore`](idbobjectstore)
* Using cursors: [`IDBCursor`](idbcursor)
* Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange>

IDBRequest
==========



The `IDBRequest` interface of the IndexedDB API provides access to results of asynchronous requests to databases and database objects using event handler attributes. Each reading and writing operation on a database is done using a request.

 The request object does not initially contain any information about the result of the operation, but once information becomes available, an event is fired on the request, and the information becomes available through the properties of the `IDBRequest` instance.

 All asynchronous operations immediately return an [`IDBRequest`](idbrequest) instance. Each request has a `readyState` that is set to the `'pending'` state; this changes to `'done'` when the request is completed or fails. When the state is set to `done`, every request returns a `result` and an `error`, and an event is fired on the request. When the state is still `pending`, any attempt to access the `result` or `error` raises an `InvalidStateError` exception.

 In plain words, all asynchronous methods return a request object. If the request has been completed successfully, the result is made available through the `result` property and an event indicating success is fired at the request ([`success`](idbrequest/success_event)). If an error occurs while performing the operation, the exception is made available through the `error` property and an error event is fired ([`error`](idbrequest/error_event)).

 The interface [`IDBOpenDBRequest`](idbopendbrequest) is derived from `IDBRequest`.


 **Note:** This feature is available in [Web Workers](web_workers_api)

   EventTarget IDBRequest

Instance properties
-------------------



*Also inherits properties from [`EventTarget`](eventtarget).*

  
[`IDBRequest.error`](idbrequest/error) Read only 
  Returns a [`DOMException`](domexception) in the event of an unsuccessful request, indicating what went wrong.

  
[`IDBRequest.result`](idbrequest/result) Read only 
  Returns the result of the request. If the request is not completed, the result is not available and an `InvalidStateError` exception is thrown.

  
[`IDBRequest.source`](idbrequest/source) Read only 
  The source of the request, such as an [`IDBIndex`](idbindex) or an [`IDBObjectStore`](idbobjectstore). If no source exists (such as when calling [`IDBFactory.open`](idbfactory/open)), it returns null.

  
[`IDBRequest.readyState`](idbrequest/readystate) Read only 
  The state of the request. Every request starts in the `pending` state. The state changes to `done` when the request completes successfully or when an error occurs.

  
[`IDBRequest.transaction`](idbrequest/transaction) Read only 
  The transaction for the request. This property can be null for certain requests, for example those returned from [`IDBFactory.open`](idbfactory/open) unless an upgrade is needed. (You're just connecting to a database, so there is no transaction to return).

  

Instance methods
----------------


*No methods, but inherits methods from [`EventTarget`](eventtarget).*


Events
------



Listen to these events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface.

  [`error`](idbrequest/error_event)  Fired when an error caused a request to fail.

  [`success`](idbrequest/success_event)  Fired when an `IDBRequest` succeeds.

  

Example
-------



In the following code snippet, we open a database asynchronously and make a request; `onerror` and `onsuccess` functions are included to handle the success and error cases. For a full working example, see our [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) app ([view example live](https://mdn.github.io/dom-examples/to-do-notifications/).)

 
```
let db;

// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

// these two event handlers act on the database being
// opened successfully, or not
DBOpenRequest.onerror = (event) => {
  note.innerHTML += "<li>Error loading database.</li>";
};

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database.
  db = DBOpenRequest.result;
};

```


Specifications
--------------




| Specification |
| --- |
| [Indexed Database API 3.0 # request-api](https://w3c.github.io/IndexedDB/#request-api) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `IDBRequest` | 242–57 | 12 | 1610–16 | 10 | 15 | 8 | ≤37–574.4 | 2525–57 | 22 | 14 | 8 | 1.51.5–7.0 |
| `error` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `error_event` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `readyState` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `result` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `source` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `success_event` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `transaction` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `worker_support` | 23 | 12 | 37 | 10 | 15 | 10 | 4.4 | 25 | 37 | 14 | 10 | 1.5 |


See also
--------


* [Using IndexedDB](indexeddb_api/using_indexeddb)
* Starting transactions: [`IDBDatabase`](idbdatabase)
* Using transactions: [`IDBTransaction`](idbtransaction)
* Setting a range of keys: [`IDBKeyRange`](idbkeyrange)
* Retrieving and making changes to your data: [`IDBObjectStore`](idbobjectstore)
* Using cursors: [`IDBCursor`](idbcursor)
* Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest>

IDBTransaction
==============



The `IDBTransaction` interface of the [IndexedDB API](indexeddb_api) provides a static, asynchronous transaction on a database using event handler attributes. All reading and writing of data is done within transactions. You use [`IDBDatabase`](idbdatabase) to start transactions, [`IDBTransaction`](idbtransaction) to set the mode of the transaction (e.g. is it `readonly` or `readwrite`), and you access an [`IDBObjectStore`](idbobjectstore) to make a request. You can also use an `IDBTransaction` object to abort transactions.


 **Note:** This feature is available in [Web Workers](web_workers_api)

   EventTarget IDBTransaction Transactions are started when the transaction is created, not when the first request is placed; for example consider this:

 
```
const trans1 = db.transaction("foo", "readwrite");
const trans2 = db.transaction("foo", "readwrite");
const objectStore2 = trans2.objectStore("foo");
const objectStore1 = trans1.objectStore("foo");
objectStore2.put("2", "key");
objectStore1.put("1", "key");

```
 After the code is executed the object store should contain the value "2", since `trans2` should run after `trans1`.



Transaction failures
--------------------



Transactions can fail for a fixed number of reasons, all of which (except the user agent crash) will trigger an abort callback:

 * Abort due to bad requests, e.g. trying to `add()` the same key twice, or `put()` with the same index key with a uniqueness constraint. This causes an error on the request, which can bubble up to an error on the transaction, which aborts the transaction. This can be prevented by using `preventDefault()` on the error event on the request.
* An explicit `abort()` call from script.
* An uncaught exception in the request's `success`/`error` handler.
* An I/O error (e.g. an actual failure to write to disk, or other OS/hardware failure).
* Quota exceeded.
* A user agent crash.



Firefox durability guarantees
-----------------------------



Note that as of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see [Webkit bug 1112702](https://bugzil.la/1112702).) Previously in a `readwrite` transaction, a [`complete`](idbtransaction/complete_event) event was fired only when all data was guaranteed to have been flushed to disk. In Firefox 40+ the `complete` event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The `complete` event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare, most consumers should not need to concern themselves further.

 If you must ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the `complete` event by creating a transaction using the experimental (non-standard) `readwriteflush` mode (see [`IDBDatabase.transaction`](idbdatabase/transaction).



Instance properties
-------------------


 
[`IDBTransaction.db`](idbtransaction/db) Read only 
  The database connection with which this transaction is associated.

  
[`IDBTransaction.durability`](idbtransaction/durability) Read only 
  Returns the durability hint the transaction was created with.

  
[`IDBTransaction.error`](idbtransaction/error) Read only 
  Returns a [`DOMException`](domexception) indicating the type of error that occurred when there is an unsuccessful transaction. This property is `null` if the transaction is not finished, is finished and successfully committed, or was aborted with the [`IDBTransaction.abort()`](idbtransaction/abort) function.

  
[`IDBTransaction.mode`](idbtransaction/mode) Read only 
  The mode for isolating access to data in the object stores that are in the scope of the transaction. The default value is [`readonly`](#const_read_only).

  
[`IDBTransaction.objectStoreNames`](idbtransaction/objectstorenames) Read only 
  Returns a [`DOMStringList`](domstringlist) of the names of [`IDBObjectStore`](idbobjectstore) objects associated with the transaction.

  
Instance methods
----------------



Inherits from: [`EventTarget`](eventtarget)

  [`IDBTransaction.abort()`](idbtransaction/abort)  Rolls back all the changes to objects in the database associated with this transaction. If this transaction has been aborted or completed, this method fires an error event.

  [`IDBTransaction.objectStore()`](idbtransaction/objectstore)  Returns an [`IDBObjectStore`](idbobjectstore) object representing an object store that is part of the scope of this transaction.

  [`IDBTransaction.commit()`](idbtransaction/commit)  For an active transaction, commits the transaction. Note that this doesn't normally *have* to be called — a transaction will automatically commit when all outstanding requests have been satisfied and no new requests have been made. `commit()` can be used to start the commit process without waiting for events from outstanding requests to be dispatched.

  

Events
------



Listen to these events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface.

  [`abort`](idbtransaction/abort_event)   An event fired when the `IndexedDB` transaction is aborted. Also available via the `onabort` property; this event bubbles to [`IDBDatabase`](idbdatabase). 

  [`complete`](idbtransaction/complete_event)   An event fired when the transaction successfully completes. Also available via the `oncomplete` property. 

  [`error`](idbtransaction/error_event)   An event fired when a request returns an error and the event bubbles up to the connection object ([`IDBDatabase`](idbdatabase)). Also available via the `onerror` property. 

  

Mode constants
--------------



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

  **Warning:** These constants are no longer available — they were removed in Gecko 25. You should use the string constants directly instead. ([Firefox bug 888598](https://bugzil.la/888598))

  Transactions can have one of three modes:

 

| Constant | Value | Description |
| --- | --- | --- |
| `READ\_ONLY` | "readonly" (0 in Chrome) | Allows data to be read but not changed. |
| `READ\_WRITE` | "readwrite" (1 in Chrome) |  Allows reading and writing of data in existing data stores to be changed.  |
| `VERSION\_CHANGE` | "versionchange" (2 in Chrome) |  Allows any operation to be performed, including ones that delete and create object stores and indexes. Transactions of this mode cannot run concurrently with other transactions. Transactions in this mode are known as "upgrade transactions."  |

 Even if these constants are now deprecated, you can still use them to provide backward compatibility if required (in Chrome [the change was made in version 21](https://peter.sh/2012/05/tab-sizing-string-values-for-indexeddb-and-chrome-21/)). You should code defensively in case the object is not available anymore:

 
```
const myIDBTransaction = window.IDBTransaction ||
  window.webkitIDBTransaction || { READ\_WRITE: "readwrite" };

```


Examples
--------



In the following code snippet, we open a read/write transaction on our database and add some data to an object store. Note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. For a full working example, see our [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) app ([view example live](https://mdn.github.io/dom-examples/to-do-notifications/)).

 
```
const note = document.getElementById("notifications");

// an instance of a db object for us to store the IDB data in
let db;

// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db
  // variable. This is used a lot below
  db = DBOpenRequest.result;

  // Add the data to the database
  addData();
};

function addData() {
  // Create a new object to insert into the IDB
  const newItem = [
    {
      taskTitle: "Walk dog",
      hours: 19,
      minutes: 30,
      day: 24,
      month: "December",
      year: 2013,
      notified: "no",
    },
  ];

  // open a read/write db transaction, ready to add data
  const transaction = db.transaction(["toDoList"], "readwrite");

  // report on the success of opening the transaction
  transaction.oncomplete = (event) => {
    note.innerHTML +=
      "<li>Transaction completed: database modification finished.</li>";
  };

  transaction.onerror = (event) => {
    note.innerHTML +=
      "<li>Transaction not opened due to error. Duplicate items not allowed.</li>";
  };

  // create an object store on the transaction
  const objectStore = transaction.objectStore("toDoList");

  // add our newItem object to the object store
  const objectStoreRequest = objectStore.add(newItem[0]);

  objectStoreRequest.onsuccess = (event) => {
    // report the success of the request (this does not mean the item
    // has been stored successfully in the DB - for that you need transaction.oncomplete)
    note.innerHTML += "<li>Request successful.</li>";
  };
}

```


Specifications
--------------




| Specification |
| --- |
| [Indexed Database API 3.0 # transaction](https://w3c.github.io/IndexedDB/#transaction) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `IDBTransaction` | 2423–57 | 12 | 1610–16 | 10 | 15 | 8 | ≤37–574.4 | 2525–57 | 22 | 14 | 8 | 1.51.5–7.0 |
| `abort` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `abort_event` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `commit` | 76 | 79 | 74 | No | 63 | 15 | 76 | 76 | 79 | 54 | 15 | 12.0 |
| `complete_event` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `db` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `durability` | 83 | 83 | No | No | 70 | 15 | 83 | 83 | No | 59 | 15 | 13.0 |
| `error` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `error_event` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `mode` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `objectStore` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `objectStoreNames` | 48 | 79 | 10 | No | 35 | 10.1 | 48 | 48 | 22 | 35 | 10.3 | 5.0 |
| `worker_support` | 23 | 12 | 37 | 10 | 15 | 10 | 4.4 | 25 | 37 | 14 | 10 | 1.5 |


See also
--------


* [Using IndexedDB](indexeddb_api/using_indexeddb)
* Starting transactions: [`IDBDatabase`](idbdatabase)
* Using transactions: [`IDBTransaction`](idbtransaction)
* Setting a range of keys: [`IDBKeyRange`](idbkeyrange)
* Retrieving and making changes to your data: [`IDBObjectStore`](idbobjectstore)
* Using cursors: [`IDBCursor`](idbcursor)
* Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction>

IDBVersionChangeEvent
=====================



The `IDBVersionChangeEvent` interface of the [IndexedDB API](indexeddb_api) indicates that the version of the database has changed, as the result of an [`onupgradeneeded`](idbopendbrequest/upgradeneeded_event) event handler function.


 **Note:** This feature is available in [Web Workers](web_workers_api)

   Event IDBVersionChangeEvent

Constructor
-----------


 [`IDBVersionChangeEvent()`](idbversionchangeevent/idbversionchangeevent)  Creates and returns a new `IDBVersionChangeEvent` object which is used to represent when a version of the database has changed.

  
Instance properties
-------------------



*Also inherits properties from its parent, [`Event`](event) interface.*

  
[`IDBVersionChangeEvent.oldVersion`](idbversionchangeevent/oldversion) Read only 
  Returns the old version of the database.

  
[`IDBVersionChangeEvent.newVersion`](idbversionchangeevent/newversion) Read only 
  Returns the new version of the database.

  

Instance methods
----------------


*No specific method, but inherits methods from its parent, [`Event`](event) interface.*


Example
-------



In the following code snippet, we make a request to open a database, and include handlers for the success and error cases. Upon a version change (after an `upgradeneeded` event), the `success` event will implement the `IDBVersionChangeEvent` interface. For a full working example, see our [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) app ([view example live](https://mdn.github.io/dom-examples/to-do-notifications/)).

 
```
const note = document.querySelector("ul");

// Let us open version 4 of our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

// these two event handlers act on the database being opened successfully, or not
DBOpenRequest.onerror = (event) => {
  note.innerHTML += "<li>Error loading database.</li>";
};

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db variable. This is used a lot later on, for opening transactions and suchlike.
  const db = DBOpenRequest.result;
};

```


Specifications
--------------




| Specification |
| --- |
| [Indexed Database API 3.0 # events](https://w3c.github.io/IndexedDB/#events) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `IDBVersionChangeEvent` | 41 | 79 | 25 | No | 28 | 10 | 41 | 41 | 25 | 28 | 10 | 4.0 |
| `IDBVersionChangeEvent` | 2412 | 12 | 1610–16 | 10 | 1515 | 8 | ≤374.4 | 2518 | 22 | 1414 | 8 | 1.51.0 |
| `newVersion` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `oldVersion` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `worker_support` | 23 | 12 | 37 | 10 | 15 | 10 | 4.4 | 25 | 37 | 14 | 10 | 1.5 |


See also
--------


* [Using IndexedDB](indexeddb_api/using_indexeddb)
* Starting transactions: [`IDBDatabase`](idbdatabase)
* Using transactions: [`IDBTransaction`](idbtransaction)
* Setting a range of keys: [`IDBKeyRange`](idbkeyrange)
* Retrieving and making changes to your data: [`IDBObjectStore`](idbobjectstore)
* Using cursors: [`IDBCursor`](idbcursor)
* Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeEvent>

IDBIndex
========



`IDBIndex` interface of the [IndexedDB API](indexeddb_api) provides asynchronous access to an [index](indexeddb_api/basic_terminology#index) in a database. An index is a kind of object store for looking up records in another object store, called the referenced object store. You use this interface to retrieve data.

 You can retrieve records in an object store through the primary key or by using an index. An index lets you look up records in an object store using properties of the values in the object stores records other than the primary key

 The index is a persistent key-value storage where the value part of its records is the key part of a record in the referenced object store. The records in an index are automatically populated whenever records in the referenced object store are inserted, updated, or deleted. Each record in an index can point to only one record in its referenced object store, but several indexes can reference the same object store. When the object store changes, all indexes that refers to the object store are automatically updated.

 You can grab a set of keys within a range. To learn more, see [`IDBKeyRange`](idbkeyrange).


 **Note:** This feature is available in [Web Workers](web_workers_api)

 

Instance properties
-------------------


 
[`IDBIndex.isAutoLocale`](idbindex/isautolocale) Read only   Non-standard   Experimental 
  Returns a boolean value indicating whether the index had a `locale` value of `auto` specified upon its creation (see the [`options`](idbobjectstore/createindex#options) parameter to [`IDBObjectStore.createIndex()`](idbobjectstore/createindex).)

  
[`IDBIndex.locale`](idbindex/locale) Read only   Non-standard   Experimental 
  Returns the locale of the index (for example `en-US`, or `pl`) if it had a `locale` value specified upon its creation (see the [`options`](idbobjectstore/createindex#options) parameter to [`IDBObjectStore.createIndex()`](idbobjectstore/createindex).)

  [`IDBIndex.name`](idbindex/name)  The name of this index.

  
[`IDBIndex.objectStore`](idbindex/objectstore) Read only 
  The name of the object store referenced by this index.

  
[`IDBIndex.keyPath`](idbindex/keypath) Read only 
  The [key path](indexeddb_api/basic_terminology#key_path) of this index. If null, this index is not auto-populated.

  
[`IDBIndex.multiEntry`](idbindex/multientry) Read only 
  Affects how the index behaves when the result of evaluating the index's key path yields an array. If `true`, there is one record in the index for each item in an array of keys. If `false`, then there is one record for each key that is an array.

  
[`IDBIndex.unique`](idbindex/unique) Read only 
  If `true`, this index does not allow duplicate values for a key.

  
Instance methods
----------------



Inherits from: [EventTarget](eventtarget)

  [`IDBIndex.count()`](idbindex/count)  Returns an [`IDBRequest`](idbrequest) object, and in a separate thread, returns the number of records within a key range.

  [`IDBIndex.get()`](idbindex/get)  Returns an [`IDBRequest`](idbrequest) object, and, in a separate thread, finds either the value in the referenced object store that corresponds to the given key or the first corresponding value, if `key` is an [`IDBKeyRange`](idbkeyrange).

  [`IDBIndex.getKey()`](idbindex/getkey)  Returns an [`IDBRequest`](idbrequest) object, and, in a separate thread, finds either the given key or the primary key, if `key` is an [`IDBKeyRange`](idbkeyrange).

  [`IDBIndex.getAll()`](idbindex/getall)  Returns an [`IDBRequest`](idbrequest) object, in a separate thread, finds all matching values in the referenced object store that correspond to the given key or are in range, if `key` is an [`IDBKeyRange`](idbkeyrange).

  [`IDBIndex.getAllKeys()`](idbindex/getallkeys)  Returns an [`IDBRequest`](idbrequest) object, in a separate thread, finds all matching keys in the referenced object store that correspond to the given key or are in range, if `key` is an [`IDBKeyRange`](idbkeyrange).

  [`IDBIndex.openCursor()`](idbindex/opencursor)  Returns an [`IDBRequest`](idbrequest) object, and, in a separate thread, creates a [cursor](indexeddb_api/basic_terminology#cursor) over the specified key range.

  [`IDBIndex.openKeyCursor()`](idbindex/openkeycursor)  Returns an [`IDBRequest`](idbrequest) object, and, in a separate thread, creates a cursor over the specified key range, as arranged by this index.

  

Example
-------



In the following example we open a transaction and an object store, then get the index `lName` from a simple contacts database. We then open a basic cursor on the index using [`IDBIndex.openCursor`](idbindex/opencursor) — this works the same as opening a cursor directly on an `ObjectStore` using [`IDBObjectStore.openCursor`](idbobjectstore/opencursor) except that the returned records are sorted based on the index, not the primary key.

 Finally, we iterate through each record, and insert the data into an HTML table. For a complete working example, see our [IndexedDB-examples demo repo](https://github.com/mdn/dom-examples/tree/main/indexeddb-examples/idbindex) ([View the example live](https://mdn.github.io/dom-examples/indexeddb-examples/idbindex/).)

 
```
function displayDataByIndex() {
  tableEntry.innerHTML = "";
  const transaction = db.transaction(["contactsList"], "readonly");
  const objectStore = transaction.objectStore("contactsList");

  const myIndex = objectStore.index("lName");
  myIndex.openCursor().onsuccess = (event) => {
    const cursor = event.target.result;
    if (cursor) {
      const tableRow = document.createElement("tr");
      tableRow.innerHTML =
        `<td>${cursor.value.id}</td>` +
        `<td>${cursor.value.lName}</td>` +
        `<td>${cursor.value.fName}</td>` +
        `<td>${cursor.value.jTitle}</td>` +
        `<td>${cursor.value.company}</td>` +
        `<td>${cursor.value.eMail}</td>` +
        `<td>${cursor.value.phone}</td>` +
        `<td>${cursor.value.age}</td>`;
      tableEntry.appendChild(tableRow);

      cursor.continue();
    } else {
      console.log("Entries all displayed.");
    }
  };
}

```


Specifications
--------------




| Specification |
| --- |
| [Indexed Database API 3.0 # index-interface](https://w3c.github.io/IndexedDB/#index-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `IDBIndex` | 2423–57 | 12 | 1610–16 | 10 | 15 | 8 | ≤37–574.4 | 2525–57 | 22 | 14 | 8 | 1.51.5–7.0 |
| `count` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `get` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `getAll` | 48 | 79 | 44 | No | 35 | 10.1 | 48 | 48 | 44 | 35 | 10.3 | 5.0 |
| `getAllKeys` | 48 | 79 | 44 | No | 35 | 10.1 | 48 | 48 | 44 | 35 | 10.3 | 5.0 |
| `getKey` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `isAutoLocale` | No | No | 43 | No | No | No | No | No | No | No | No | No |
| `keyPath` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `locale` | No | No | 43 | No | No | No | No | No | No | No | No | No |
| `multiEntry` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `name` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `objectStore` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `openCursor` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `openKeyCursor` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `unique` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `worker_support` | 23 | 12 | 37 | 10 | 15 | 10 | 4.4 | 25 | 37 | 14 | 10 | 1.5 |


See also
--------


* [Using IndexedDB](indexeddb_api/using_indexeddb)
* Starting transactions: [`IDBDatabase`](idbdatabase)
* Using transactions: [`IDBTransaction`](idbtransaction)
* Setting a range of keys: [`IDBKeyRange`](idbkeyrange)
* Retrieving and making changes to your data: [`IDBObjectStore`](idbobjectstore)
* Using cursors: [`IDBCursor`](idbcursor)
* Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex>

IDBLocaleAwareKeyRange
======================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.


**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The `IDBLocaleAwareKeyRange` interface of the [IndexedDB API](indexeddb_api) is a Firefox-specific version of [`IDBKeyRange`](idbkeyrange) — it functions in exactly the same fashion, and has the same properties and methods, but it is intended for use with [`IDBIndex`](idbindex) objects when the original index had a `locale` value specified upon its creation (see the [`options`](idbobjectstore/createindex#options) parameter to [`IDBObjectStore.createIndex()`](idbobjectstore/createindex)) — that is, it has [locale aware sorting](indexeddb_api/using_indexeddb#locale-aware_sorting) enabled.



Instance methods
----------------


*This interface inherits all the methods of its parent interface, [`IDBKeyRange`](idbkeyrange).*


Instance properties
-------------------



*This interface inherits all the properties of its parent interface, [`IDBKeyRange`](idbkeyrange).*

 Bear in mind however that `IDBLocaleAwareKeyRange` has its own implementation of [`IDBKeyRange.bound`](idbkeyrange/bound). This is because when you use `bound()`, it checks if lower bound < upper bound, and throws an exception if that's not the case. With locale-aware indexes, the meaning of < depends on the locale, so for example in Lithuanian Y is sorted between I and K. The only difference between `IDBKeyRange` and `IDBLocaleAwareKeyRange` is that the latter doesn't do the aforementioned check.

 Developers should always use `IDBLocaleAwareKeyRange` when dealing with locale-aware indexes.



Examples
--------



```
function displayData() {
  const keyRangeValue = IDBLocaleAwareKeyRange.bound("A", "F");

  const transaction = db.transaction(["fThings"], "readonly");
  const objectStore = transaction.objectStore("fThings");

  const myIndex = objectStore.index("lName");
  myIndex.openCursor(keyRangeValue).onsuccess = (event) => {
    const cursor = event.target.result;
    if (cursor) {
      const tableRow = document.createElement("tr");
      tableRow.innerHTML =
        `<td>${cursor.value.id}</td>` +
        `<td>${cursor.value.lName}</td>` +
        `<td>${cursor.value.fName}</td>` +
        `<td>${cursor.value.jTitle}</td>` +
        `<td>${cursor.value.company}</td>` +
        `<td>${cursor.value.eMail}</td>` +
        `<td>${cursor.value.phone}</td>` +
        `<td>${cursor.value.age}</td>`;
      tableEntry.appendChild(tableRow);

      cursor.continue();
    } else {
      console.log("Entries all displayed.");
    }
  };
}

```

Specifications
--------------


Not currently part of any specification.


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `IDBLocaleAwareKeyRange` | No | No | 43 | No | No | No | No | No | No | No | No | No |


See also
--------


* [Using IndexedDB](indexeddb_api/using_indexeddb)
* Starting transactions: [`IDBDatabase`](idbdatabase)
* Using transactions: [`IDBTransaction`](idbtransaction)
* Setting a range of keys: [`IDBKeyRange`](idbkeyrange)
* Retrieving and making changes to your data: [`IDBObjectStore`](idbobjectstore)
* Using cursors: [`IDBCursor`](idbcursor)
* Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/IDBLocaleAwareKeyRange>

IDBObjectStore
==============



The `IDBObjectStore` interface of the [IndexedDB API](indexeddb_api) represents an object store in a database. Records within an object store are sorted according to their keys. This sorting enables fast insertion, look-up, and ordered retrieval.


 **Note:** This feature is available in [Web Workers](web_workers_api)

 

Instance properties
-------------------


 
[`IDBObjectStore.indexNames`](idbobjectstore/indexnames) Read only 
  A list of the names of [indexes](indexeddb_api/basic_terminology#index) on objects in this object store.

  
[`IDBObjectStore.keyPath`](idbobjectstore/keypath) Read only 
  The [key path](indexeddb_api/basic_terminology#key_path) of this object store. If this attribute is `null`, the application must provide a key for each modification operation.

  [`IDBObjectStore.name`](idbobjectstore/name)  The name of this object store.

  
[`IDBObjectStore.transaction`](idbobjectstore/transaction) Read only 
  The [`IDBTransaction`](idbtransaction) object to which this object store belongs.

  
[`IDBObjectStore.autoIncrement`](idbobjectstore/autoincrement) Read only 
  The value of the auto increment flag for this object store.

  
Instance methods
----------------


 [`IDBObjectStore.add()`](idbobjectstore/add)  Returns an [`IDBRequest`](idbrequest) object, and, in a separate thread, creates a [structured clone](https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#structured-clone) of the `value`, and stores the cloned value in the object store. This is for adding new records to an object store.

  [`IDBObjectStore.clear()`](idbobjectstore/clear)  Creates and immediately returns an [`IDBRequest`](idbrequest) object, and clears this object store in a separate thread. This is for deleting all current records out of an object store.

  [`IDBObjectStore.count()`](idbobjectstore/count)  Returns an [`IDBRequest`](idbrequest) object, and, in a separate thread, returns the total number of records that match the provided key or [`IDBKeyRange`](idbkeyrange). If no arguments are provided, it returns the total number of records in the store.

  [`IDBObjectStore.createIndex()`](idbobjectstore/createindex)  Creates a new index during a version upgrade, returning a new [`IDBIndex`](idbindex) object in the connected database.

  [`IDBObjectStore.delete()`](idbobjectstore/delete)  returns an [`IDBRequest`](idbrequest) object, and, in a separate thread, deletes the store object selected by the specified key. This is for deleting individual records out of an object store.

  [`IDBObjectStore.deleteIndex()`](idbobjectstore/deleteindex)  Destroys the specified index in the connected database, used during a version upgrade.

  [`IDBObjectStore.get()`](idbobjectstore/get)  Returns an [`IDBRequest`](idbrequest) object, and, in a separate thread, returns the store object store selected by the specified key. This is for retrieving specific records from an object store.

  [`IDBObjectStore.getKey()`](idbobjectstore/getkey)  Returns an [`IDBRequest`](idbrequest) object, and, in a separate thread retrieves and returns the record key for the object in the object stored matching the specified parameter.

  [`IDBObjectStore.getAll()`](idbobjectstore/getall)  Returns an [`IDBRequest`](idbrequest) object retrieves all objects in the object store matching the specified parameter or all objects in the store if no parameters are given.

  [`IDBObjectStore.getAllKeys()`](idbobjectstore/getallkeys)  Returns an [`IDBRequest`](idbrequest) object retrieves record keys for all objects in the object store matching the specified parameter or all objects in the store if no parameters are given.

  [`IDBObjectStore.index()`](idbobjectstore/index)  Opens an index from this object store after which it can, for example, be used to return a sequence of records sorted by that index using a cursor.

  [`IDBObjectStore.openCursor()`](idbobjectstore/opencursor)  Returns an [`IDBRequest`](idbrequest) object, and, in a separate thread, returns a new [`IDBCursorWithValue`](idbcursorwithvalue) object. Used for iterating through an object store by primary key with a cursor.

  [`IDBObjectStore.openKeyCursor()`](idbobjectstore/openkeycursor)  Returns an [`IDBRequest`](idbrequest) object, and, in a separate thread, returns a new [`IDBCursor`](idbcursor). Used for iterating through an object store with a key.

  [`IDBObjectStore.put()`](idbobjectstore/put)  Returns an [`IDBRequest`](idbrequest) object, and, in a separate thread, creates a [structured clone](https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#structured-clone) of the `value`, and stores the cloned value in the object store. This is for updating existing records in an object store when the transaction's mode is `readwrite`.

  
Example
-------



This example shows a variety of different uses of object stores, from updating the data structure with [`IDBObjectStore.createIndex`](idbobjectstore/createindex) inside an `onupgradeneeded` function, to adding a new item to our object store with [`IDBObjectStore.add`](idbobjectstore/add). For a full working example, see our [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) app ([view example live](https://mdn.github.io/dom-examples/to-do-notifications/)).

 
```
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in db.
  db = DBOpenRequest.result;
};

// This event handles the event whereby a new version of
// the database needs to be created Either one has not
// been created before, or a new version number has been
// submitted via the window.indexedDB.open line above
DBOpenRequest.onupgradeneeded = (event) => {
  const db = event.target.result;

  db.onerror = (event) => {
    note.innerHTML += "<li>Error loading database.</li>";
  };

  // Create an objectStore for this database

  const objectStore = db.createObjectStore("toDoList", {
    keyPath: "taskTitle",
  });

  // define what data items the objectStore will contain

  objectStore.createIndex("hours", "hours", { unique: false });
  objectStore.createIndex("minutes", "minutes", { unique: false });
  objectStore.createIndex("day", "day", { unique: false });
  objectStore.createIndex("month", "month", { unique: false });
  objectStore.createIndex("year", "year", { unique: false });

  objectStore.createIndex("notified", "notified", { unique: false });

  note.innerHTML += "<li>Object store created.</li>";
};

// Create a new item to add in to the object store
const newItem = [
  {
    taskTitle: "Walk dog",
    hours: 19,
    minutes: 30,
    day: 24,
    month: "December",
    year: 2013,
    notified: "no",
  },
];

// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["toDoList"], "readwrite");

// report on the success of the transaction completing, when everything is done
transaction.oncomplete = (event) => {
  note.innerHTML += "<li>Transaction completed.</li>";
};

transaction.onerror = (event) => {
  note.innerHTML +=
    "<li>Transaction not opened due to error. Duplicate items not allowed.</li>";
};

// create an object store on the transaction
const objectStore = transaction.objectStore("toDoList");
// make a request to add our newItem object to the object store
const objectStoreRequest = objectStore.add(newItem[0]);

objectStoreRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Request successful .</li>";
};

```


Specifications
--------------




| Specification |
| --- |
| [Indexed Database API 3.0 # object-store-interface](https://w3c.github.io/IndexedDB/#object-store-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `IDBObjectStore` | 2423–57 | 12 | 1610–16 | 10 | 15 | 8 | ≤37–574.4 | 2525–57 | 22 | 14 | 8 | 1.51.5–7.0 |
| `add` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `autoIncrement` | 23 | 79 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `clear` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `count` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `createIndex` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `delete` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `deleteIndex` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `get` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `getAll` | 48 | 79 | 44 | No | 35 | 10.1 | 48 | 48 | 48 | 35 | 10.3 | 5.0 |
| `getAllKeys` | 48 | 79 | 44 | No | 35 | 10.1 | 48 | 48 | 48 | 35 | 10.3 | 5.0 |
| `getKey` | 48 | 79 | 51 | No | 45 | 10.1 | 48 | 48 | 58 | 43 | 10.3 | 5.0 |
| `index` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `indexNames` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `keyPath` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `name` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `openCursor` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `openKeyCursor` | 23 | 79 | 44 | 10 | 15 | 10.1 | 4.4 | 25 | 22 | 14 | 10.3 | 1.5 |
| `put` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `transaction` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `worker_support` | 23 | 12 | 37 | 10 | 15 | 10 | 4.4 | 25 | 37 | 14 | 10 | 1.5 |


See also
--------


* [Using IndexedDB](indexeddb_api/using_indexeddb)
* Starting transactions: [`IDBDatabase`](idbdatabase)
* Using transactions: [`IDBTransaction`](idbtransaction)
* Setting a range of keys: [`IDBKeyRange`](idbkeyrange)
* Retrieving and making changes to your data: [`IDBObjectStore`](idbobjectstore)
* Using cursors: [`IDBCursor`](idbcursor)
* Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore>

IDBOpenDBRequest
================



The `IDBOpenDBRequest` interface of the IndexedDB API provides access to the results of requests to open or delete databases (performed using [`IDBFactory.open`](idbfactory/open) and [`IDBFactory.deleteDatabase`](idbfactory/deletedatabase)), using specific event handler attributes.


 **Note:** This feature is available in [Web Workers](web_workers_api)

   EventTarget IDBRequest IDBOpenDBRequest

Instance properties
-------------------


*Also inherits properties from its parents [`IDBRequest`](idbrequest) and [`EventTarget`](eventtarget)*.


Instance methods
----------------


*No methods, but inherits methods from its parents [`IDBRequest`](idbrequest) and [`EventTarget`](eventtarget).*


Events
------



*Events defined on parent interfaces, [`IDBRequest`](idbrequest) and [`EventTarget`](eventtarget), can also be dispatched on `IDBOpenDBRequest` objects.*

 Listen to these generic and specific events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface.

 Events specific to this interface are:

  [`blocked`](idbopendbrequest/blocked_event)  Fired when an open connection to a database is blocking a `versionchange` transaction on the same database. Also available via the [`onblocked`](idbopendbrequest/blocked_event) property.

  [`upgradeneeded`](idbopendbrequest/upgradeneeded_event)  Fired when an attempt was made to open a database with a version number higher than its current version. Also available via the [`onupgradeneeded`](idbopendbrequest/upgradeneeded_event) property.

  

Example
-------



In the following example you can see the onupgradeneeded handler being used to update the database structure if a database with a higher version number is loaded. For a full working example, see our [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) app ([view example live](https://mdn.github.io/dom-examples/to-do-notifications/).)

 
```
let db;

// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

// these event handlers act on the database being opened.
DBOpenRequest.onerror = (event) => {
  note.innerHTML += "<li>Error loading database.</li>";
};

DBOpenRequest.onsuccess = (event) => {
  note.innerHTML += "<li>Database initialized.</li>";

  // store the result of opening the database in the db
  // variable. This is used a lot below
  db = DBOpenRequest.result;

  // Run the displayData() function to populate the task
  // list with all the to-do list data already in the IDB
  displayData();
};

// This event handles the event whereby a new version of
// the database needs to be created Either one has not
// been created before, or a new version number has been
// submitted via the window.indexedDB.open line above
// it is only implemented in recent browsers
DBOpenRequest.onupgradeneeded = (event) => {
  const db = event.target.result;

  db.onerror = (event) => {
    note.innerHTML += "<li>Error loading database.</li>";
  };

  // Create an objectStore for this database
  const objectStore = db.createObjectStore("toDoList", {
    keyPath: "taskTitle",
  });

  // define what data items the objectStore will contain

  objectStore.createIndex("hours", "hours", { unique: false });
  objectStore.createIndex("minutes", "minutes", { unique: false });
  objectStore.createIndex("day", "day", { unique: false });
  objectStore.createIndex("month", "month", { unique: false });
  objectStore.createIndex("year", "year", { unique: false });
  objectStore.createIndex("notified", "notified", { unique: false });
};

```


Specifications
--------------




| Specification |
| --- |
| [Indexed Database API 3.0 # idbopendbrequest](https://w3c.github.io/IndexedDB/#idbopendbrequest) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `IDBOpenDBRequest` | 2423–57 | 12 | 1610–16 | 10 | 15 | 8 | ≤37–574.4 | 2525–57 | 22 | 14 | 8 | 1.51.5–7.0 |
| `blocked_event` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `upgradeneeded_event` | 23 | 12 | 10 | 10 | 15 | 8 | 4.4 | 25 | 22 | 14 | 8 | 1.5 |
| `worker_support` | 23 | 12 | 37 | 10 | 15 | 10 | 4.4 | 25 | 37 | 14 | 10 | 1.5 |


See also
--------


* [Using IndexedDB](indexeddb_api/using_indexeddb)
* Starting transactions: [`IDBDatabase`](idbdatabase)
* Using transactions: [`IDBTransaction`](idbtransaction)
* Setting a range of keys: [`IDBKeyRange`](idbkeyrange)
* Retrieving and making changes to your data: [`IDBObjectStore`](idbobjectstore)
* Using cursors: [`IDBCursor`](idbcursor)
* Reference example: [To-do Notifications](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) ([View the example live](https://mdn.github.io/dom-examples/to-do-notifications/)).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/IDBOpenDBRequest>

IdentityCredential
==================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `IdentityCredential` interface of the [Federated Credential Management API (FedCM)](fedcm_api) represents a user identity credential arising from a successful federated sign-in.


 Credential IdentityCredential

Instance properties
-------------------



*Inherits properties from its ancestor, [`Credential`](credential).*

  
[`IdentityCredential.token`](identitycredential/token)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with the [`Credential`](credential) instance that matches the provided parameters.

  

Examples
--------



Relying parties (RPs) can call `navigator.credentials.get()` with the `identity` option to make a request for users to sign in to the RP via an identity provider (IdP), using identity federation. A typical request would look like this:

 
```
async function signIn() {
  const identityCredential = await navigator.credentials.get({
    identity: {
      providers: [
        {
          configURL: "https://accounts.idp.example/config.json",
          clientId: "\*\*\*\*\*\*\*\*",
          nonce: "\*\*\*\*\*\*",
        },
      ],
    },
  });
}

```
 A successful [`navigator.credentials.get()`](credentialscontainer/get) call that includes an `identity` option fulfills with an `IdentityCredential` instance.

 Check out [Federated Credential Management API (FedCM)](fedcm_api) for more details on how this works. This call will start off the sign-in flow described in [FedCM sign-in flow](fedcm_api#fedcm_sign-in_flow).



Specifications
--------------




| Specification |
| --- |
| [Federated Credential Management API # browser-api-identity-credential-interface](https://fedidcg.github.io/FedCM/#browser-api-identity-credential-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `IdentityCredential` | 108 | 108 | No | No | 94 | No | 108 | 108 | No | 73 | No | No |
| `token` | 108 | 108 | No | No | 94 | No | 108 | 108 | No | 73 | No | No |


See also
--------


* [Federated Credential Management API](https://developer.chrome.com/docs/privacy-sandbox/fedcm/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/IdentityCredential>

IdleDeadline
============



The `IdleDeadline` interface is used as the data type of the input parameter to idle callbacks established by calling [`Window.requestIdleCallback()`](window/requestidlecallback). It offers a method, [`timeRemaining()`](idledeadline/timeremaining), which lets you determine how much longer the user agent estimates it will remain idle and a property, [`didTimeout`](idledeadline/didtimeout), which lets you determine if your callback is executing because its timeout duration expired.

 To learn more about how request callbacks work, see [Collaborative Scheduling of Background Tasks](background_tasks_api).



Instance properties
-------------------


 
[`IdleDeadline.didTimeout`](idledeadline/didtimeout) Read only 
  A Boolean whose value is `true` if the callback is being executed because the timeout specified when the idle callback was installed has expired.

  
Instance methods
----------------


 [`IdleDeadline.timeRemaining()`](idledeadline/timeremaining)  Returns a [`DOMHighResTimeStamp`](domhighrestimestamp), which is a floating-point value providing an estimate of the number of milliseconds remaining in the current idle period. If the idle period is over, the value is 0. Your callback can call this repeatedly to see if there's enough time left to do more work before returning.

  
Example
-------


See our [complete example](background_tasks_api#example) in the article [Cooperative Scheduling of Background Tasks API](background_tasks_api).


Specifications
--------------




| Specification |
| --- |
| [requestIdleCallback() Cooperative Scheduling of Background Tasks # the-idledeadline-interface](https://w3c.github.io/requestidlecallback/#the-idledeadline-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `IdleDeadline` | 47 | 79 | 55 | No | 34 | No | 47 | 47 | 55 | 34 | No | 5.0 |
| `didTimeout` | 47 | 79 | 55 | No | 34 | No | 47 | 47 | 55 | 34 | No | 5.0 |
| `timeRemaining` | 47 | 79 | 55 | No | 34 | No | 47 | 47 | 55 | 34 | No | 5.0 |


See also
--------


* [Cooperative Scheduling of Background Tasks API](background_tasks_api)
* [`Window.requestIdleCallback()`](window/requestidlecallback)
* [`Window.cancelIdleCallback()`](window/cancelidlecallback)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/IdleDeadline>

ImageBitmapRenderingContext
===========================



The `ImageBitmapRenderingContext` interface is a canvas rendering context that provides the functionality to replace the canvas's contents with the given [`ImageBitmap`](imagebitmap). Its context id (the first argument to [`HTMLCanvasElement.getContext()`](htmlcanvaselement/getcontext) or [`OffscreenCanvas.getContext()`](offscreencanvas/getcontext)) is `"bitmaprenderer"`.

 This interface is available in both the window and the [worker](web_workers_api) context.



Instance methods
----------------


 [`ImageBitmapRenderingContext.transferFromImageBitmap()`](imagebitmaprenderingcontext/transferfromimagebitmap)  Displays the given `ImageBitmap` in the canvas associated with this rendering context. Ownership of the `ImageBitmap` is transferred to the canvas. This was previously named `transferImageBitmap()`, but was renamed in a spec change. The old name is being kept as an alias to avoid code breakage.

  
Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-imagebitmaprenderingcontext-interface](https://html.spec.whatwg.org/multipage/canvas.html#the-imagebitmaprenderingcontext-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ImageBitmapRenderingContext` | 66 | 79 | 46 | No | 53 | 15 | 66 | 66 | 46 | 47 | 15 | 9.0 |
| `canvas` | 66 | 79 | 97 | No | 53 | 15 | 66 | 66 | 97 | 47 | 15 | 9.0 |
| `transferFromImageBitmap` | 66 | 79 | 5046–52 | No | 53 | 15 | 66 | 66 | 5046–52 | 47 | 15 | 9.0 |


See also
--------


* [`OffscreenCanvas`](offscreencanvas)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmapRenderingContext>

ImageData
=========



The `ImageData` interface represents the underlying pixel data of an area of a [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element.

 It is created using the [`ImageData()`](imagedata/imagedata) constructor or creator methods on the [`CanvasRenderingContext2D`](canvasrenderingcontext2d) object associated with a canvas: [`createImageData()`](canvasrenderingcontext2d/createimagedata) and [`getImageData()`](canvasrenderingcontext2d/getimagedata). It can also be used to set a part of the canvas by using [`putImageData()`](canvasrenderingcontext2d/putimagedata).


 **Note:** This feature is available in [Web Workers](web_workers_api)

 

Constructors
------------


 [`ImageData()`](imagedata/imagedata)  Creates an `ImageData` object from a given [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) and the size of the image it contains. If no array is given, it creates an image of a transparent black rectangle. Note that this is the most common way to create such an object in workers as [`createImageData()`](canvasrenderingcontext2d/createimagedata) is not available there.

  
Instance properties
-------------------


 
[`ImageData.data`](imagedata/data) Read only 
  A [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) representing a one-dimensional array containing the data in the RGBA order, with integer values between `0` and `255` (inclusive). The order goes by rows from the top-left pixel to the bottom-right.

  
[`ImageData.colorSpace`](imagedata/colorspace) Read only 
  A string indicating the color space of the image data.

  
[`ImageData.height`](imagedata/height) Read only 
  An `unsigned long` representing the actual height, in pixels, of the `ImageData`.

  
[`ImageData.width`](imagedata/width) Read only 
  An `unsigned long` representing the actual width, in pixels, of the `ImageData`.

  
Specifications
--------------




| Specification |
| --- |
| [HTML Standard # imagedata](https://html.spec.whatwg.org/multipage/canvas.html#imagedata) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ImageData` | 36 | 14 | 29 | No | 23 | 8 | 37 | 36 | 29 | 24 | 8 | 3.0 |
| `ImageData` | 1 | 12 | 3.5 | 9 | 9 | 3.1 | ≤37 | 18 | 4 | 10.1 | 2 | 1.0 |
| `colorSpace` | 92 | 92 | No | No | 78 | 15.2 | 92 | 92 | No | 65 | 15.2 | 16.0 |
| `data` | 1 | 12 | 3.5 | 9 | 9 | 3.1 | ≤37 | 18 | 4 | 10.1 | 2 | 1.0 |
| `height` | 1 | 12 | 3.5 | 9 | 9 | 3.1 | ≤37 | 18 | 4 | 10.1 | 2 | 1.0 |
| `width` | 1 | 12 | 3.5 | 9 | 9 | 3.1 | ≤37 | 18 | 4 | 10.1 | 2 | 1.0 |
| `worker_support` | 36 | 14 | 25 | No | 23 | 7 | 37 | 36 | 25 | 24 | 7 | 3.0 |


See also
--------


* [`CanvasRenderingContext2D`](canvasrenderingcontext2d)
* The [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element and its associated interface, [`HTMLCanvasElement`](htmlcanvaselement).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ImageData>

ImageDecoder
============



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `ImageDecoder` interface of the [WebCodecs API](webcodecs_api) provides a way to unpack and decode encoded image data.



Constructor
-----------


 
[`ImageDecoder()`](imagedecoder/imagedecoder)  Experimental 
  Creates a new `ImageDecoder` object.

  
Instance properties
-------------------


 
[`ImageDecoder.complete`](imagedecoder/complete) Read only   Experimental 
  Returns a boolean value indicating whether encoded data is completely buffered.

  
[`ImageDecoder.completed`](imagedecoder/completed) Read only   Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves once `complete` is true.

  
[`ImageDecoder.tracks`](imagedecoder/tracks) Read only   Experimental 
  Returns an [`ImageTrackList`](imagetracklist) object listing the available tracks and providing a method for selecting a track to decode.

  
[`ImageDecoder.type`](imagedecoder/type) Read only   Experimental 
  Returns a string reflecting the [MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) configured during construction.

  
Static methods
--------------


 
[`ImageDecoder.isTypeSupported()`](imagedecoder/istypesupported)  Experimental 
  Indicates if the provided [MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) is supported for unpacking and decoding.

  
Instance methods
----------------


 
[`ImageDecoder.close()`](imagedecoder/close)  Experimental 
  Ends all pending work and releases system resources.

  
[`ImageDecoder.decode()`](imagedecoder/decode)  Experimental 
  Enqueues a control message to decode the frame of an image.

  
[`ImageDecoder.reset()`](imagedecoder/reset)  Experimental 
  Aborts all pending `decode()` operations.

  
Examples
--------



Given a [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element:

 
```
<canvas></canvas>

```
 the following code decodes and renders an animated image to that canvas:

 
```
let imageDecoder = null;
let imageIndex = 0;

function renderImage(result) {
  const canvas = document.querySelector("canvas");
  const canvasContext = canvas.getContext("2d");

  canvasContext.drawImage(result.image, 0, 0);

  const track = imageDecoder.tracks.selectedTrack;

  // We check complete here since `frameCount` won't be stable until all
  // data has been received. This may cause us to receive a RangeError
  // during the decode() call below which needs to be handled.
  if (imageDecoder.complete) {
    if (track.frameCount === 1) return;

    if (imageIndex + 1 >= track.frameCount) imageIndex = 0;
  }

  // Decode the next frame ahead of display so it's ready in time.
  imageDecoder
    .decode({ frameIndex: ++imageIndex })
    .then((nextResult) =>
      setTimeout(() => {
        renderImage(nextResult);
      }, result.image.duration / 1000.0)
    )
    .catch((e) => {
      // We can end up requesting an imageIndex past the end since
      // we're using a ReadableStream from fetch(), when this happens
      // just wrap around.
      if (e instanceof RangeError) {
        imageIndex = 0;
        imageDecoder.decode({ frameIndex: imageIndex }).then(renderImage);
      } else {
        throw e;
      }
    });
}

function decodeImage(imageByteStream) {
  imageDecoder = new ImageDecoder({ data: imageByteStream, type: "image/gif" });
  imageDecoder.decode({ frameIndex: imageIndex }).then(renderImage);
}

fetch("fancy.gif").then((response) => decodeImage(response.body));

```


Specifications
--------------




| Specification |
| --- |
| [WebCodecs # imagedecoder-interface](https://w3c.github.io/webcodecs/#imagedecoder-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ImageDecoder` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `ImageDecoder` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `close` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `complete` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `completed` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `decode` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `isTypeSupported` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `reset` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `tracks` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `type` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ImageDecoder>

ImageTrack
==========



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `ImageTrack` interface of the [WebCodecs API](webcodecs_api) represents an individual image track.



Instance properties
-------------------


 
[`ImageTrack.animated`](imagetrack/animated) Read only   Experimental 
  Returns a [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean) indicating whether the track is animated and therefore has multiple frames.

  
[`ImageTrack.frameCount`](imagetrack/framecount) Read only   Experimental 
  Returns an integer indicating the number of frames in the track.

  
[`ImageTrack.repetitionCount`](imagetrack/repetitioncount) Read only   Experimental 
  Returns an integer indicating the number of times that the animation repeats.

  
[`ImageTrack.selected`](imagetrack/selected) Read only   Experimental 
  Returns a [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean) indicating whether the track is selected for decoding.

  
Specifications
--------------




| Specification |
| --- |
| [WebCodecs # imagetrack-interface](https://w3c.github.io/webcodecs/#imagetrack-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ImageTrack` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `animated` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `frameCount` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `repetitionCount` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `selected` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ImageTrack>

IdleDetector
============



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `IdleDetector` interface of the [Idle Detection API](idle_detection_api) provides methods and events for detecting user activity on a device or screen.

 This interface requires a secure context.


 EventTarget IdleDetector

Constructor
-----------


 
[`IdleDetector()`](idledetector/idledetector)  Experimental 
  Creates a new `IdleDetector` object.

  
Instance properties
-------------------


 
[`IdleDetector.userState`](idledetector/userstate) Read only   Experimental 
  Returns a string indicating whether the users has interacted with either the screen or the device within the threshold provided to `start()`, one of `"active"` or `"idle"`. This attribute returns `null` before `start()` is called.

  
[`IdleDetector.screenState`](idledetector/screenstate) Read only   Experimental 
  Returns a string indicating whether the screen is locked, one of `"locked"` or `"unlocked"`. This attribute returns `null` before `start()` is called.

  
Events
------


 
[`change`](idledetector/change_event)  Experimental 
  Called when the value of `userState` or `screenState` has changed.

  
Instance methods
----------------


 
[`IdleDetector.requestPermission()`](idledetector/requestpermission)  Experimental 
   Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves when the user has chosen whether to grant the origin access to their idle state. Resolves with `"granted"` on acceptance and `"denied"` on refusal. 

  
[`IdleDetector.start()`](idledetector/start)  Experimental 
   Returns a `Promise` that resolves when the detector starts listening for changes in the user's idle state. `userState` and `screenState` are given initial values. This method takes an optional `options` object with the `threshold` in milliseconds where inactivity should be reported and `signal` for an `AbortSignal` to abort the idle detector. 

  
Examples
--------



 The following example shows creating a detector and logging changes to the user's idle state. A button is used to get the necessary user activation before requesting permission. 

 
```
const controller = new AbortController();
const signal = controller.signal;

startButton.addEventListener("click", async () => {
  if ((await IdleDetector.requestPermission()) !== "granted") {
    console.error("Idle detection permission denied.");
    return;
  }

  try {
    const idleDetector = new IdleDetector();
    idleDetector.addEventListener("change", () => {
      const userState = idleDetector.userState;
      const screenState = idleDetector.screenState;
      console.log(`Idle change: ${userState}, ${screenState}.`);
    });

    await idleDetector.start({
      threshold: 60\_000,
      signal,
    });
    console.log("IdleDetector is active.");
  } catch (err) {
    // Deal with initialization errors like permission denied,
    // running outside of top-level frame, etc.
    console.error(err.name, err.message);
  }
});

stopButton.addEventListener("click", () => {
  controller.abort();
  console.log("IdleDetector is stopped.");
});

```


Specifications
--------------




| Specification |
| --- |
| [Idle Detection API # api-idledetector](https://wicg.github.io/idle-detection/#api-idledetector) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `IdleDetector` | 94 | 94–96 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `IdleDetector` | 94 | 94–96 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `change_event` | 94 | 94–96 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `requestPermission` | 94 | 94–96 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `screenState` | 94 | 94–96 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `start` | 94 | 94–96 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `userState` | 94 | 94–96 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/IdleDetector>

IIRFilterNode
=============



The `IIRFilterNode` interface of the [Web Audio API](web_audio_api) is a [`AudioNode`](audionode) processor which implements a general **[infinite impulse response](https://en.wikipedia.org/wiki/Infinite_impulse_response)** (IIR) filter; this type of filter can be used to implement tone control devices and graphic equalizers as well. It lets the parameters of the filter response be specified, so that it can be tuned as needed.


 EventTarget AudioNode IIRFilterNode 

|  |  |
| --- | --- |
| Number of inputs | `1` |
| Number of outputs | `1` |
| Channel count mode | `"max"` |
| Channel count | Same as on the input |
| Channel interpretation | `"speakers"` |

 Typically, it's best to use the [`BiquadFilterNode`](biquadfilternode) interface to implement higher-order filters. There are several reasons why:

 * Biquad filters are typically less sensitive to numeric quirks.
* The filter parameters of biquad filters can be automated.
* All even-ordered IIR filters can be created using [`BiquadFilterNode`](biquadfilternode).

 However, if you need to create an odd-ordered IIR filter, you'll need to use `IIRFilterNode`. You may also find this interface useful if you don't need automation, or for other reasons.

  **Note:** Once the node has been created, you can't change its coefficients.

  `IIRFilterNode`s have a tail-time reference; they continue to output non-silent audio with zero input. As an IIR filter, the non-zero input continues forever, but this can be limited after some finite time in practice, when the output has approached zero closely enough. The actual time that takes depends on the filter coefficients provided.



Constructor
-----------


 [`IIRFilterNode()`](iirfilternode/iirfilternode)  Creates a new instance of an IIRFilterNode object.

  
Instance properties
-------------------


*This interface has no properties of its own; however, it inherits properties from its parent, [`AudioNode`](audionode)*.


Instance methods
----------------



*Inherits methods from its parent, [`AudioNode`](audionode). It also has the following additional methods:*

  [`getFrequencyResponse()`](iirfilternode/getfrequencyresponse)  Uses the filter's current parameter settings to calculate the response for frequencies specified in the provided array of frequencies.

  

Examples
--------



You can find a simple IIR filter demo live [on Codepen](https://codepen.io/Rumyra/pen/oPxvYB/). Also see the [source code on GitHub](https://github.com/mdn/webaudio-examples/tree/master/iirfilter-node). It includes some different coefficient values for different lowpass frequencies — you can change the value of the `filterNumber` constant to a value between 0 and 3 to check out the different available effects.

 Also see our [Using IIR filters](web_audio_api/using_iir_filters) guide for a full explanation.



Specifications
--------------




| Specification |
| --- |
| [Web Audio API # IIRFilterNode](https://webaudio.github.io/web-audio-api/#IIRFilterNode) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `IIRFilterNode` | 55 | 79 | 53 | No | 42 | 14.1 | 55 | 55 | 53 | 42 | 14.5 | 6.0 |
| `IIRFilterNode` | 49 | 14 | 50 | No | 36 | 14.1 | 49 | 49 | 50 | 36 | 14.5 | 5.0 |
| `getFrequencyResponse` | 49 | 14 | 50 | No | 36 | 14.1 | 49 | 49 | 50 | 36 | 14.5 | 5.0 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)
* [`AudioNode`](audionode)
* [`BiquadFilterNode`](biquadfilternode)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/IIRFilterNode>

ImageBitmap
===========



The `ImageBitmap` interface represents a bitmap image which can be drawn to a [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) without undue latency. It can be created from a variety of source objects using the [`createImageBitmap()`](createimagebitmap) factory method. `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare textures for rendering in WebGL.

 `ImageBitmap` is a [transferable object](web_workers_api/transferable_objects).



Instance properties
-------------------


 
[`ImageBitmap.height`](imagebitmap/height) Read only 
  An `unsigned long` representing the height, in CSS pixels, of the `ImageData`.

  
[`ImageBitmap.width`](imagebitmap/width) Read only 
  An `unsigned long` representing the width, in CSS pixels, of the `ImageData`.

  
Instance methods
----------------


 [`ImageBitmap.close()`](imagebitmap/close)  Disposes of all graphical resources associated with an `ImageBitmap`.

  
Specifications
--------------




| Specification |
| --- |
| [HTML Standard # imagebitmap](https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#imagebitmap) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ImageBitmap` | 50 | 79 | 42 | No | 37 | 15 | 50 | 50 | 42 | 37 | 15 | 5.0 |
| `close` | 52 | 79 | 46 | No | 37 | 15 | 52 | 52 | 46 | 37 | 15 | 6.0 |
| `height` | 50 | 79 | 42 | No | 37 | 15 | 50 | 50 | 42 | 37 | 15 | 5.0 |
| `width` | 50 | 79 | 42 | No | 37 | 15 | 50 | 50 | 42 | 37 | 15 | 5.0 |


See also
--------


* [`createImageBitmap()`](createimagebitmap)
* [`CanvasRenderingContext2D.drawImage()`](canvasrenderingcontext2d/drawimage)
* [`WebGLRenderingContext.texImage2D()`](webglrenderingcontext/teximage2d)
* [`OffscreenCanvas.transferToImageBitmap()`](offscreencanvas/transfertoimagebitmap)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap>

ImageCapture
============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `ImageCapture` interface of the [MediaStream Image Capture API](mediastream_image_capture_api) provides methods to enable the capture of images or photos from a camera or other photographic device. It provides an interface for capturing images from a photographic device referenced through a valid [`MediaStreamTrack`](mediastreamtrack).



Constructor
-----------


 
[`ImageCapture()`](imagecapture/imagecapture)  Experimental 
  Creates a new `ImageCapture` object which can be used to capture still frames (photos) from a given [`MediaStreamTrack`](mediastreamtrack) which represents a video stream.

  
Instance properties
-------------------


 
[`ImageCapture.track`](imagecapture/track) Read only   Experimental 
  Returns a reference to the [`MediaStreamTrack`](mediastreamtrack) passed to the constructor.

  
Instance methods
----------------



The `ImageCapture` interface is based on [`EventTarget`](eventtarget), so it includes the methods defined by that interface as well as the ones listed below.

  
[`ImageCapture.takePhoto()`](imagecapture/takephoto)  Experimental 
  Takes a single exposure using the video capture device sourcing a [`MediaStreamTrack`](mediastreamtrack) and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with a [`Blob`](blob) containing the data.

  
[`ImageCapture.getPhotoCapabilities()`](imagecapture/getphotocapabilities)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with a [`PhotoCapabilities`](imagecapture/getphotocapabilities) object containing the ranges of available configuration options.

  
[`ImageCapture.getPhotoSettings()`](imagecapture/getphotosettings)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with a `PhotoSettings` object containing the current photo configuration settings.

  
[`ImageCapture.grabFrame()`](imagecapture/grabframe)  Experimental 
  Takes a snapshot of the live video in a [`MediaStreamTrack`](mediastreamtrack), returning an [`ImageBitmap`](imagebitmap), if successful.

  

Example
-------



The following code is taken from [Chrome's Grab Frame - Take Photo Sample](https://googlechrome.github.io/samples/image-capture/grab-frame-take-photo.html). Since `ImageCapture` requires some place to capture an image from, the example below starts with a device's media device (in other words a camera).

 This example shows, roughly, a [`MediaStreamTrack`](mediastreamtrack) extracted from a device's [`MediaStream`](mediastream). The track is then used to create an `ImageCapture` object so that `takePhoto()` and `grabFrame()` can be called. Finally, it shows how to apply the results of these calls to a canvas object.

 
```
let imageCapture;

function onGetUserMediaButtonClick() {
  navigator.mediaDevices
    .getUserMedia({ video: true })
    .then((mediaStream) => {
      document.querySelector("video").srcObject = mediaStream;

      const track = mediaStream.getVideoTracks()[0];
      imageCapture = new ImageCapture(track);
    })
    .catch((error) => console.error(error));
}

function onGrabFrameButtonClick() {
  imageCapture
    .grabFrame()
    .then((imageBitmap) => {
      const canvas = document.querySelector("#grabFrameCanvas");
      drawCanvas(canvas, imageBitmap);
    })
    .catch((error) => console.error(error));
}

function onTakePhotoButtonClick() {
  imageCapture
    .takePhoto()
    .then((blob) => createImageBitmap(blob))
    .then((imageBitmap) => {
      const canvas = document.querySelector("#takePhotoCanvas");
      drawCanvas(canvas, imageBitmap);
    })
    .catch((error) => console.error(error));
}

/\* Utils \*/

function drawCanvas(canvas, img) {
  canvas.width = getComputedStyle(canvas).width.split("px")[0];
  canvas.height = getComputedStyle(canvas).height.split("px")[0];
  let ratio = Math.min(canvas.width / img.width, canvas.height / img.height);
  let x = (canvas.width - img.width \* ratio) / 2;
  let y = (canvas.height - img.height \* ratio) / 2;
  canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height);
  canvas
    .getContext("2d")
    .drawImage(
      img,
      0,
      0,
      img.width,
      img.height,
      x,
      y,
      img.width \* ratio,
      img.height \* ratio
    );
}

document.querySelector("video").addEventListener("play", () => {
  document.querySelector("#grabFrameButton").disabled = false;
  document.querySelector("#takePhotoButton").disabled = false;
});

```


Specifications
--------------




| Specification |
| --- |
| [MediaStream Image Capture # imagecaptureapi](https://w3c.github.io/mediacapture-image/#imagecaptureapi) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ImageCapture` | 59 | 79 | NoSee [bug 888177](https://bugzil.la/888177). | No | 46 | No | 59 | 59 | NoSee [bug 888177](https://bugzil.la/888177). | 43 | No | 7.0 |
| `ImageCapture` | 59 | 79 | NoSee [bug 888177](https://bugzil.la/888177). | No | 46 | No | 59 | 59 | NoSee [bug 888177](https://bugzil.la/888177). | 43 | No | 7.0 |
| `getPhotoCapabilities` | 59 | 79 | NoSee [bug 888177](https://bugzil.la/888177). | No | 46 | No | 59 | 59 | NoSee [bug 888177](https://bugzil.la/888177). | 43 | No | 7.0 |
| `getPhotoSettings` | 61 | 79 | NoSee [bug 888177](https://bugzil.la/888177). | No | 46 | No | 61 | 61 | NoSee [bug 888177](https://bugzil.la/888177). | 43 | No | 8.0 |
| `grabFrame` | 59 | 79 | NoSee [bug 888177](https://bugzil.la/888177). | No | 46 | No | 59 | 59 | NoSee [bug 888177](https://bugzil.la/888177). | 43 | No | 7.0 |
| `takePhoto` | 6059–60`photoSettings` parameter not supported. | 79 | NoSee [bug 888177](https://bugzil.la/888177). | No | 4746–47`photoSettings` parameter not supported. | No | 6059–60`photoSettings` parameter not supported. | 6059–60`photoSettings` parameter not supported. | NoSee [bug 888177](https://bugzil.la/888177). | 4443–44`photoSettings` parameter not supported. | No | 8.07.0–8.0`photoSettings` parameter not supported. |
| `track` | 59 | 79 | NoSee [bug 888177](https://bugzil.la/888177). | No | 46 | No | 59 | 59 | NoSee [bug 888177](https://bugzil.la/888177). | 43 | No | 7.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ImageCapture>

Ink
===



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `Ink` interface of the [Ink API](ink_api) provides access to [`InkPresenter`](inkpresenter) objects for the application to use to render ink strokes.



Instance methods
----------------


 
[`requestPresenter()`](ink/requestpresenter)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that fulfills with an [`InkPresenter`](inkpresenter) object to handle rendering strokes.

  
Example
-------



```
async function inkInit() {
  const ink = navigator.ink;
  let presenter = await ink.requestPresenter({ presentationArea: canvas });

  //...
}

```

Specifications
--------------




| Specification |
| --- |
| [Ink API # ink-interface](https://wicg.github.io/ink-enhancement/#ink-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Ink` | 94 | 93 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `requestPresenter` | 94 | 93 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |


See also
--------


* [Enhancing Inking on the Web](https://blogs.windows.com/msedgedev/2021/08/18/enhancing-inking-on-the-web/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Ink>

InputDeviceCapabilities
=======================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `InputDeviceCapabilities` interface of the [Input Device Capabilities API](inputdevicecapabilities_api) provides information about the physical device or a group of related devices responsible for generating input events. Events caused by the same physical input device get the same instance of this object, but the converse isn't true. For example, two mice with the same capabilities in a system may appear as a single `InputDeviceCapabilities` instance.

 In some instances, `InputDeviceCapabilities` represents the capabilities of logical devices rather than physical devices. This allows, for example, touchscreen keyboards and physical keyboards to be represented the same way when they produce the same input.



Constructors
------------


 
[`InputDeviceCapabilities()`](inputdevicecapabilities/inputdevicecapabilities)  Experimental 
  Creates an `InputDeviceCapabilities` object.

  
Instance properties
-------------------


 
[`InputDeviceCapabilities.firesTouchEvents`](inputdevicecapabilities/firestouchevents) Read only   Experimental 
  A [`Boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean) that indicates whether the device dispatches touch events.

  
Instance methods
----------------


None.


Specifications
--------------




| Specification |
| --- |
| [Input Device Capabilities # dom-inputdevicecapabilities](https://wicg.github.io/input-device-capabilities/#dom-inputdevicecapabilities) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `InputDeviceCapabilities` | 47 | 79 | No | No | 34 | No | 47 | 47 | No | 34 | No | 5.0 |
| `InputDeviceCapabilities` | 47 | 79 | No | No | 34 | No | 47 | 47 | No | 34 | No | 5.0 |
| `firesTouchEvents` | 47 | 79 | No | No | 34 | No | 47 | 47 | No | 34 | No | 5.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/InputDeviceCapabilities>

InputDeviceInfo
===============



The `InputDeviceInfo` interface of the [Media Capture and Streams API](media_capture_and_streams_api) gives access to the capabilities of the input device that it represents.

 `InputDeviceInfo` objects are returned by [`MediaDevices.enumerateDevices()`](mediadevices/enumeratedevices) if the returned device is an audio or video input device.


 MediaDeviceInfo InputDeviceInfo

Instance methods
----------------


 [`InputDeviceInfo.getCapabilities()`](inputdeviceinfo/getcapabilities)  Returns a `MediaTrackCapabilities` object describing the primary audio or video track of a device's `MediaStream`.

  
Examples
--------



The following example gets all media devices with [`MediaDevices.enumerateDevices()`](mediadevices/enumeratedevices). If any of the devices are input devices then `console.log(device)` will print an `InputDeviceInfo` object to the console.

 
```
navigator.mediaDevices.enumerateDevices().then((devices) => {
  devices.forEach((device) => {
    console.log(device); // an InputDeviceInfo object if the device is an input device, otherwise a MediaDeviceInfo object.
  });
});

```


Specifications
--------------




| Specification |
| --- |
| [Media Capture and Streams # dom-inputdeviceinfo](https://w3c.github.io/mediacapture-main/#dom-inputdeviceinfo) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `InputDeviceInfo` | 47 | 79 | 39 | No | 34 | 11 | 47 | 47 | 39 | 34 | 11 | 5.0 |
| `getCapabilities` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/InputDeviceInfo>

InputEvent
==========



The `InputEvent` interface represents an event notifying the user of editable content changes.


 Event UIEvent InputEvent

Constructor
-----------


 [`InputEvent()`](inputevent/inputevent)  Creates an `InputEvent` object.

  
Instance properties
-------------------



*This interface inherits properties from its parents, [`UIEvent`](uievent) and [`Event`](event).*

  
[`InputEvent.data`](inputevent/data) Read only 
  Returns a string with the inserted characters. This may be an empty string if the change doesn't insert text (such as when deleting characters, for example).

  
[`InputEvent.dataTransfer`](inputevent/datatransfer) Read only 
  Returns a [`DataTransfer`](datatransfer) object containing information about richtext or plaintext data being added to or removed from editable content.

  
[`InputEvent.inputType`](inputevent/inputtype) Read only 
  Returns the type of change for editable content such as, for example, inserting, deleting, or formatting text. See the property page for a complete list of input types.

  
[`InputEvent.isComposing`](inputevent/iscomposing) Read only 
  Returns a [`Boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean) value indicating if the event is fired after [`compositionstart`](element/compositionstart_event) and before [`compositionend`](element/compositionend_event).

  

Instance methods
----------------



*This interface inherits methods from its parents, [`UIEvent`](uievent) and [`Event`](event).*

  [`InputEvent.getTargetRanges()`](inputevent/gettargetranges)  Returns an array of static ranges that will be affected by a change to the DOM if the input event is not canceled.

  

Specifications
--------------




| Specification |
| --- |
| [Input Events Level 2 # interface-InputEvent](https://w3c.github.io/input-events/#interface-InputEvent) |
| [UI Events # interface-inputevent](https://w3c.github.io/uievents/#interface-inputevent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `InputEvent` | 60 | 79 | 31 | No | 47 | 10.1The `inputEventInit` parameter is not supported. See [bug 170416](https://webkit.org/b/170416). | 60 | 60 | 31 | 44 | 10.3The `inputEventInit` parameter is not supported. See [bug 170416](https://webkit.org/b/170416). | 8.0 |
| `InputEvent` | 60 | 79 | 31 | No | 47 | 10.1 | 60 | 60 | 31 | 44 | 10.3 | 8.0 |
| `data` | 60 | 79 | 67 | No | 47 | 10.1 | 60 | 60 | 67 | 44 | 10.3 | 8.0 |
| `dataTransfer` | 60 | 79 | 67 | No | 47 | 10.1 | 60 | 60 | 67 | 44 | 10.3 | 8.0 |
| `getTargetRanges` | 60 | 79 | 87 | No | 47 | 10.1 | 60 | 60 | 87 | 44 | 10.3 | 8.0 |
| `inputType` | 60 | 79 | 66 | No | 47 | 10.1 | 60 | 60 | 66 | 44 | 10.3 | 8.0 |
| `isComposing` | 60 | 79 | 31 | No | 47 | 16.4 | 60 | 60 | 31 | 44 | 16.4 | 8.0 |


See also
--------


* [`beforeinput` event](htmlelement/beforeinput_event)
* [`input` event](htmlelement/input_event)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/InputEvent>

ImageTrackList
==============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `ImageTrackList` interface of the [WebCodecs API](webcodecs_api) represents a list of image tracks.



Instance properties
-------------------


 
[`ImageTrackList.ready`](imagetracklist/ready) Read only   Experimental 
  Returns a [`promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves once the `ImageTrackList` has been populated with [`tracks`](imagetrack).

  
[`ImageTrackList.length`](imagetracklist/length) Read only   Experimental 
  Returns an integer indicating the length of the `ImageTrackList`.

  
[`ImageTrackList.selectedIndex`](imagetracklist/selectedindex) Read only   Experimental 
  Returns an integer indicating the index of the `selectedTrack`.

  
[`ImageTrackList.selectedTrack`](imagetracklist/selectedtrack) Read only   Experimental 
  Returns the selected [`ImageTrack`](imagetrack).

  
Specifications
--------------




| Specification |
| --- |
| [WebCodecs # imagetracklist-interface](https://w3c.github.io/webcodecs/#imagetracklist-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ImageTrackList` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `length` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `ready` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `selectedIndex` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `selectedTrack` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ImageTrackList>

InkPresenter
============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `InkPresenter` interface of the [Ink API](ink_api) provides the ability to instruct the OS-level compositor to render ink strokes between pointer event dispatches.



Instance properties
-------------------


 
[`expectedImprovement`](inkpresenter/expectedimprovement)  Experimental  Read only 
  Returns a value, in milliseconds, indicating the latency improvement that can be expected using this presenter.

  
[`presentationArea`](inkpresenter/presentationarea)  Experimental  Read only 
  Returns the [`Element`](element) inside which rendering of ink strokes is confined.

  
Instance methods
----------------


 
[`updateInkTrailStartPoint()`](inkpresenter/updateinktrailstartpoint)  Experimental 
  Passes the [`PointerEvent`](pointerevent) that was used as the last rendering point for the current frame, allowing the OS-level compositor to render a delegated ink trail ahead of the next pointer event being dispatched.

  
Example
-------



In this example, we draw a trail onto a 2D canvas. Near the start of the code, we call [`Ink.requestPresenter()`](ink/requestpresenter), passing it the canvas as the presentation area for it to take care of and storing the promise it returns in the `presenter` variable.

 Later on, in the `pointermove` event listener, the new position of the trailhead is drawn onto the canvas each time the event fires. In addition, the [`InkPresenter`](inkpresenter) object returned when the `presenter` promise fulfills has its [`updateInkTrailStartPoint()`](inkpresenter/updateinktrailstartpoint) method invoked; this is passed:

 * The last trusted pointer event representing the rendering point for the current frame.
* A `style` object containing color and diameter settings.

 The result is that a delegated ink trail is drawn ahead of the default browser rendering on the app's behalf, in the specified style, until the next time it receives a `pointermove` event.

 
```
const ctx = canvas.getContext("2d");
let presenter = navigator.ink.requestPresenter({ presentationArea: canvas });
let move_cnt = 0;
let style = { color: "rgba(0, 0, 255, 1)", diameter: 10 };

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() \* (max - min + 1)) + min;
}

canvas.addEventListener("pointermove", (evt) => {
  const pointSize = 10;
  ctx.fillStyle = "#000000";
  ctx.fillRect(evt.pageX, evt.pageY, pointSize, pointSize);
  if (move_cnt == 50) {
    let r = getRandomInt(0, 255);
    let g = getRandomInt(0, 255);
    let b = getRandomInt(0, 255);
    style = { color: "rgba(" + r + ", " + g + ", " + b + ", 1)", diameter: 10 };
    move_cnt = 0;
    document.getElementById("div").style.backgroundColor =
      "rgba(" + r + ", " + g + ", " + b + ", 1)";
  }
  move_cnt += 1;
  presenter.then(function (v) {
    v.updateInkTrailStartPoint(evt, style);
  });
});

window.addEventListener("pointerdown", (evt) => {
  evt.pointerId;
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
});

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

```
  **Note:** See this example running live — [Delegated ink trail](https://mabian-ms.github.io/delegated-ink-trail.html).

 

Specifications
--------------




| Specification |
| --- |
| [Ink API # ink-presenter](https://wicg.github.io/ink-enhancement/#ink-presenter) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `InkPresenter` | 94 | 93 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `expectedImprovement` | 94 | 93 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `presentationArea` | 94 | 93 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `updateInkTrailStartPoint` | 94 | 93 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |


See also
--------


* [Enhancing Inking on the Web](https://blogs.windows.com/msedgedev/2021/08/18/enhancing-inking-on-the-web/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/InkPresenter>

InstallEvent
============



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.


**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The parameter passed into the [`oninstall`](serviceworkerglobalscope/install_event) handler, the `InstallEvent` interface represents an install action that is dispatched on the [`ServiceWorkerGlobalScope`](serviceworkerglobalscope) of a [`ServiceWorker`](serviceworker). As a child of [`ExtendableEvent`](extendableevent), it ensures that functional events such as [`FetchEvent`](fetchevent) are not dispatched during installation.

 This interface inherits from the [`ExtendableEvent`](extendableevent) interface.



Constructor
-----------


 
[`InstallEvent()`](installevent/installevent)  Deprecated   Non-standard 
  Creates a new `InstallEvent` object.

  
Instance properties
-------------------



*Inherits properties from its ancestor, [`Event`](event)*.

  
[`InstallEvent.activeWorker`](installevent/activeworker) Read only   Deprecated   Non-standard 
  Returns the [`ServiceWorker`](serviceworker) that is currently controlling the page.

  

Instance methods
----------------


*Inherits methods from its parent, [`ExtendableEvent`](extendableevent)*.


Examples
--------



This code snippet is from the [service worker prefetch sample](https://github.com/GoogleChrome/samples/blob/gh-pages/service-worker/prefetch/service-worker.js) (see [prefetch running live](https://googlechrome.github.io/samples/service-worker/prefetch/).) The code calls [`ExtendableEvent.waitUntil()`](extendableevent/waituntil) in [`ServiceWorkerGlobalScope.oninstall`](serviceworkerglobalscope/install_event) and delays treating the [`ServiceWorkerRegistration.installing`](serviceworkerregistration/installing) worker as installed until the passed promise resolves successfully. The promise resolves when all resources have been fetched and cached, or when any exception occurs.

 The code snippet also shows a best practice for versioning caches used by the service worker. Although this example has only one cache, you can use this approach for multiple caches. The code maps a shorthand identifier for a cache to a specific, versioned cache name.

  **Note:** Logging statements are visible in Google Chrome via the "Inspect" interface for the relevant service worker accessed via chrome://serviceworker-internals.

  
```
const CACHE\_VERSION = 1;
const CURRENT\_CACHES = {
  prefetch: `prefetch-cache-v${CACHE\_VERSION}`,
};

self.addEventListener("install", (event) => {
  const urlsToPrefetch = [
    "./static/pre\_fetched.txt",
    "./static/pre\_fetched.html",
    "https://www.chromium.org/\_/rsrc/1302286216006/config/customLogo.gif",
  ];

  console.log(
    "Handling install event. Resources to pre-fetch:",
    urlsToPrefetch
  );

  event.waitUntil(
    caches
      .open(CURRENT\_CACHES["prefetch"])
      .then((cache) => {
        return cache
          .addAll(
            urlsToPrefetch.map((urlToPrefetch) => {
              return new Request(urlToPrefetch, { mode: "no-cors" });
            })
          )
          .then(() => {
            console.log("All resources have been fetched and cached.");
          });
      })
      .catch((error) => {
        console.error("Pre-fetching failed:", error);
      })
  );
});

```


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `InstallEvent` | 40 | 79 | 44 | No | 27 | No | 40 | 40 | 44 | 27 | No | 4.0 |
| `InstallEvent` | 40 | 17 | 44 | No | 27 | No | 40 | 40 | 44 | 27 | No | 4.0 |
| `activeWorker` | 40 | 17 | 44 | No | 27 | No | 40 | 40 | 44 | 27 | No | 4.0 |


See also
--------


* [`NotificationEvent`](notificationevent)
* [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
* [Fetch API](fetch_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/InstallEvent>

IntersectionObserver
====================



The `IntersectionObserver` interface of the [Intersection Observer API](intersection_observer_api) provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's [viewport](https://developer.mozilla.org/en-US/docs/Glossary/Viewport). The ancestor element or viewport is referred to as the root.

 When an `IntersectionObserver` is created, it's configured to watch for given ratios of visibility within the root. The configuration cannot be changed once the `IntersectionObserver` is created, so a given observer object is only useful for watching for specific changes in degree of visibility; however, you can watch multiple target elements with the same observer.



Constructor
-----------


 [`IntersectionObserver()`](intersectionobserver/intersectionobserver)  Creates a new `IntersectionObserver` object which will execute a specified callback function when it detects that a target element's visibility has crossed one or more thresholds.

  
Instance properties
-------------------


 
[`IntersectionObserver.root`](intersectionobserver/root) Read only 
  The [`Element`](element) or [`Document`](document) whose bounds are used as the bounding box when testing for intersection. If no `root` value was passed to the constructor or its value is `null`, the top-level document's viewport is used.

  
[`IntersectionObserver.rootMargin`](intersectionobserver/rootmargin) Read only 
  An offset rectangle applied to the root's [bounding box](https://developer.mozilla.org/en-US/docs/Glossary/Bounding_box) when calculating intersections, effectively shrinking or growing the root for calculation purposes. The value returned by this property may not be the same as the one specified when calling the constructor as it may be changed to match internal requirements. Each offset can be expressed in pixels (`px`) or as a percentage (`%`). The default is "0px 0px 0px 0px".

  
[`IntersectionObserver.thresholds`](intersectionobserver/thresholds) Read only 
  A list of thresholds, sorted in increasing numeric order, where each threshold is a ratio of intersection area to bounding box area of an observed target. Notifications for a target are generated when any of the thresholds are crossed for that target. If no value was passed to the constructor, 0 is used.

  
Instance methods
----------------


 [`IntersectionObserver.disconnect()`](intersectionobserver/disconnect)  Stops the `IntersectionObserver` object from observing any target.

  [`IntersectionObserver.observe()`](intersectionobserver/observe)  Tells the `IntersectionObserver` a target element to observe.

  [`IntersectionObserver.takeRecords()`](intersectionobserver/takerecords)  Returns an array of [`IntersectionObserverEntry`](intersectionobserverentry) objects for all observed targets.

  [`IntersectionObserver.unobserve()`](intersectionobserver/unobserve)  Tells the `IntersectionObserver` to stop observing a particular target element.

  
Examples
--------



```
const intersectionObserver = new IntersectionObserver((entries) => {
  // If intersectionRatio is 0, the target is out of view
  // and we do not need to do anything.
  if (entries[0].intersectionRatio <= 0) return;

  loadItems(10);
  console.log("Loaded new items");
});
// start observing
intersectionObserver.observe(document.querySelector(".scrollerFooter"));

```

Specifications
--------------




| Specification |
| --- |
| [Intersection Observer # intersection-observer-interface](https://w3c.github.io/IntersectionObserver/#intersection-observer-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `IntersectionObserver` | 51 | 15 | 55Before version 96, the constructor throws a `DOMException` if the `options.rootMargin` option is passed an empty string (see [bug 1738791](https://bugzil.la/1738791)). | No | 38 | 12.1 | 51 | 51 | 55 | 41 | 12.2 | 5.0 |
| `IntersectionObserver` | 51 | 15 | 55 | No | 38 | 12.1 | 51 | 51 | 55 | 41 | 12.2 | 5.0 |
| `disconnect` | 51 | 15Available since [Windows Insider Preview Build 14986](https://developer.microsoft.com/microsoft-edge/platform/status/intersectionobserver/). | 55 | No | 38 | 12.1 | 51 | 51 | 55 | 41 | 12.2 | 5.0 |
| `observe` | 51 | 15 | 55 | No | 38 | 12.1 | 51 | 51 | 55 | 41 | 12.2 | 5.0 |
| `root` | 51 | 15 | 55 | No | 38 | 12.1 | 51 | 51 | 55 | 41 | 12.2 | 5.0 |
| `rootMargin` | 51 | 15 | 55 | No | 38 | 12.1`rootMargin` does not work with `<iframe>`s. | 51 | 51 | 55 | 41 | 12.2`rootMargin` does not work with `<iframe>`s. | 5.0 |
| `takeRecords` | 51 | 15Available since [Windows Insider Preview Build 14986](https://developer.microsoft.com/microsoft-edge/platform/status/intersectionobserver/). | 55 | No | 38 | 12.1 | 51 | 51 | 55 | 41 | 12.2 | 5.0 |
| `thresholds` | 52 | 15 | 55 | No | 39 | 12.1 | 52 | 52 | 55 | 41 | 12.2 | 6.0 |
| `unobserve` | 51 | 15Available since [Windows Insider Preview Build 14986](https://developer.microsoft.com/microsoft-edge/platform/status/intersectionobserver/). | 55 | No | 38 | 12.1 | 51 | 51 | 55 | 41 | 12.2 | 5.0 |


See also
--------


* [`MutationObserver`](mutationobserver)
* [`PerformanceObserver`](performanceobserver)
* [`ResizeObserver`](resizeobserver)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver>

Keyboard
========



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.


**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `Keyboard` interface of the [Keyboard API](keyboard_api) provides functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard.

 A list of valid code values is found in the [UI Events KeyboardEvent code Values](https://www.w3.org/TR/uievents-code/#key-alphanumeric-writing-system) spec.


 EventTarget Keyboard

Instance properties
-------------------


None.


Instance methods
----------------


 
[`Keyboard.getLayoutMap()`](keyboard/getlayoutmap)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with an instance of [`KeyboardLayoutMap`](keyboardlayoutmap) which is a map-like object with functions for retrieving the strings associated with specific physical keys.

  
[`Keyboard.lock()`](keyboard/lock)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) after enabling the capture of keypresses for any or all of the keys on the physical keyboard.

  
[`Keyboard.unlock()`](keyboard/unlock)  Experimental 
  Unlocks all keys captured by the `lock()` method and returns synchronously.

  
Example
-------



The following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'W' key on an English QWERTY keyboard.

 
```
if (navigator.keyboard) {
  const keyboard = navigator.keyboard;
  keyboard.getLayoutMap().then((keyboardLayoutMap) => {
    const upKey = keyboardLayoutMap.get("KeyW");
    window.alert(`Press ${upKey} to move up.`);
  });
} else {
  // Do something else.
}

```


Specifications
--------------




| Specification |
| --- |
| [Keyboard Map # keyboard-interface](https://wicg.github.io/keyboard-map/#keyboard-interface) |
| [Keyboard Lock # keyboard-interface](https://wicg.github.io/keyboard-lock/#keyboard-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Keyboard` | 68 | 79 | No | No | 55 | No | 68 | 68 | No | 48 | No | 10.0 |
| `getLayoutMap` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `lock` | 68 | 79 | No | No | 55 | No | 68 | 68 | No | 48 | No | 10.0 |
| `unlock` | 68 | 79 | No | No | 55 | No | 68 | 68 | No | 48 | No | 10.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Keyboard>

KeyboardEvent
=============



`KeyboardEvent` objects describe a user interaction with the keyboard; each event describes a single interaction between the user and a key (or combination of a key with modifier keys) on the keyboard. The event type ([`keydown`](element/keydown_event), [`keypress`](element/keypress_event), or [`keyup`](element/keyup_event)) identifies what kind of keyboard activity occurred.

  **Note:** `KeyboardEvent` events just indicate what interaction the user had with a key on the keyboard at a low level, providing no contextual meaning to that interaction. When you need to handle text input, use the [`input`](htmlelement/input_event) event instead. Keyboard events may not be fired if the user is using an alternate means of entering text, such as a handwriting system on a tablet or graphics tablet.

 
 Event UIEvent KeyboardEvent

Constructor
-----------


 [`KeyboardEvent()`](keyboardevent/keyboardevent)  Creates a new `KeyboardEvent` object.

  
Constants
---------


The `KeyboardEvent` interface defines the following constants.


### Keyboard locations



The following constants identify which part of the keyboard the key event originates from. They are accessed as `KeyboardEvent.DOM_KEY_LOCATION_STANDARD` and so forth.

 

Keyboard location identifiers| Constant | Value | Description |
| --- | --- | --- |
| `DOM_KEY_LOCATION_STANDARD` | 0x00 |  The key described by the event is not identified as being located in a particular area of the keyboard; it is not located on the numeric keypad (unless it's the NumLock key), and for keys that are duplicated on the left and right sides of the keyboard, the key is, for whatever reason, not to be associated with that location.   Examples include alphanumeric keys on the standard PC 101 US keyboard, the NumLock key, and the space bar.  |
| `DOM_KEY_LOCATION_LEFT` | 0x01 |  The key is one which may exist in multiple locations on the keyboard and, in this instance, is on the left side of the keyboard.   Examples include the left Control key, the left Command key on a Macintosh keyboard, or the left Shift key.  |
| `DOM_KEY_LOCATION_RIGHT` | 0x02 |  The key is one which may exist in multiple positions on the keyboard and, in this case, is located on the right side of the keyboard.   Examples include the right Shift key and the right Alt key (Option on a Mac keyboard).  |
| `DOM_KEY_LOCATION_NUMPAD` | 0x03 |  The key is located on the numeric keypad, or is a virtual key associated with the numeric keypad if there's more than one place the key could originate from. The NumLock key does not fall into this group and is always encoded with the location `DOM_KEY_LOCATION_STANDARD`.   Examples include the digits on the numeric keypad, the keypad's Enter key, and the decimal point on the keypad.  |



Instance properties
-------------------



*This interface also inherits properties of its parents, [`UIEvent`](uievent) and [`Event`](event).*

  
[`KeyboardEvent.altKey`](keyboardevent/altkey) Read only 
  Returns a boolean value that is `true` if the `Alt` (`Option` or `⌥` on macOS) key was active when the key event was generated.

  
[`KeyboardEvent.code`](keyboardevent/code) Read only 
  Returns a string with the code value of the physical key represented by the event.

  **Warning:** This ignores the user's keyboard layout, so that if the user presses the key at the "Y" position in a QWERTY keyboard layout (near the middle of the row above the home row), this will always return "KeyY", even if the user has a QWERTZ keyboard (which would mean the user expects a "Z" and all the other properties would indicate a "Z") or a Dvorak keyboard layout (where the user would expect an "F"). If you want to display the correct keystrokes to the user, you can use [`Keyboard.getLayoutMap()`](keyboard/getlayoutmap).

   
[`KeyboardEvent.ctrlKey`](keyboardevent/ctrlkey) Read only 
  Returns a boolean value that is `true` if the `Ctrl` key was active when the key event was generated.

  
[`KeyboardEvent.isComposing`](keyboardevent/iscomposing) Read only 
  Returns a boolean value that is `true` if the event is fired between after `compositionstart` and before `compositionend`.

  
[`KeyboardEvent.key`](keyboardevent/key) Read only 
  Returns a string representing the key value of the key represented by the event.

  
`KeyboardEvent.locale` Read only 
  Returns a string representing a locale string indicating the locale the keyboard is configured for. This may be the empty string if the browser or device doesn't know the keyboard's locale.

  **Note:** This does not describe the locale of the data being entered. A user may be using one keyboard layout while typing text in a different language.

   
[`KeyboardEvent.location`](keyboardevent/location) Read only 
  Returns a number representing the location of the key on the keyboard or other input device. A list of the constants identifying the locations is shown above in [Keyboard locations](#keyboard_locations).

  
[`KeyboardEvent.metaKey`](keyboardevent/metakey) Read only 
  Returns a boolean value that is `true` if the `Meta` key (on Mac keyboards, the `⌘ Command` key; on Windows keyboards, the Windows key (`⊞`)) was active when the key event was generated.

  
[`KeyboardEvent.repeat`](keyboardevent/repeat) Read only 
  Returns a boolean value that is `true` if the key is being held down such that it is automatically repeating.

  
[`KeyboardEvent.shiftKey`](keyboardevent/shiftkey) Read only 
  Returns a boolean value that is `true` if the `Shift` key was active when the key event was generated.

  

Instance methods
----------------



*This interface also inherits methods of its parents, [`UIEvent`](uievent) and [`Event`](event).*

  [`KeyboardEvent.getModifierState()`](keyboardevent/getmodifierstate)  Returns a boolean value indicating if a modifier key such as `Alt`, `Shift`, `Ctrl`, or `Meta`, was pressed when the event was created.

  

Obsolete methods
----------------


 
[`KeyboardEvent.initKeyEvent()`](keyboardevent/initkeyevent)  Deprecated 
  Initializes a `KeyboardEvent` object. This was implemented only by Firefox, and is no longer supported even there; instead, you should use the [`KeyboardEvent()`](keyboardevent/keyboardevent) constructor.

  
[`KeyboardEvent.initKeyboardEvent()`](keyboardevent/initkeyboardevent)  Deprecated 
  Initializes a `KeyboardEvent` object. This is now deprecated. You should instead use the [`KeyboardEvent()`](keyboardevent/keyboardevent) constructor.

  
Obsolete properties
-------------------


 
`KeyboardEvent.char`  Non-standard   Deprecated  Read only 
  Returns a string representing the character value of the key. If the key corresponds to a printable character, this value is a non-empty Unicode string containing that character. If the key doesn't have a printable representation, this is an empty string.

  **Note:** If the key is used as a macro that inserts multiple characters, this property's value is the entire string, not just the first character.

   
[`KeyboardEvent.charCode`](keyboardevent/charcode)  Deprecated  Read only 
  Returns a number representing the Unicode reference number of the key; this property is used only by the `keypress` event. For keys whose `char` property contains multiple characters, this is the Unicode value of the first character in that property. In Firefox 26 this returns codes for printable characters.

  **Warning:** This property is deprecated; you should use [`KeyboardEvent.key`](keyboardevent/key) instead, if available.

   
[`KeyboardEvent.keyCode`](keyboardevent/keycode)  Deprecated  Read only 
  Returns a number representing a system and implementation dependent numerical code identifying the unmodified value of the pressed key.

  **Warning:** This property is deprecated; you should use [`KeyboardEvent.key`](keyboardevent/key) instead, if available.

   
[`KeyboardEvent.keyIdentifier`](keyboardevent/keyidentifier)  Non-standard   Deprecated  Read only 
  This property is non-standard and has been deprecated in favor of [`KeyboardEvent.key`](keyboardevent/key). It was part of an old version of DOM Level 3 Events.

  
`KeyboardEvent.keyLocation`  Non-standard   Deprecated  Read only 
  This is a non-standard deprecated alias for [`KeyboardEvent.location`](keyboardevent/location). It was part of an old version of DOM Level 3 Events.

  
[`KeyboardEvent.which`](uievent/which)  Deprecated  Read only 
  Returns a number representing a system and implementation dependent numeric code identifying the unmodified value of the pressed key; this is usually the same as `keyCode`.

  **Warning:** This property is deprecated; you should use [`KeyboardEvent.key`](keyboardevent/key) instead, if available.

   
Events
------



The following events are based on the `KeyboardEvent` type. In the list below, each event links to the documentation for the `Element` handler for the event, which applies generally to all of the recipients, including [`Element`](element), [`Document`](document), and [`Window`](window).

  [`keydown`](element/keydown_event)  A key has been pressed.

  [`keyup`](element/keyup_event)  A key has been released.

  

### Obsolete events


 
[`keypress`](element/keypress_event)  Deprecated 
  A key that normally produces a character value has been pressed. This event was highly device-dependent and is obsolete. You should not use it.

  
Usage notes
-----------



There are three types of keyboard events: [`keydown`](element/keydown_event), [`keypress`](element/keypress_event), and [`keyup`](element/keyup_event). For most keys, Gecko dispatches a sequence of key events like this:

 1. When the key is first pressed, the `keydown` event is sent.
2. If the key is not a modifier key, the `keypress` event is sent.
3. When the user releases the key, the `keyup` event is sent.



### Special cases



Some keys toggle the state of an indicator light; these include keys such as Caps Lock, Num Lock, and Scroll Lock. On Windows and Linux, these keys dispatch only the `keydown` and `keyup` events.

  **Note:** On Linux, Firefox 12 and earlier also dispatched the `keypress` event for these keys.

  However, a limitation of the macOS event model causes Caps Lock to dispatch only the `keydown` event. Num Lock was supported on some older laptop models (2007 models and older), but since then, macOS hasn't supported Num Lock even on external keyboards. On older MacBooks with a Num Lock key, that key doesn't generate any key events. Gecko does support the Scroll Lock key if an external keyboard which has an F14 key is connected. In certain older versions of Firefox, this key generated a `keypress` event; this inconsistent behavior was [Firefox bug 602812](https://bugzil.la/602812).



### Auto-repeat handling



When a key is pressed and held down, it begins to auto-repeat. This results in a sequence of events similar to the following being dispatched:

 1. `keydown`
2. `keypress`
3. `keydown`
4. `keypress`
5. <<repeating until the user releases the key>>
6. `keyup`

 This is what the DOM Level 3 specification says should happen. There are some caveats, however, as described below.

 #### Auto-repeat on some GTK environments such as Ubuntu 9.4

 In some GTK-based environments, auto-repeat dispatches a native key-up event automatically during auto-repeat, and there's no way for Gecko to know the difference between a repeated series of keypresses and an auto-repeat. On those platforms, then, an auto-repeat key will generate the following sequence of events:

 1. `keydown`
2. `keypress`
3. `keyup`
4. `keydown`
5. `keypress`
6. `keyup`
7. <<repeating until the user releases the key>>
8. `keyup`

 In these environments, unfortunately, there's no way for web content to tell the difference between auto-repeating keys and keys that are just being pressed repeatedly.



Example
-------



```
document.addEventListener(
  "keydown",
  (event) => {
    const keyName = event.key;

    if (keyName === "Control") {
      // do not alert when only Control key is pressed.
      return;
    }

    if (event.ctrlKey) {
      // Even though event.key is not 'Control' (e.g., 'a' is pressed),
      // event.ctrlKey may be true if Ctrl key is pressed at the same time.
      alert(`Combination of ctrlKey + ${keyName}`);
    } else {
      alert(`Key pressed ${keyName}`);
    }
  },
  false
);

document.addEventListener(
  "keyup",
  (event) => {
    const keyName = event.key;

    // As the user releases the Ctrl key, the key is no longer active,
    // so event.ctrlKey is false.
    if (keyName === "Control") {
      alert("Control key was released");
    }
  },
  false
);

```

Specifications
--------------




| Specification |
| --- |
| [UI Events # interface-keyboardevent](https://w3c.github.io/uievents/#interface-keyboardevent) |


The `KeyboardEvent` interface specification went through numerous draft versions, first under DOM Events Level 2 where it was dropped as no consensus arose, then under DOM Events Level 3. This led to the implementation of non-standard initialization methods, the early DOM Events Level 2 version, [`KeyboardEvent.initKeyEvent()`](keyboardevent/initkeyevent) by Gecko browsers and the early DOM Events Level 3 version, [`KeyboardEvent.initKeyboardEvent()`](keyboardevent/initkeyboardevent) by others. Both have been superseded by the modern usage of a constructor: [`KeyboardEvent()`](keyboardevent/keyboardevent).


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `KeyboardEvent` | 26 | 12 | 31 | No | 15 | 7 | 4.4 | 26 | 31 | 14 | 7 | 1.5 |
| `KeyboardEvent` | 1 | 12 | 1.5 | 9 | ≤12.1 | 1.2 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `altKey` | 1 | 12 | 1.5 | 9 | ≤12.1 | 1.2 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `charCode` | 1 | 12 | 1.5 | 9 | 12.1 | 1.2 | ≤37 | 18 | 4 | 12.1 | 1 | 1.0 |
| `code` | 48 | 79 | 38 | No | 35 | 10.1 | 48 | 48 | 38 | 35 | 10.3 | 5.0 |
| `ctrlKey` | 1 | 12 | 1.5 | 9 | ≤12.1 | 1.2 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `getModifierState` | 30 | 12 | 15 | 9 | 17 | 10.1 | 4.4 | 30 | 15 | 18 | 10.3 | 2.0 |
| `initKeyboardEvent` | 1 | 12 | 57 | 9 | ≤12.1 | 1.2 | ≤37 | 18 | 57 | ≤12.1 | 1 | 1.0 |
| `isComposing` | 56 | 79 | 31 | No | 43 | 10.1 | 56 | 56 | 31 | 43 | 10.3 | 6.0 |
| `key` | 51 | 12 | 23 | 9IE's implementation does not completely match the current spec because it is based on an older version of the spec. | 38 | 10.1 | 51 | 51 | 23 | 41 | 10.3 | 5.0 |
| `keyCode` | 1 | 12 | 1.5 | 9 | 12.1 | 1.2 | ≤37 | 18 | 4 | 12.1 | 1 | 1.0 |
| `keyIdentifier` | 26–54 | No | No | No | 15–41 | 1.2 | 4.4–54 | 26–54 | No | 14–41 | 1 | 1.5–6.0 |
| `location` | 30 | 12 | 15 | 9 | 17 | 8 | 4.4 | 30 | 15 | 18 | 8 | 2.0 |
| `metaKey` | 1 | 12 | 1.5Since Firefox 48, the Windows key is no longer treated as a `meta` key. | 9 | ≤12.1 | 1.2 | ≤37 | 18 | 4Since Firefox 48, the Windows key is no longer treated as a `meta` key. | ≤12.1 | 1 | 1.0 |
| `repeat` | 32 | 12 | 28 | 9 | 19 | 10.1 | 4.4.3 | 32 | 28 | 19 | 10.3 | 2.0 |
| `shiftKey` | 1 | 12 | 1.5 | 9 | ≤12.1 | 1.2 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |


### Compatibility notes


* As of Firefox 65, the `keypress` event is no longer fired for [non-printable keys](keyboardevent/keycode#non-printable_keys_(function_keys)) ([Firefox bug 968056](https://bugzil.la/968056)), except for the `Enter` key, and the `Shift` + `Enter` and `Ctrl` + `Enter` key combinations (these were kept for cross-browser compatibility purposes).

See also
--------


* [`KeyboardEvent.code`](keyboardevent/code).
* [`KeyboardEvent.key`](keyboardevent/key).
* [`KeyboardEvent.getModifierState()`](keyboardevent/getmodifierstate)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent>

KeyboardLayoutMap
=================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `KeyboardLayoutMap` interface of the [Keyboard API](keyboard_api) is a map-like object with functions for retrieving the string associated with specific physical keys.

 A list of valid keys is found in the [UI Events KeyboardEvent code Values](https://www.w3.org/TR/uievents-code/#key-alphanumeric-writing-system) specification.



Instance properties
-------------------


 
[`KeyboardLayoutMap.entries`](keyboardlayoutmap/entries) Read only   Experimental 
  Returns an array of a given object's own enumerable property `[key, value]` pairs, in the same order as that provided by a [`for...in`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loop (the difference being that a `for-in` loop enumerates properties in the prototype chain as well).

  
[`KeyboardLayoutMap.keys`](keyboardlayoutmap/keys) Read only   Experimental 
  Returns a new *array iterator* object that contains the keys for each index in the array.

  
[`KeyboardLayoutMap.size`](keyboardlayoutmap/size) Read only   Experimental 
  Returns the number of elements in the `KeyboardLayoutMap` object.

  
[`KeyboardLayoutMap.values`](keyboardlayoutmap/values) Read only   Experimental 
  Returns a new *array iterator* object that contains the values for each index in the `KeyboardLayoutMap` object.

  
Instance methods
----------------


 
[`KeyboardLayoutMap.forEach()`](keyboardlayoutmap/foreach) Read only   Experimental 
  Executes a provided function once for each element of `KeyboardLayoutMap`.

  
[`KeyboardLayoutMap.get()`](keyboardlayoutmap/get)  Experimental 
  Returns the element with the given key from the `KeyboardLayoutMap` object.

  
[`KeyboardLayoutMap.has()`](keyboardlayoutmap/has)  Experimental 
  Returns a boolean indicating whether the `KeyboardLayoutMap` object has an element with the specified key.

  
Examples
--------



The following example demonstrates how to get the location- or layout-specific string associated with the key that corresponds to the 'W' key on an English QWERTY keyboard.

 
```
const keyboard = navigator.keyboard;
keyboard.getLayoutMap().then((keyboardLayoutMap) => {
  const upKey = keyboardLayoutMap.get("KeyW");
  window.alert(`Press ${upKey} to move up.`);
});

```


Specifications
--------------




| Specification |
| --- |
| [Keyboard Map # keyboardlayoutmap-interface](https://wicg.github.io/keyboard-map/#keyboardlayoutmap-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@iterator` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `KeyboardLayoutMap` | 69 | 79 | No | No | 55 | No | 69 | 69 | No | 48 | No | 10.0 |
| `entries` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `forEach` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `get` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `has` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `keys` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `size` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `values` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/KeyboardLayoutMap>

LargestContentfulPaint
======================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `LargestContentfulPaint` interface provides timing information about the largest image or text paint before user input on a web page.



Description
-----------



The key moment this API provides is the [Largest Contentful Paint](https://developer.mozilla.org/en-US/docs/Glossary/Largest_contentful_paint) (LCP) metric. It provides the render time of the largest image or text block visible within the viewport, recorded from when the page first begins to load. The following elements are considered when determining the LCP:

 * [`<img>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img) elements.
* [`<image>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/image) elements inside an SVG.
* The poster images of [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) elements.
* Elements with a [`background-image`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-image).
* Groups of text nodes, such as [`<p>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p).

 To measure render times of other elements, use the [`PerformanceElementTiming`](performanceelementtiming) API.

 Additional key paint moments are provided by the [`PerformancePaintTiming`](performancepainttiming) API:

 * [First paint](https://developer.mozilla.org/en-US/docs/Glossary/First_paint) (FP): Time when anything is rendered. Note that the marking of the first paint is optional, not all user agents report it.
* [First contentful paint](https://developer.mozilla.org/en-US/docs/Glossary/First_contentful_paint) (FCP): Time when the first bit of DOM text or image content is rendered.

 `LargestContentfulPaint` inherits from [`PerformanceEntry`](performanceentry).


 PerformanceEntry LargestContentfulPaint

Instance properties
-------------------



This interface extends the following [`PerformanceEntry`](performanceentry) properties by qualifying and constraining the properties as follows:

  
[`PerformanceEntry.entryType`](performanceentry/entrytype) Read only   Experimental 
  Returns "`largest-contentful-paint`".

  
[`PerformanceEntry.name`](performanceentry/name) Read only   Experimental 
  Always returns an empty string.

  
[`PerformanceEntry.startTime`](performanceentry/starttime) Read only   Experimental 
  Returns the value of this entry's [`renderTime`](largestcontentfulpaint/rendertime) if it is not `0`, otherwise the value of this entry's [`loadTime`](largestcontentfulpaint/loadtime).

  
[`PerformanceEntry.duration`](performanceentry/duration) Read only   Experimental 
  Returns `0`, as `duration` is not applicable to this interface.

   It also supports the following properties:

  
[`LargestContentfulPaint.element`](largestcontentfulpaint/element) Read only   Experimental 
  The element that is the current largest contentful paint.

  
[`LargestContentfulPaint.renderTime`](largestcontentfulpaint/rendertime) Read only   Experimental 
  The time the element was rendered to the screen. May not be available if the element is a cross-origin image loaded without the `Timing-Allow-Origin` header.

  
[`LargestContentfulPaint.loadTime`](largestcontentfulpaint/loadtime) Read only   Experimental 
  The time the element was loaded.

  
[`LargestContentfulPaint.size`](largestcontentfulpaint/size) Read only   Experimental 
  The intrinsic size of the element returned as the area (width \* height).

  
[`LargestContentfulPaint.id`](largestcontentfulpaint/id) Read only   Experimental 
  The id of the element. This property returns an empty string when there is no id.

  
[`LargestContentfulPaint.url`](largestcontentfulpaint/url) Read only   Experimental 
  If the element is an image, the request url of the image.

  

Instance methods
----------------



*This interface also inherits methods from [`PerformanceEntry`](performanceentry).*

  
[`LargestContentfulPaint.toJSON()`](largestcontentfulpaint/tojson)  Experimental 
  Returns a JSON representation of the `LargestContentfulPaint` object.

  

Examples
--------


### Observing the largest contentful paint



In the following example, an observer is registered to get the largest contentful paint while the page is loading. The `buffered` flag is used to access data from before observer creation.

 The LCP API analyzes all content it finds (including content that is removed from the DOM). When new largest content is found, it creates a new entry. It stops searching for larger content when scroll or input events occur, since these events likely introduce new content on the website. Thus the LCP is the last performance entry reported by the observer.

 
```
const observer = new PerformanceObserver((list) => {
  const entries = list.getEntries();
  const lastEntry = entries[entries.length - 1]; // Use the latest LCP candidate
  console.log("LCP:", lastEntry.startTime);
  console.log(lastEntry);
});
observer.observe({ type: "largest-contentful-paint", buffered: true });

```


### Cross-origin image render time



For security reasons, the value of the [`renderTime`](largestcontentfulpaint/rendertime) property is `0` if the resource is a cross-origin request. Instead the [`loadTime`](largestcontentfulpaint/loadtime) is exposed. To expose cross-origin render time information, the [`Timing-Allow-Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Timing-Allow-Origin) HTTP response header needs to be set.

 For example, to allow `https://developer.mozilla.org` to see `renderTime`, the cross-origin resource should send:

 
```
Timing-Allow-Origin: https://developer.mozilla.org

```
 Like in the code example, you can use [`startTime`](performanceentry/starttime), which returns the value of the entry's [`renderTime`](largestcontentfulpaint/rendertime) if it is not `0`, and otherwise the value of this entry's [`loadTime`](largestcontentfulpaint/loadtime). However, it is recommended to set the [`Timing-Allow-Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Timing-Allow-Origin) header so that the metrics will be more accurate.

 If you use `startTime`, you can flag any inaccuracies by checking if `renderTime` was used:

 
```
const isAccurateLCP = entry.renderTime ? true : false;

```


Specifications
--------------




| Specification |
| --- |
| [Largest Contentful Paint # sec-largest-contentful-paint-interface](https://w3c.github.io/largest-contentful-paint/#sec-largest-contentful-paint-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `LargestContentfulPaint` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |
| `element` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |
| `id` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |
| `loadTime` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |
| `renderTime` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |
| `size` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |
| `toJSON` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |
| `url` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |


See also
--------


* [Largest Contentful Paint](https://developer.mozilla.org/en-US/docs/Glossary/Largest_contentful_paint)
* [First contentful paint](https://developer.mozilla.org/en-US/docs/Glossary/First_contentful_paint)
* [First paint](https://developer.mozilla.org/en-US/docs/Glossary/First_paint)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/LargestContentfulPaint>

IntersectionObserverEntry
=========================



The `IntersectionObserverEntry` interface of the [Intersection Observer API](intersection_observer_api) describes the intersection between the target element and its root container at a specific moment of transition.

 Instances of `IntersectionObserverEntry` are delivered to an [`IntersectionObserver`](intersectionobserver) callback in its `entries` parameter; otherwise, these objects can only be obtained by calling [`IntersectionObserver.takeRecords()`](intersectionobserver/takerecords).



Instance properties
-------------------


 
[`IntersectionObserverEntry.boundingClientRect`](intersectionobserverentry/boundingclientrect) Read only 
  Returns the bounds rectangle of the target element as a [`DOMRectReadOnly`](domrectreadonly). The bounds are computed as described in the documentation for [`Element.getBoundingClientRect()`](element/getboundingclientrect).

  
[`IntersectionObserverEntry.intersectionRatio`](intersectionobserverentry/intersectionratio) Read only 
  Returns the ratio of the `intersectionRect` to the `boundingClientRect`.

  
[`IntersectionObserverEntry.intersectionRect`](intersectionobserverentry/intersectionrect) Read only 
  Returns a [`DOMRectReadOnly`](domrectreadonly) representing the target's visible area.

  
[`IntersectionObserverEntry.isIntersecting`](intersectionobserverentry/isintersecting) Read only 
  A Boolean value which is `true` if the target element intersects with the intersection observer's root. If this is `true`, then, the `IntersectionObserverEntry` describes a transition into a state of intersection; if it's `false`, then you know the transition is from intersecting to not-intersecting.

  
[`IntersectionObserverEntry.rootBounds`](intersectionobserverentry/rootbounds) Read only 
  Returns a [`DOMRectReadOnly`](domrectreadonly) for the intersection observer's root.

  
[`IntersectionObserverEntry.target`](intersectionobserverentry/target) Read only 
  The [`Element`](element) whose intersection with the root changed.

  
[`IntersectionObserverEntry.time`](intersectionobserverentry/time) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) indicating the time at which the intersection was recorded, relative to the `IntersectionObserver`'s [time origin](domhighrestimestamp#the_time_origin).

  
Instance methods
----------------


*This interface has no methods.*


Specifications
--------------




| Specification |
| --- |
| [Intersection Observer # intersection-observer-entry](https://w3c.github.io/IntersectionObserver/#intersection-observer-entry) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `IntersectionObserverEntry` | No | 15–79 | No | No | No | 12.1 | No | No | No | No | 12.2 | No |
| `IntersectionObserverEntry` | 51 | 15 | 55 | No | 38 | 12.1 | 51 | 51 | 55 | 41 | 12.2 | 5.0 |
| `boundingClientRect` | 51 | 15 | 55 | No | 38 | 12.1 | 51 | 51 | 55 | 41 | 12.2 | 5.0 |
| `intersectionRatio` | 51 | 15 | 55 | No | 38 | 12.1 | 51 | 51 | 55 | 41 | 12.2 | 5.0 |
| `intersectionRect` | 51 | 15 | 55 | No | 38 | 12.1 | 51 | 51 | 55 | 41 | 12.2 | 5.0 |
| `isIntersecting` | 58 | 16 | 55 | No | 45 | 12.1 | 58 | 58 | 55 | 43 | 12.2 | 7.0 |
| `rootBounds` | 51 | 15 | 55 | No | 38 | 12.1 | 51 | 51 | 55 | 41 | 12.2 | 5.0 |
| `target` | 51 | 15 | 55 | No | 38 | 12.1 | 51 | 51 | 55 | 41 | 12.2 | 5.0 |
| `time` | 51 | 15 | 55 | No | 38 | 12.1 | 51 | 51 | 55 | 41 | 12.2 | 5.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserverEntry>

InterventionReportBody
======================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `InterventionReportBody` interface of the [Reporting API](reporting_api) represents the body of an intervention report.

 An intervention report is generated when usage of a feature in a web document has been blocked by the browser for reasons such as security, performance, or user annoyance. So for example, a script was been stopped because it was significantly slowing down the browser, or the browser's autoplay policy blocked audio from playing without a user gesture to trigger it.

 A deprecation report is generated when a deprecated feature (for example a deprecated API method) is used on a document being observed by a [`ReportingObserver`](reportingobserver). In addition to the support of this API, receiving useful intervention warnings relies on browser vendors adding these warnings for the relevant features.


 ReportBody InterventionReportBody

Constructor
-----------


An instance of `InterventionReportBody` is returned as the value of [`Report.body`](report/body) when [`Report.Type`](report/type) is `intervention`. The interface has no constructor.


Instance properties
-------------------



This interface also inherits properties from [`ReportBody`](reportbody).

  
[`InterventionReportBody.id`](interventionreportbody/id)  Experimental  Read only 
  A string representing the intervention that generated the report. This can be used to group reports.

  
[`InterventionReportBody.message`](interventionreportbody/message)  Experimental  Read only 
  A string containing a human-readable description of the intervention, including information such how the intervention could be avoided. This typically matches the message a browser will display in its DevTools console when an intervention is imposed, if one is available.

  
[`InterventionReportBody.sourceFile`](interventionreportbody/sourcefile)  Experimental  Read only 
  A string containing the path to the source file where the intervention occurred, if known, or `null` otherwise.

  
[`InterventionReportBody.lineNumber`](interventionreportbody/linenumber)  Experimental  Read only 
  A string representing the line in the source file in which the intervention occurred, if known, or `null` otherwise.

  
[`InterventionReportBody.columnNumber`](interventionreportbody/columnnumber)  Experimental  Read only 
  A string representing the column in the source file in which the intervention occurred, if known, or `null` otherwise.

  

Instance methods
----------------



This interface also inherits methods from [`ReportBody`](reportbody).

  
[`InterventionReportBody.toJSON()`](interventionreportbody/tojson)  Experimental 
  A *serializer* which returns a JSON representation of the `InterventionReportBody` object.

  

Examples
--------



In this example we create a new [`ReportingObserver`](reportingobserver) to observe intervention reports, then print details of each property of the first report to the console.

 
```
const options = {
  types: ["intervention"],
  buffered: true,
};

const observer = new ReportingObserver((reports, observer) => {
  const firstReport = reports[0];
  console.log(firstReport.type); // intervention
  console.log(firstReport.body.id);
  console.log(firstReport.body.message);
  console.log(firstReport.body.sourceFile);
  console.log(firstReport.body.lineNumber);
  console.log(firstReport.body.columnNumber);
}, options);

```


Specifications
--------------




| Specification |
| --- |
| [Intervention Reporting # intervention-report](https://wicg.github.io/intervention-reporting/#intervention-report) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `InterventionReportBody` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `columnNumber` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `id` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `lineNumber` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `message` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `sourceFile` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `toJSON` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |


See also
--------


* [Reporting API](reporting_api)
* [The Reporting API](https://web.dev/reporting-api/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/InterventionReportBody>

KeyframeEffect
==============



The `KeyframeEffect` interface of the [Web Animations API](web_animations_api) lets us create sets of animatable properties and values, called **keyframes.** These can then be played using the [`Animation()`](animation/animation) constructor.


 AnimationEffect KeyframeEffect

Constructor
-----------


 [`KeyframeEffect()`](keyframeeffect/keyframeeffect)  Returns a new `KeyframeEffect` object instance, and also allows you to clone an existing keyframe effect object instance.

  
Instance properties
-------------------


 [`KeyframeEffect.target`](keyframeeffect/target)  Gets and sets the element, or originating element of the pseudo-element, being animated by this object. This may be `null` for animations that do not target a specific element or pseudo-element.

  [`KeyframeEffect.pseudoElement`](keyframeeffect/pseudoelement)  Gets and sets the selector of the pseudo-element being animated by this object. This may be `null` for animations that do not target a pseudo-element.

  [`KeyframeEffect.iterationComposite`](keyframeeffect/iterationcomposite)  Gets and sets the iteration composite operation for resolving the property value changes of this keyframe effect.

  [`KeyframeEffect.composite`](keyframeeffect/composite)  Gets and sets the composite operation property for resolving the property value changes between this and other keyframe effects.

  
Instance methods
----------------



*This interface inherits some of its methods from its parent, [`AnimationEffect`](animationeffect).*

  [`AnimationEffect.getComputedTiming()`](animationeffect/getcomputedtiming)  Returns the calculated, current timing values for this keyframe effect.

  [`KeyframeEffect.getKeyframes()`](keyframeeffect/getkeyframes)  Returns the computed keyframes that make up this effect along with their computed keyframe offsets.

  [`AnimationEffect.getTiming()`](animationeffect/gettiming)  Returns the object associated with the animation containing all the animation's timing values.

  [`KeyframeEffect.setKeyframes()`](keyframeeffect/setkeyframes)  Replaces the set of keyframes that make up this effect.

  [`AnimationEffect.updateTiming()`](animationeffect/updatetiming)  Updates the specified timing properties.

  

Examples
--------



In the [Follow the White Rabbit example](https://codepen.io/rachelnabors/pen/eJyWzm/?editors=0010), the KeyframeEffect constructor is used to create a set of keyframes that dictate how the White Rabbit should animate down the hole:

 
```
const whiteRabbit = document.getElementById("rabbit");

const rabbitDownKeyframes = new KeyframeEffect(
  whiteRabbit, // element to animate
  [
    { transform: "translateY(0%)" }, // keyframe
    { transform: "translateY(100%)" }, // keyframe
  ],
  { duration: 3000, fill: "forwards" } // keyframe options
);

const rabbitDownAnimation = new Animation(
  rabbitDownKeyframes,
  document.timeline
);

// Play rabbit animation
rabbitDownAnimation.play();

```


Specifications
--------------




| Specification |
| --- |
| [Web Animations # the-keyframeeffect-interface](https://w3c.github.io/csswg-drafts/web-animations-1/#the-keyframeeffect-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `KeyframeEffect` | 75 | 79 | 63 | No | 62 | 13.1 | 75 | 75 | 63 | 54 | 13.4 | 11.0 |
| `KeyframeEffect` | 75 | 79 | 63 | No | 62 | 13.1 | 75 | 75 | 63 | 54 | 13.4 | 11.0 |
| `composite` | 84 | 84 | 80 | No | 71 | 16 | 84 | 84 | 80 | 60 | 16 | 14.0 |
| `getKeyframes` | 84 | 84 | 63 | No | 71 | 13.1 | 84 | 84 | 63 | 60 | 13.4 | 14.0 |
| `iterationComposite` | No | No | 80 | No | No | 16.4 | No | No | 80 | No | 16.4 | No |
| `pseudoElement` | 84 | 84 | 75 | No | 71 | 14 | 84 | 84 | 79 | 60 | 14 | 14.0 |
| `setKeyframes` | 84 | 84 | 63 | No | 71 | 13.1 | 84 | 84 | 63 | 60 | 13.4 | 14.0 |
| `target` | 75 | 79 | 63 | No | 62 | 13.1 | 75 | 75 | 63 | 54 | 13.4 | 11.0 |


See also
--------


* [Web Animations API](web_animations_api)
* [`Animation`](animation)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect>

LaunchParams
============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `LaunchParams` interface of the [Launch Handler API](launch_handler_api) is used when implementing custom launch navigation handling in a PWA. When [`window.launchQueue.setConsumer()`](launchqueue/setconsumer) is invoked to set up the launch navigation handling functionality, the callback function inside `setConsumer()` is passed a `LaunchParams` object instance.

 Such custom navigation handling is initiated via [`Window.launchQueue`](window/launchqueue) when a PWA has been launched with a [`launch_handler`](https://developer.mozilla.org/en-US/docs/Web/Manifest/launch_handler) `client_mode` value of `focus-existing`, `navigate-new`, or `navigate-existing`.



Instance properties
-------------------


 
[`LaunchParams.files`](launchparams/files) Read only  Experimental 
  Returns a read-only array of [`FileSystemHandle`](filesystemhandle) objects representing any files passed along with the launch navigation via the [`POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) method.

  
[`LaunchParams.targetURL`](launchparams/targeturl) Read only  Experimental 
  Returns the target URL of the launch.

  
Examples
--------



```
if ("launchQueue" in window) {
  window.launchQueue.setConsumer((launchParams) => {
    if (launchParams.targetURL) {
      const params = new URL(launchParams.targetURL).searchParams;

      // Assuming a music player app that gets a track passed to it to be played
      const track = params.get("track");
      if (track) {
        audio.src = track;
        title.textContent = new URL(track).pathname.substr(1);
        audio.play();
      }
    }
  });
}

```

Specifications
--------------




| Specification |
| --- |
| [Web App Launch Handler API # launchparams-interface](https://wicg.github.io/web-app-launch/#launchparams-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `LaunchParams` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `files` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `targetURL` | 110 | 110 | No | No | 96 | No | 110 | 110 | No | 74 | No | No |


See also
--------


* [Launch Handler API: Control how your app is launched](https://developer.chrome.com/docs/web-platform/launch-handler/)
* [`Window.launchQueue`](window/launchqueue)
* [Musicr 2.0](https://launch-handler.glitch.me/) demo app


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/LaunchParams>

LaunchQueue
===========



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `LaunchQueue` interface of the [Launch Handler API](launch_handler_api) is available via the [`Window.launchQueue`](window/launchqueue) property. When a [progressive web app](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps) (PWA) is launched with a [`launch_handler`](https://developer.mozilla.org/en-US/docs/Web/Manifest/launch_handler) `client_mode` value of `focus-existing`, `navigate-new`, or `navigate-existing`, [`LaunchQueue`](launchqueue) provides access to functionality that allows custom launch navigation handling to be implemented in the PWA. This functionality is controlled by the properties of the [`LaunchParams`](launchparams) object passed into the [`setConsumer()`](launchqueue/setconsumer) callback function.



Instance Methods
----------------


 
[`setConsumer()`](launchqueue/setconsumer)  Experimental 
  Contains a callback function that handles custom launch navigation for a PWA.

  
Examples
--------



```
if ("launchQueue" in window) {
  window.launchQueue.setConsumer((launchParams) => {
    if (launchParams.targetURL) {
      const params = new URL(launchParams.targetURL).searchParams;

      // Assuming a music player app that gets a track passed to it to be played
      const track = params.get("track");
      if (track) {
        audio.src = track;
        title.textContent = new URL(track).pathname.substr(1);
        audio.play();
      }
    }
  });
}

```

Specifications
--------------




| Specification |
| --- |
| [Web App Launch Handler API # launchqueue-interface](https://wicg.github.io/web-app-launch/#launchqueue-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `LaunchQueue` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `setConsumer` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |


See also
--------


* [Launch Handler API: Control how your app is launched](https://developer.chrome.com/docs/web-platform/launch-handler/)
* [`Window.launchQueue`](window/launchqueue)
* [Musicr 2.0](https://launch-handler.glitch.me/) demo app


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/LaunchQueue>

LayoutShiftAttribution
======================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `LayoutShiftAttribution` interface provides debugging information about elements which have shifted.

 Instances of `LayoutShiftAttribution` are returned in an array by calling [`LayoutShift.sources`](layoutshift/sources).



Instance properties
-------------------


 
[`LayoutShiftAttribution.node`](layoutshiftattribution/node) Read only   Experimental 
  Returns the element that has shifted (null if it has been removed).

  
[`LayoutShiftAttribution.previousRect`](layoutshiftattribution/previousrect) Read only   Experimental 
  Returns a [`DOMRectReadOnly`](domrectreadonly) object representing the position of the element before the shift.

  
[`LayoutShiftAttribution.currentRect`](layoutshiftattribution/currentrect) Read only   Experimental 
  Returns a [`DOMRectReadOnly`](domrectreadonly) object representing the position of the element after the shift.

  
Instance methods
----------------


 
[`LayoutShiftAttribution.toJSON()`](layoutshiftattribution/tojson)  Experimental 
  Returns a JSON representation of the `LayoutShiftAttribution` object.

  
Examples
--------



The following example finds the element with the highest layout shift score, and returns the element in that entry with the largest size prior to the shift (`previousRect`). For more detail on this see [Debug Web Vitals in the field](https://web.dev/debug-web-vitals-in-the-field/).

 
```
function getCLSDebugTarget(entries) {
  const largestEntry = entries.reduce((a, b) =>
    a && a.value > b.value ? a : b
  );
  if (largestEntry?.sources?.length) {
    const largestSource = largestEntry.sources.reduce((a, b) => {
      const area = (el) => el.previousRect.width \* el.previousRect.height;
      return a.node && area(a) > area(b) ? a : b;
    });
    if (largestSource) {
      return largestSource.node;
    }
  }
}

```


Specifications
--------------




| Specification |
| --- |
| [Layout Instability # sec-layout-shift-attribution](https://wicg.github.io/layout-instability/#sec-layout-shift-attribution) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `LayoutShiftAttribution` | 84 | 84 | No | No | 70 | No | 84 | 84 | No | 60 | No | 14.0 |
| `currentRect` | 84 | 84 | No | No | 70 | No | 84 | 84 | No | 60 | No | 14.0 |
| `node` | 84 | 84 | No | No | 70 | No | 84 | 84 | No | 60 | No | 14.0 |
| `previousRect` | 84 | 84 | No | No | 70 | No | 84 | 84 | No | 60 | No | 14.0 |
| `toJSON` | 84 | 84 | No | No | 70 | No | 84 | 84 | No | 60 | No | 14.0 |


See also
--------


* [Debug layout shifts](https://web.dev/debug-layout-shifts/)
* [Debug Web Vitals in the field](https://web.dev/debug-web-vitals-in-the-field/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/LayoutShiftAttribution>

Lock
====


 The `Lock` interface of the [Web Locks API](web_locks_api) provides the name and mode of a lock. This may be a newly requested lock that is received in the callback to [`LockManager.request()`](lockmanager/request), or a record of an active or queued lock returned by [`LockManager.query()`](lockmanager/query). 


Instance properties
-------------------


 
[`Lock.mode`](lock/mode) Read only 
   Returns the access mode passed to [`LockManager.request()`](lockmanager/request) when the lock was requested. The mode is either `"exclusive"` (the default) or `"shared"`. 

  
[`Lock.name`](lock/name) Read only 
  Returns the name passed to [`LockManager.request()`](lockmanager/request) when the lock was requested.

  
Examples
--------



 The following examples show how the mode and name properties are passed in the call to [`LockManager.request()`](lockmanager/request). `LockManager` is the object returned by [`navigator.locks`](navigator/locks). 

 
```
navigator.locks.request("net\_db\_sync", show_lock_properties);
navigator.locks.request(
  "another\_lock",
  { mode: "shared" },
  show_lock_properties
);

function show\_lock\_properties(lock) {
  console.log(`The lock name is: ${lock.name}`);
  console.log(`The lock mode is: ${lock.mode}`);
}

```


Specifications
--------------




| Specification |
| --- |
| [Web Locks API # api-lock](https://w3c.github.io/web-locks/#api-lock) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Lock` | 69 | 79 | 96 | No | 56 | 15.4 | 69 | 69 | 96 | 48 | 15.4 | 10.0 |
| `mode` | 69 | 79 | 96 | No | 56 | 15.4 | 69 | 69 | 96 | 48 | 15.4 | 10.0 |
| `name` | 69 | 79 | 96 | No | 56 | 15.4 | 69 | 69 | 96 | 48 | 15.4 | 10.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Lock>

LockManager
===========


The `LockManager` interface of the [Web Locks API](web_locks_api) provides methods for requesting a new [`Lock`](lock) object and querying for an existing `Lock` object. To get an instance of `LockManager`, call [`navigator.locks`](navigator/locks).


Instance methods
----------------


 [`LockManager.request()`](lockmanager/request)  Requests a [`Lock`](lock) object with parameters specifying its name and characteristics.

  [`LockManager.query()`](lockmanager/query)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with an object that contains information about held and pending locks.

  
Specifications
--------------




| Specification |
| --- |
| [Web Locks API # api-lock-manager](https://w3c.github.io/web-locks/#api-lock-manager) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `LockManager` | 69 | 79 | 96 | No | 56 | 15.4 | 69 | 69 | 96 | 48 | 15.4 | 10.0 |
| `query` | 69 | 79 | 96 | No | 56 | 15.4 | 69 | 69 | 96 | 48 | 15.4 | 10.0 |
| `request` | 69 | 79 | 96 | No | 56 | 15.4 | 69 | 69 | 96 | 48 | 15.4 | 10.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/LockManager>

LayoutShift
===========



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `LayoutShift` interface of the [Performance API](performance_api) provides insights into the layout stability of web pages based on movements of the elements on the page.



Description
-----------



A layout shift happens when any element that is visible in the viewport changes its position between two frames. These elements are described as being **unstable**, indicating a lack of visual stability.

 The Layout Instability API provides a way to measure and report on these layout shifts. All tools for debugging layout shifts, including those in the browser's developer tools, use this API. The API can also be used to observe and debug layout shifts by logging the information to the console, to send the data to a server endpoint, or to web page analytics.

 Popular performance tools, use this API to calculate a [Cumulative Layout Shift (CLS)](https://web.dev/cls/) score.


 PerformanceEntry LayoutShift

Instance properties
-------------------



This interface extends the following [`PerformanceEntry`](performanceentry) properties by qualifying them as follows:

  
[`PerformanceEntry.duration`](performanceentry/duration) Read only   Experimental 
  Always returns `0` (the concept of duration does not apply to layout shifts).

  
[`PerformanceEntry.entryType`](performanceentry/entrytype) Read only   Experimental 
  Always returns `"layout-shift"`.

  
[`PerformanceEntry.name`](performanceentry/name) Read only   Experimental 
  Always returns `"layout-shift"`.

  
[`PerformanceEntry.startTime`](performanceentry/starttime) Read only   Experimental 
  Returns a [`DOMHighResTimeStamp`](domhighrestimestamp) representing the time when the layout shift started.

   This interface also supports the following properties:

  
[`LayoutShift.value`](layoutshift/value)  Experimental 
  Returns the layout shift score calculated as the impact fraction (fraction of the viewport that was shifted) multiplied by the distance fraction (distance moved as a fraction of viewport).

  
[`LayoutShift.hadRecentInput`](layoutshift/hadrecentinput)  Experimental 
  Returns `true` if [`lastInputTime`](layoutshift/lastinputtime) is less than 500 milliseconds in the past.

  
[`LayoutShift.lastInputTime`](layoutshift/lastinputtime)  Experimental 
  Returns the time of the most recent excluding input (user input that would exclude this entry as a contributor to the CLS score) or `0` if no excluding input has occurred.

  
[`LayoutShift.sources`](layoutshift/sources)  Experimental 
  Returns an array of [`LayoutShiftAttribution`](layoutshiftattribution) objects with information on the elements that were shifted.

  

Instance methods
----------------


 
[`LayoutShift.toJSON()`](layoutshift/tojson)  Experimental 
  Converts the properties to JSON.

  
Examples
--------


### Logging layout shift values



The following example shows how to capture layout shifts and log them to the console.

 
```
const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    // Count layout shifts without recent user input only
    if (!entry.hadRecentInput) {
      console.log("LayoutShift value:", entry.value);
      if (entry.sources) {
        for (const { node, currentRect, previousRect } of entry.sources)
          console.log("LayoutShift source:", node, {
            currentRect,
            previousRect,
          });
      }
    }
  }
});

observer.observe({ type: "layout-shift", buffered: true });

```


Specifications
--------------




| Specification |
| --- |
| [Layout Instability # sec-layout-shift](https://wicg.github.io/layout-instability/#sec-layout-shift) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `LayoutShift` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |
| `hadRecentInput` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |
| `lastInputTime` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |
| `sources` | 84 | 84 | No | No | 70 | No | 84 | 84 | No | 60 | No | 14.0 |
| `toJSON` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |
| `value` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |


See also
--------


* [`LayoutShiftAttribution`](layoutshiftattribution)
* [Cumulative Layout Shift (CLS)](https://web.dev/cls/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift>

LinearAccelerationSensor
========================



The `LinearAccelerationSensor` interface of the [Sensor APIs](sensor_apis) provides on each reading the acceleration applied to the device along all three axes, but without the contribution of gravity.

 To use this sensor, the user must grant permission to the `'accelerometer'` device sensor through the [Permissions API](permissions_api). In addition, this feature may be blocked by a [Permissions Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy) set on your server.


 EventTarget Sensor Accelerometer LinearAccelerationSensor

Constructor
-----------


 [`LinearAccelerationSensor()`](linearaccelerationsensor/linearaccelerationsensor)  Creates a new `LinearAccelerationSensor` object.

  
Instance properties
-------------------


*Inherits properties from its ancestors, [`Accelerometer`](accelerometer), [`Sensor`](sensor), and [`EventTarget`](eventtarget).*


Instance methods
----------------


*`LinearAccelerationSensor` doesn't have own methods. However, it inherits methods from its parent interfaces, [`Sensor`](sensor) and [`EventTarget`](eventtarget).*


Events
------


*`LinearAccelerationSensor` doesn't have own events. However, it inherits events from its parent interface, [`Sensor`](sensor).*


Example
-------



Linear acceleration is typically read in the [`reading`](sensor/reading_event) event callback. In the example below this occurs sixty times a second.

 
```
let laSensor = new LinearAccelerationSensor({ frequency: 60 });

laSensor.addEventListener("reading", (e) => {
  console.log(`Linear acceleration along the X-axis ${laSensor.x}`);
  console.log(`Linear acceleration along the Y-axis ${laSensor.y}`);
  console.log(`Linear acceleration along the Z-axis ${laSensor.z}`);
});
laSensor.start();

```


Specifications
--------------




| Specification |
| --- |
| [Accelerometer # linearaccelerationsensor-interface](https://w3c.github.io/accelerometer/#linearaccelerationsensor-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `LinearAccelerationSensor` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |
| `LinearAccelerationSensor` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/LinearAccelerationSensor>

Location
========


The `Location` interface represents the location (URL) of the object it is linked to. Changes done on it are reflected on the object it relates to. Both the [`Document`](document) and [`Window`](window) interface have such a linked `Location`, accessible via [`Document.location`](document/location) and [`Window.location`](window/location) respectively.


Location anatomy
----------------



Hover over the URL segments below to highlight their meaning:




Instance properties
-------------------


 [`Location.ancestorOrigins`](location/ancestororigins)  A static [`DOMStringList`](domstringlist) containing, in reverse order, the origins of all ancestor browsing contexts of the document associated with the given `Location` object.

  [`Location.href`](location/href)  A [stringifier](https://developer.mozilla.org/en-US/docs/Glossary/Stringifier) that returns a string containing the entire URL. If changed, the associated document navigates to the new page. It can be set from a different origin than the associated document.

  [`Location.protocol`](location/protocol)  A string containing the protocol scheme of the URL, including the final `':'`.

  [`Location.host`](location/host)  A string containing the host, that is the *hostname*, a `':'`, and the *port* of the URL.

  [`Location.hostname`](location/hostname)  A string containing the domain of the URL.

  [`Location.port`](location/port)  A string containing the port number of the URL.

  [`Location.pathname`](location/pathname)  A string containing an initial `'/'` followed by the path of the URL, not including the query string or fragment.

  [`Location.search`](location/search)  A string containing a `'?'` followed by the parameters or "querystring" of the URL. Modern browsers provide [URLSearchParams](urlsearchparams/get#examples) and [URL.searchParams](url/searchparams#examples) to make it easy to parse out the parameters from the querystring.

  [`Location.hash`](location/hash)  A string containing a `'#'` followed by the fragment identifier of the URL.

  
[`Location.origin`](location/origin) Read only 
  Returns a string containing the canonical form of the origin of the specific location.

  
Instance methods
----------------


 [`Location.assign()`](location/assign)  Loads the resource at the URL provided in parameter.

  [`Location.reload()`](location/reload)  Reloads the current URL, like the Refresh button.

  [`Location.replace()`](location/replace)  Replaces the current resource with the one at the provided URL (redirects to the provided URL). The difference from the `assign()` method and setting the `href` property is that after using `replace()` the current page will not be saved in session [`History`](history), meaning the user won't be able to use the *back* button to navigate to it.

  [`Location.toString()`](location/tostring)  Returns a string containing the whole URL. It is a synonym for [`Location.href`](location/href), though it can't be used to modify the value.

  
Examples
--------



```
// location: https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container
const loc = document.location;
console.log(loc.href); // https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container
console.log(loc.protocol); // https:
console.log(loc.host); // developer.mozilla.org:8080
console.log(loc.hostname); // developer.mozilla.org
console.log(loc.port); // 8080
console.log(loc.pathname); // /en-US/search
console.log(loc.search); // ?q=URL
console.log(loc.hash); // #search-results-close-container
console.log(loc.origin); // https://developer.mozilla.org:8080

location.assign("http://another.site"); // load another page

```

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-location-interface](https://html.spec.whatwg.org/multipage/nav-history-apis.html#the-location-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Location` | 1 | 12 | 1 | 3 | 3 | 1 | ≤37 | 18 | 4 | 10.1 | 1 | 1.0 |
| `ancestorOrigins` | 20 | 79 | No | No | 15 | 6 | 4.4 | 25 | No | 14 | 6 | 1.5 |
| `assign` | 1 | 12 | 1 | 5.5 | 3 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `hash` | 1 | 12 | 1 | 3 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `host` | 1 | 12 | 1 | 3 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `hostname` | 1 | 12 | 1 | 3 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `href` | 1 | 12 | 1 | 3 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `origin` | 8 | 12 | 21Before Firefox 49, results for URL using the blob scheme incorrectly returned null. | 11Intranet sites are set to Compatibility View, which will emulate IE7 and omit `window.location.origin`. | 15 | 5.1 | 3 | 18 | 21Before Firefox 49, results for URL using the blob scheme incorrectly returned null. | 14 | 5 | 1.0 |
| `pathname` | 1 | 12 | 1Before Firefox 53, the `pathname` property returned wrong parts of the URL. For example, for a URL of http://z.com/x?a=true&b=false, `pathname` would return "/x?a=true&b=false" rather than "/x". | 3Internet Explorer does not provide the leading slash character in the `pathname` (`docs/Web/API/Location` instead of `/docs/Web/API/Location`). | ≤12.1 | 1 | 4.4 | 18 | 4Before Firefox 53, the `pathname` property returned wrong parts of the URL. For example, for a URL of http://z.com/x?a=true&b=false, `pathname` would return "/x?a=true&b=false" rather than "/x". | ≤12.1 | 1 | 1.0 |
| `port` | 1 | 12 | 1 | 3 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `protocol` | 1 | 12 | 1 | 3 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `reload` | 1 | 12Before Edge 79, if a page added to *Trusted Sites* contains a cross-origin iframe, then calling `reload()` from within the iframe reloads the trusted page (in other words, the top page reloads, not the iframe). | 1 | 5.5If a page added to *Trusted Sites* contains a cross-origin iframe, then calling `reload()` from within the iframe reloads the trusted page (in other words, the top page reloads, not the iframe). | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `replace` | 1 | 12 | 1 | 5.5 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `search` | 1 | 12 | 1Before Firefox 53, the `search` property returned wrong parts of the URL. For example, for a URL of http://z.com/x?a=true&b=false, `search` would return "", rather than "?a=true&b=false". | 3 | ≤12.1 | 1 | 4.4 | 18 | 4Before Firefox 53, the `search` property returned wrong parts of the URL. For example, for a URL of http://z.com/x?a=true&b=false, `search` would return "", rather than "?a=true&b=false". | ≤12.1 | 1 | 1.0 |
| `toString` | 52 | 12 | 22 | 11Intranet sites are set to Compatibility View, which will emulate IE7 and omit `window.location.toString`. | 39 | 1 | 52 | 52 | 22 | 41 | 1 | 6.0 |


See also
--------


* Two `Location` properties: [`Window.location`](window/location) and [`Document.location`](document/location).
* URL manipulation interfaces: [`URL`](url) and [`URLSearchParams`](urlsearchparams).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Location>

Magnetometer
============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `Magnetometer` interface of the [Sensor APIs](sensor_apis) provides information about the magnetic field as detected by the device's primary magnetometer sensor.

 To use this sensor, the user must grant permission to the `'magnetometer'` device sensor through the [Permissions API](permissions_api). In addition, this feature may be blocked by a [Permissions Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy) set on your server.


 EventTarget Sensor Magnetometer

Constructor
-----------


 
[`Magnetometer()`](magnetometer/magnetometer)  Experimental 
  Creates a new `Magnetometer` object.

  
Instance properties
-------------------


 
[`Magnetometer.x`](magnetometer/x) Read only   Experimental 
  Returns a double containing the magnetic field around the device's x axis.

  
[`Magnetometer.y`](magnetometer/y) Read only   Experimental 
  Returns a double containing the magnetic field around the device's y axis.

  
[`Magnetometer.z`](magnetometer/z) Read only   Experimental 
  Returns a double containing the magnetic field around the device's z axis.

  
Instance methods
----------------


*`Magnetometer` doesn't have own methods. However, it inherits methods from its parent interfaces, [`Sensor`](sensor) and [`EventTarget`](eventtarget).*


Events
------


*`Magnetometer` doesn't have own events. However, it inherits events from its parent interface, [`Sensor`](sensor).*


Example
-------



The magnetometer is typically read in the [`reading`](sensor/reading_event) event callback. In the example below this occurs sixty times a second.

 
```
let magSensor = new Magnetometer({ frequency: 60 });

magSensor.addEventListener("reading", (e) => {
  console.log(`Magnetic field along the X-axis ${magSensor.x}`);
  console.log(`Magnetic field along the Y-axis ${magSensor.y}`);
  console.log(`Magnetic field along the Z-axis ${magSensor.z}`);
});
magSensor.start();

```


Specifications
--------------




| Specification |
| --- |
| [Magnetometer # magnetometer-interface](https://w3c.github.io/magnetometer/#magnetometer-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Magnetometer` | 56 | 79 | No | No | 43 | No | No | 56 | No | No | No | No |
| `Magnetometer` | 56 | 79 | No | No | 43 | No | No | 56 | No | No | No | No |
| `x` | 56 | 79 | No | No | 43 | No | No | 56 | No | No | No | No |
| `y` | 56 | 79 | No | No | 43 | No | No | 56 | No | No | No | No |
| `z` | 56 | 79 | No | No | 43 | No | No | 56 | No | No | No | No |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Magnetometer>

MathMLElement
=============



The `MathMLElement` interface represents any [MathML](https://developer.mozilla.org/en-US/docs/Web/MathML) element.


 EventTarget Node Element MathMLElement

Instance properties
-------------------



*Also inherits properties from its parent, [`Element`](element)*.

  
`MathMLElement.attributeStyleMap` Read only 
  A [`StylePropertyMap`](stylepropertymap) representing the declarations of the element's `style` attribute.

  `MathMLElement.style`  A [`CSSStyleDeclaration`](cssstyledeclaration) representing the declarations of the element's `style` attribute.

  

Instance methods
----------------


*This interface has no methods, but inherits methods from its parent, [`Element`](element)*.


Examples
--------


### MathML



```
<math xmlns="http://www.w3.org/1998/Math/MathML">
  <msqrt>
    <mi>x</mi>
  </msqrt>
</math>

```

### JavaScript



```
document.querySelector("msqrt").constructor.name; // MathMLElement

```

Specifications
--------------




| Specification |
| --- |
| [MathML Core # dom-mathmlelement](https://w3c.github.io/mathml-core/#dom-mathmlelement) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MathMLElement` | 10980 | 10980 | 71 | No | 9567 | 13.1 | 109 | 10980 | 79 | 74 | 13.4 | No |
| `attributeStyleMap` | 109 | No | No | No | 95 | 16.4 | 109 | 109 | No | 74 | 16.4 | No |
| `autofocus` | 109 | 109 | No | No | 95 | 15.4 | 109 | 109 | No | 74 | 15.4 | No |
| `blur` | 10980 | 10980 | 71 | No | 9567 | 13.1 | 109 | 10980 | 79 | 74 | 13.4 | No |
| `dataset` | 10980 | 10980 | 71 | No | 9567 | 13.1 | 109 | 10980 | 79 | 74 | 13.4 | No |
| `focus` | 10980 | 10980 | 71 | No | 9567 | 13.1 | 109 | 10980 | 79 | 74 | 13.4 | No |
| `nonce` | 109 | 109 | No | No | 95 | 15.4 | 109 | 109 | No | 74 | 15.4 | No |
| `style` | 10980 | 10980 | 71 | No | 9567 | 13.1 | 109 | 10980 | 79 | 74 | 13.4 | No |
| `tabIndex` | 10980 | 10980 | 71 | No | 9567 | 13.1 | 109 | 10980 | 79 | 74 | 13.4 | No |


See also
--------


* [`Element`](element)
* [`HTMLElement`](htmlelement)
* [`SVGElement`](svgelement)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MathMLElement>

MediaDeviceInfo
===============



The `MediaDeviceInfo` interface contains information that describes a single media input or output device.

 The list of devices obtained by calling [`navigator.mediaDevices.enumerateDevices()`](mediadevices/enumeratedevices) is an array of `MediaDeviceInfo` objects, one per media device.



Instance properties
-------------------



 
[`MediaDeviceInfo.deviceId`](mediadeviceinfo/deviceid) Read only 
  Returns a string that is an identifier for the represented device that is persisted across sessions. It is un-guessable by other applications and unique to the origin of the calling application. It is reset when the user clears cookies (for Private Browsing, a different identifier is used that is not persisted across sessions).

  
[`MediaDeviceInfo.groupId`](mediadeviceinfo/groupid) Read only 
  Returns a string that is a group identifier. Two devices have the same group identifier if they belong to the same physical device — for example a monitor with both a built-in camera and a microphone.

  
[`MediaDeviceInfo.kind`](mediadeviceinfo/kind) Read only 
  Returns an enumerated value that is either `"videoinput"`, `"audioinput"` or `"audiooutput"`.

  
[`MediaDeviceInfo.label`](mediadeviceinfo/label) Read only 
  Returns a string describing this device (for example "External USB Webcam").

    **Note:** For security reasons, the `label` field is always blank unless an active media stream exists *or* the user has granted persistent permission for media device access. The set of device labels could otherwise be used as part of a [fingerprinting](https://developer.mozilla.org/en-US/docs/Glossary/Fingerprinting) mechanism to identify a user.

 

Instance methods
----------------


 [`MediaDeviceInfo.toJSON()`](mediadeviceinfo/tojson)  Returns a JSON representation of the `MediaDeviceInfo` object.

  
Example
-------



Here's an example that uses [`enumerateDevices()`](mediadevices/enumeratedevices) to get a list of devices.

 
```
if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
  console.log("enumerateDevices() not supported.");
} else {
  // List cameras and microphones.
  navigator.mediaDevices
    .enumerateDevices()
    .then((devices) => {
      devices.forEach((device) => {
        console.log(`${device.kind}: ${device.label} id = ${device.deviceId}`);
      });
    })
    .catch((err) => {
      console.log(`${err.name}: ${err.message}`);
    });
}

```
 This might produce:

 
```
videoinput: id = csO9c0YpAf274OuCPUA53CNE0YHlIr2yXCi+SqfBZZ8=
audioinput: id = RKxXByjnabbADGQNNZqLVLdmXlS0YkETYCIbg+XxnvM=
audioinput: id = r2/xw1xUPIyZunfV1lGrKOma5wTOvCkWfZ368XCndm0=

```
 or if one or more media streams are active, or if persistent permissions have been granted:

 
```
videoinput: FaceTime HD Camera (Built-in) id=csO9c0YpAf274OuCPUA53CNE0YHlIr2yXCi+SqfBZZ8=
audioinput: default (Built-in Microphone) id=RKxXByjnabbADGQNNZqLVLdmXlS0YkETYCIbg+XxnvM=
audioinput: Built-in Microphone id=r2/xw1xUPIyZunfV1lGrKOma5wTOvCkWfZ368XCndm0=

```


Specifications
--------------




| Specification |
| --- |
| [Media Capture and Streams # device-info](https://w3c.github.io/mediacapture-main/#device-info) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaDeviceInfo` | 47 | 14 | 39 | No | 34 | 11 | 47 | 47 | 39 | 34 | 11 | 5.0 |
| `deviceId` | 47 | 14 | 39 | No | 34 | 11 | 47 | 47 | 39 | 34 | 11 | 5.0 |
| `groupId` | 47 | 14 | 39Before Firefox 67, related devices are not actually grouped together by `groupId`. | No | 34 | 11 | 47 | 47 | 39Before Firefox 67, related devices are not actually grouped together by `groupId`. | 34 | 11 | 5.0 |
| `kind` | 47 | 14 | 39 | No | 34 | 11 | 47 | 47 | 39 | 34 | 11 | 5.0 |
| `label` | 47 | 14 | 39 | No | 34 | 11 | 47 | 47 | 39 | 34 | 11 | 5.0 |
| `toJSON` | 47 | 18 | 42 | No | 34 | 11 | 47 | 47 | 42 | 34 | 11 | 5.0 |


See also
--------


* [WebRTC API](webrtc_api)
* [`navigator.mediaDevices.enumerateDevices()`](mediadevices/enumeratedevices)
* [`navigator.mediaDevices.getUserMedia()`](mediadevices/getusermedia)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaDeviceInfo>

MediaDevices
============



The `MediaDevices` interface provides access to connected media input devices like cameras and microphones, as well as screen sharing. In essence, it lets you obtain access to any hardware source of media data.


 EventTarget MediaDevices

Instance properties
-------------------


*Inherits properties from its parent interface, [`EventTarget`](eventtarget).*


Instance methods
----------------



*Inherits methods from its parent interface, [`EventTarget`](eventtarget).*

  [`enumerateDevices()`](mediadevices/enumeratedevices)  Obtains an array of information about the media input and output devices available on the system.

  [`getSupportedConstraints()`](mediadevices/getsupportedconstraints)  Returns an object conforming to [`MediaTrackSupportedConstraints`](mediatracksupportedconstraints) indicating which constrainable properties are supported on the [`MediaStreamTrack`](mediastreamtrack) interface. See [Media Streams API](media_capture_and_streams_api/constraints) to learn more about constraints and how to use them.

  [`getDisplayMedia()`](mediadevices/getdisplaymedia)  Prompts the user to select a display or portion of a display (such as a window) to capture as a [`MediaStream`](mediastream) for sharing or recording purposes. Returns a promise that resolves to a `MediaStream`.

  [`getUserMedia()`](mediadevices/getusermedia)  With the user's permission through a prompt, turns on a camera and/or a microphone on the system and provides a [`MediaStream`](mediastream) containing a video track and/or an audio track with the input.

  
[`selectAudioOutput()`](mediadevices/selectaudiooutput)  Experimental 
  Prompts the user to select a specific audio output device.

  

Events
------


 [`devicechange`](mediadevices/devicechange_event)  Fired when a media input or output device is attached to or removed from the user's computer.

  
Example
-------



```
// Put variables in global scope to make them available to the browser console.
const video = document.querySelector("video");
const constraints = {
  audio: false,
  video: true,
};

navigator.mediaDevices
  .getUserMedia(constraints)
  .then((stream) => {
    const videoTracks = stream.getVideoTracks();
    console.log("Got stream with constraints:", constraints);
    console.log(`Using video device: ${videoTracks[0].label}`);
    stream.onremovetrack = () => {
      console.log("Stream ended");
    };
    video.srcObject = stream;
  })
  .catch((error) => {
    if (error.name === "ConstraintNotSatisfiedError") {
      console.error(
        `The resolution ${constraints.video.width.exact}x${constraints.video.height.exact} px is not supported by your device.`
      );
    } else if (error.name === "PermissionDeniedError") {
      console.error(
        "You need to grant this page permission to access your camera and microphone."
      );
    } else {
      console.error(`getUserMedia error: ${error.name}`, error);
    }
  });

```

Specifications
--------------




| Specification |
| --- |
| [Media Capture and Streams # mediadevices](https://w3c.github.io/mediacapture-main/#mediadevices) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaDevices` | 47 | 12 | 33 | No | 30 | 11 | 47 | 47 | 36 | 30 | 11 | 5.0 |
| `devicechange_event` | 57 | 12 | 52 | No | 34 | 11 | No | No | 52 | 43 | 11 | No |
| `enumerateDevices` | 47 | 12 | 63Before Firefox 63, `enumerateDevices()` only returned input devices. Starting with Firefox 63, output devices are also included if the `media.setsinkid.enabled` preference is enabled.39`enumerateDevices()` only returns input devices.preview`enumerateDevices()` enumerates both input and output devices. Previously only input devices were returned. | No | 34 | 11 | 47 | 47 | 39`enumerateDevices()` only returns input devices. | 34 | 11 | 5.0 |
| `getDisplayMedia` | 72 | 7917–79Available as a member of `Navigator` instead of `MediaDevices`. | 6633–66Since Firefox 33 you can capture screen data using `[getUserMedia()](https://developer.mozilla.org/docs/Web/API/MediaDevices/getUserMedia)`, with a `video` constraint called `mediaSource`. Before 52 it relied on a client-configurable list of allowed sites. | No | 60 | 13 | NoFrom Chrome Android 72 to 88, this method was exposed, but always failed with `NotAllowedError`. See [bug 487935](https://crbug.com/487935). | NoFrom Chrome Android 72 to 88, this method was exposed, but always failed with `NotAllowedError`. See [bug 487935](https://crbug.com/487935). | NoFrom Firefox Android 66 to 79, this method was exposed, but always failed with `NotAllowedError`. | NoFrom Opera Android 72 to 88, this method was exposed, but always failed with `NotAllowedError`. See [bug 487935](https://crbug.com/487935). | No | NoFrom Samsung Internet Android 72 to 88, this method was exposed, but always failed with `NotAllowedError`. See [bug 487935](https://crbug.com/487935). |
| `getSupportedConstraints` | 53 | 12 | 44 | No | 40 | 11 | 53 | 52 | 50 | 41 | 11 | 6.0 |
| `getUserMedia` | 53If you need this capability before version 53, refer to `navigator.webkitGetUserMedia`, a prefixed form of the deprecated [`navigator.getUserMedia`](https://developer.mozilla.org/docs/Web/API/Navigator/getUserMedia) API. | 12 | 36["If you need this capability before version 36, refer to `navigator.mozGetUserMedia`, a prefixed form of the deprecated [`navigator.getUserMedia`](https://developer.mozilla.org/docs/Web/API/Navigator/getUserMedia) API.", "Before Firefox 55, `getUserMedia()` incorrectly returns `NotSupportedError` when the list of constraints specified is empty, or has all constraints set to `false`. Starting in Firefox 55, this situation now correctly calls the failure handler with a `TypeError`.", "When using the Firefox-specific `video` constraint called `mediaSource` to request display capture, Firefox 66 and later consider values of `screen` and `window` to both cause a list of screens *and* windows to be shown.", "Starting in Firefox 66, `getUserMedia()` can no longer be used in sandboxed `<iframe>`s or `data` URLs entered in the address bar by the user."] | No | 40If you need this capability before version 40, refer to `navigator.webkitGetUserMedia`, a prefixed form of the deprecated [`navigator.getUserMedia`](https://developer.mozilla.org/docs/Web/API/Navigator/getUserMedia) API. | 11 | 53 | 53If you need this capability before version 53, refer to `navigator.webkitGetUserMedia`, a prefixed form of the deprecated [`navigator.getUserMedia`](https://developer.mozilla.org/docs/Web/API/Navigator/getUserMedia) API. | 36["If you need this capability before version 36, refer to `navigator.mozGetUserMedia`, a prefixed form of the deprecated [`navigator.getUserMedia`](https://developer.mozilla.org/docs/Web/API/Navigator/getUserMedia) API.", "Before Firefox 55, `getUserMedia()` incorrectly returns `NotSupportedError` when the list of constraints specified is empty, or has all constraints set to `false`. Starting in Firefox 55, this situation now correctly calls the failure handler with a `TypeError`.", "When using the Firefox-specific `video` constraint called `mediaSource` to request display capture, Firefox 66 and later consider values of `screen` and `window` to both cause a list of screens *and* windows to be shown.", "Starting in Firefox 66, `getUserMedia()` can no longer be used in sandboxed `<iframe>`s or `data` URLs entered in the address bar by the user."] | 41If you need this capability before version 41, refer to `navigator.webkitGetUserMedia`, a prefixed form of the deprecated [`navigator.getUserMedia`](https://developer.mozilla.org/docs/Web/API/Navigator/getUserMedia) API. | 11 | 6.0 |
| `selectAudioOutput` | No | No | 88preview | No | No | No | No | No | No | No | No | No |
| `setCaptureHandleConfig` | 102 | 102 | No | No | 88 | No | No | No | No | No | No | No |


See also
--------


* [Media Capture and Streams API](media_capture_and_streams_api): The API this interface is part of.
* [Screen Capture API](screen_capture_api): The API defining the [`getDisplayMedia()`](mediadevices/getdisplaymedia) method.
* [WebRTC API](webrtc_api)
* [`Navigator.mediaDevices`](navigator/mediadevices): Returns a reference to a `MediaDevices` object that can be used to access devices.
* [CameraCaptureJS:](https://github.com/chrisjohndigital/CameraCaptureJS) HTML video capture and playback using `MediaDevices` and the MediaStream Recording API
* [OpenLang](https://github.com/chrisjohndigital/OpenLang): HTML video language lab web application using `MediaDevices` and the MediaStream Recording API for video recording


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices>

MediaError
==========



The `MediaError` interface represents an error which occurred while handling media in an HTML media element based on [`HTMLMediaElement`](htmlmediaelement), such as [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) or [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video).

 A `MediaError` object describes the error in general terms using a numeric `code` categorizing the kind of error, and a `message`, which provides specific diagnostics about what went wrong.



Instance properties
-------------------



*This interface doesn't inherit any properties.*

  [`MediaError.code`](mediaerror/code)  A number which represents [the general type of error that occurred](mediaerror/code#media_error_code_constants).

  [`MediaError.message`](mediaerror/message)  A human-readable string which provides *specific diagnostic information* to help the reader understand the error condition which occurred; specifically, it isn't a summary of what the error code means, but actual diagnostic information to help in understanding what exactly went wrong. This text and its format is not defined by the specification and will vary from one [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) to another. If no diagnostics are available, or no explanation can be provided, this value is an empty string (`""`).

  

Instance methods
----------------


*This interface doesn't implement or inherit any methods, and has none of its own.*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # error-codes](https://html.spec.whatwg.org/multipage/media.html#error-codes) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaError` | 3 | 12 | 43.5–4 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 2 | 1.0 |
| `code` | 3 | 12 | 3.5 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 2 | 1.0 |
| `message` | 59 | 79 | 52 | No | 46 | 15 | 59 | 59 | 52 | 43 | 15 | 7.0 |


See also
--------


* [`HTMLMediaElement.error`](htmlmediaelement/error)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaError>

MediaImage
==========



The Media Session API's `MediaImage` dictionary describes the images associated with a media resource's [`MediaMetadata`](mediametadata).

 Its contents can be displayed by the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) in appropriate contexts like in a player interface to show the current playing video or audio track.



Instance properties
-------------------


 `src`  The URL from which the user agent fetches the image's data.

  `sizes`  Specifies the resource in multiple sizes so the user agent doesn't have to scale a single image.

  `type`  The [MIME type](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type) hint for the user agent that allows it to ignore images of types that it doesn't support. However, the user agent may still use MIME type sniffing after downloading the image to determine its type.

  
Specifications
--------------



**No specification found**No specification data found for `api.MediaImage`.  
[Check for problems with this page](#on-github) or contribute a missing `spec_url` to [mdn/browser-compat-data](https://github.com/mdn/browser-compat-data). Also make sure the specification is included in [w3c/browser-specs](https://github.com/w3c/browser-specs).



Browser compatibility
---------------------


See also
--------


* [`MediaMetadata.artwork`](mediametadata/artwork)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaImage>

MediaCapabilities
=================



The `MediaCapabilities` interface of the [Media Capabilities API](media_capabilities_api) provides information about the decoding abilities of the device, system and browser. The API can be used to query the browser about the decoding abilities of the device based on codecs, profile, resolution, and bitrates. The information can be used to serve optimal media streams to the user and determine if playback should be smooth and power efficient.

 The information is accessed through the `mediaCapabilities` property of the [`Navigator`](navigator) interface.



Instance methods
----------------


 [`MediaCapabilities.encodingInfo()`](mediacapabilities/encodinginfo)  When passed a valid media configuration, it returns a promise with information as to whether the media type is supported, and whether encoding such media would be smooth and power efficient.

  [`MediaCapabilities.decodingInfo()`](mediacapabilities/decodinginfo)  When passed a valid media configuration, it returns a promise with information as to whether the media type is supported, and whether decoding such media would be smooth and power efficient.

  
Specifications
--------------




| Specification |
| --- |
| [Media Capabilities # media-capabilities-interface](https://w3c.github.io/media-capabilities/#media-capabilities-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaCapabilities` | 66 | 79 | 63 | No | 53 | 13 | 66 | 66 | 63 | 48 | 13 | 9.0 |
| `decodingInfo` | 66["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 79["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 63["The `webrtc` value of the `type` option is named `transmission`.", "Before Firefox 101, `decodingInfo()` ignored `codecs` parameter options for `av01` codecs (treating them as `av1`)."] | No | 53["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 13 | 66["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 66["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 63["The `webrtc` value of the `type` option is named `transmission`.", "Before Firefox 101, `decodingInfo()` ignored `codecs` parameter options for `av01` codecs (treating them as `av1`)."] | 48["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 13 | 9.0["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] |
| `encodingInfo` | 101 | 101 | 63The `webrtc` value of the `type` option is named `transmission`. | No | 87 | 15.4 | 101 | 101 | 63The `webrtc` value of the `type` option is named `transmission`. | 70 | 15.4 | 19.0 |


See also
--------


* [HTMLMediaElement](htmlmediaelement)'s method [canPlayType()](htmlmediaelement/canplaytype)
* [MediaSource](mediasource)'s method [isTypeSupported()](mediasource/istypesupported)
* [`Navigator`](navigator) interface


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaCapabilities>

MediaElementAudioSourceNode
===========================



The `MediaElementAudioSourceNode` interface represents an audio source consisting of an HTML [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) or [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) element. It is an [`AudioNode`](audionode) that acts as an audio source.

 A `MediaElementAudioSourceNode` has no inputs and exactly one output, and is created using the [`AudioContext.createMediaElementSource()`](audiocontext/createmediaelementsource) method. The number of channels in the output equals the number of channels of the audio referenced by the [`HTMLMediaElement`](htmlmediaelement) used in the creation of the node, or is 1 if the [`HTMLMediaElement`](htmlmediaelement) has no audio.


 EventTarget AudioNode MediaElementAudioSourceNode 

|  |  |
| --- | --- |
| Number of inputs | `0` |
| Number of outputs | `1` |
| Channel count | 2 (but note that [`AudioNode.channelCount`](audionode/channelcount) is only used for up-mixing and down-mixing [`AudioNode`](audionode) inputs, and [`MediaElementAudioSourceNode`](mediaelementaudiosourcenode) doesn't have any input) |



Constructor
-----------


 [`MediaElementAudioSourceNode()`](mediaelementaudiosourcenode/mediaelementaudiosourcenode)  Creates a new `MediaElementAudioSourceNode` object instance.

  
Instance properties
-------------------



*Inherits properties from its parent, [`AudioNode`](audionode)*.

  
[`mediaElement`](mediaelementaudiosourcenode/mediaelement) Read only 
  The [`HTMLMediaElement`](htmlmediaelement) used when constructing this `MediaStreamAudioSourceNode`.

  

Instance methods
----------------


*Inherits methods from its parent, [`AudioNode`](audionode)*.


Example
-------


See [`AudioContext.createMediaElementSource()`](audiocontext/createmediaelementsource#examples) for example code.


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # MediaElementAudioSourceNode](https://webaudio.github.io/web-audio-api/#MediaElementAudioSourceNode) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaElementAudioSourceNode` | 55 | 79 | 53 | No | 42 | 14.1 | 55 | 55 | 53 | 42 | 14.5 | 6.0 |
| `MediaElementAudioSourceNode` | 15 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `mediaElement` | 15 | 79 | 70 | No | 15 | 6 | ≤37 | 18 | 79 | 14 | 6 | 1.0 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaElementAudioSourceNode>

MediaEncryptedEvent
===================



The `MediaEncryptedEvent` interface of the [Encrypted Media Extensions API](encrypted_media_extensions_api) contains the information associated with an [`encrypted`](htmlmediaelement/encrypted_event) event sent to a [`HTMLMediaElement`](htmlmediaelement) when some initialization data is encountered in the media.


 Event MediaEncryptedEvent

Constructor
-----------


 [`MediaEncryptedEvent()`](mediaencryptedevent/mediaencryptedevent)  Creates a new instance of a `MediaEncryptedEvent` object.

  
Instance properties
-------------------



*This interface also inherits properties from its parent, [`Event`](event).*

  
[`MediaEncryptedEvent.initDataType`](mediaencryptedevent/initdatatype) Read only 
  Returns a case-sensitive string with the *type* of the format of the initialization data found.

  
[`MediaEncryptedEvent.initData`](mediaencryptedevent/initdata) Read only 
  Returns an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing the initialization data found. If there is no initialization data associated with the format, it returns `null`.

  

Instance methods
----------------


*This interface doesn't provide any specific methods, but inherits methods from its parent, [`Event`](event).*


Specifications
--------------




| Specification |
| --- |
| [Encrypted Media Extensions # mediaencryptedevent](https://w3c.github.io/encrypted-media/#mediaencryptedevent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaEncryptedEvent` | 42 | 13 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |
| `MediaEncryptedEvent` | 42 | 13 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |
| `initData` | 42 | 13 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |
| `initDataType` | 42 | 13 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaEncryptedEvent>

MediaKeys
=========


The `MediaKeys` interface of [Encrypted Media Extensions API](encrypted_media_extensions_api) represents a set of keys that an associated [`HTMLMediaElement`](htmlmediaelement) can use for decryption of media data during playback.


Instance properties
-------------------


None.


Instance methods
----------------


 [`MediaKeys.createSession()`](mediakeys/createsession)  Returns a new [`MediaKeySession`](mediakeysession) object, which represents a context for message exchange with a content decryption module (CDM).

  [`MediaKeys.setServerCertificate()`](mediakeys/setservercertificate)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) to a server certificate to be used to encrypt messages to the license server.

  
Examples
--------



```
//TBD

```

Specifications
--------------




| Specification |
| --- |
| [Encrypted Media Extensions # mediakeys-interface](https://w3c.github.io/encrypted-media/#mediakeys-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaKeys` | 42 | 13 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |
| `createSession` | 42 | 13 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |
| `setServerCertificate` | 42 | 13 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaKeys>

MediaKeySession
===============



The `MediaKeySession` interface of the [Encrypted Media Extensions API](encrypted_media_extensions_api) represents a context for message exchange with a content decryption module (CDM).


 EventTarget MediaKeySession

Instance properties
-------------------


 
[`MediaKeySession.closed`](mediakeysession/closed) Read only 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) signaling when a `MediaKeySession` closes. This promise can only be fulfilled and is never rejected. Closing a session means that licenses and keys associated with it are no longer valid for decrypting media data.

  
[`MediaKeySession.expiration`](mediakeysession/expiration) Read only 
  The time after which the keys in the current session can no longer be used to decrypt media data, or `NaN` if no such time exists. This value is determined by the CDM and measured in milliseconds since January 1, 1970, UTC. This value may change during a session lifetime, such as when an action triggers the start of a window.

  
[`MediaKeySession.keyStatuses`](mediakeysession/keystatuses) Read only 
  Contains a reference to a read-only [`MediaKeyStatusMap`](mediakeystatusmap) of the current session's keys and their statuses.

  
[`MediaKeySession.sessionId`](mediakeysession/sessionid) Read only 
  Contains a unique string generated by the CDM for the current media object and its associated keys or licenses.

  
### Events


 [`keystatuseschange`](mediakeysession/keystatuseschange_event)  Fires when there has been a change in the keys in a session or their statuses.

  [`message`](mediakeysession/message_event)  Fires when the content decryption module has generated a message for the session.

  
Instance methods
----------------


 [`MediaKeySession.close()`](mediakeysession/close)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) after notifying the current media session is no longer needed and that the CDM should release any resources associated with this object and close it.

  [`MediaKeySession.generateRequest()`](mediakeysession/generaterequest)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) after generating a media request based on initialization data.

  [`MediaKeySession.load()`](mediakeysession/load)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to a boolean value after loading data for a specified session object.

  [`MediaKeySession.remove()`](mediakeysession/remove)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) after removing any session data associated with the current object.

  [`MediaKeySession.update()`](mediakeysession/update)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) after loading messages and licenses to the CDM.

  
Examples
--------



```
// TBD

```

Specifications
--------------




| Specification |
| --- |
| [Encrypted Media Extensions # mediakeysession-interface](https://w3c.github.io/encrypted-media/#mediakeysession-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaKeySession` | 42 | 13 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |
| `close` | 42 | 13 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |
| `closed` | 42 | 13 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |
| `expiration` | 42 | 13 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |
| `generateRequest` | 42 | 13 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |
| `keyStatuses` | 42 | 13 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |
| `keystatuseschange_event` | 5542–55The `onkeystatuseschange` event handler property is not supported. | 79 | 52 | No | 4229–42The `onkeystatuseschange` event handler property is not supported. | 12.1 | 5543–55The `onkeystatuseschange` event handler property is not supported. | 5542–55The `onkeystatuseschange` event handler property is not supported. | 52 | 4229–42The `onkeystatuseschange` event handler property is not supported. | 12.2 | 6.04.0–6.0The `onkeystatuseschange` event handler property is not supported. |
| `load` | 42 | 13 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |
| `message_event` | 5542–55The `onmessage` event handler property is not supported. | 79 | 52 | No | 4229–42The `onmessage` event handler property is not supported. | 12.1 | 5543–55The `onmessage` event handler property is not supported. | 5542–55The `onmessage` event handler property is not supported. | 52 | 4229–42The `onmessage` event handler property is not supported. | 12.2 | 6.04.0–6.0The `onmessage` event handler property is not supported. |
| `remove` | 42 | 13 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |
| `sessionId` | 42 | 13 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |
| `update` | 42 | 13 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySession>

MediaKeyStatusMap
=================


The `MediaKeyStatusMap` interface of the [Encrypted Media Extensions API](encrypted_media_extensions_api) is a read-only map of media key statuses by key IDs.


Instance properties
-------------------


 
[`MediaKeyStatusMap.size`](mediakeystatusmap/size) Read only 
  Returns the number of key/value pairs in the status map.

  
Instance methods
----------------


 
[`MediaKeyStatusMap.entries()`](mediakeystatusmap/entries) Read only 
  Returns a new `Iterator` object containing an array of `[key, value]` for each element in the status map, in insertion order.

  
[`MediaKeyStatusMap.forEach(callback[, argument])`](mediakeystatusmap/foreach) Read only 
  Calls `callback` once for each key-value pair in the status map, in insertion order. If `argument` is present it will be passed to the callback.

  
[`MediaKeyStatusMap.get()`](mediakeystatusmap/get) Read only 
  Returns the value associated with the given key, or `undefined` if there is none.

  
[`MediaKeyStatusMap.has()`](mediakeystatusmap/has) Read only 
  Returns a boolean asserting whether a value has been associated with the given key.

  
[`MediaKeyStatusMap.keys()`](mediakeystatusmap/keys) Read only 
  Returns a new `Iterator` object containing keys for each element in the status map, in insertion order.

  
[`MediaKeyStatusMap.values()`](mediakeystatusmap/values) Read only 
  Returns a new `Iterator` object containing values for each element in the status map, in insertion order.

  
`MediaKeyStatusMap.[@@iterator]()` Read only 
  Returns a new `Iterator` object containing an array of `[key, value]` for each element in the status map, in insertion order.

  
Specifications
--------------




| Specification |
| --- |
| [Encrypted Media Extensions # mediakeystatusmap-interface](https://w3c.github.io/encrypted-media/#mediakeystatusmap-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@iterator` | 42 | 16 | 45 | No | 29 | 12.1 | 43 | 42 | 45 | 29 | 12.2 | 4.0 |
| `MediaKeyStatusMap` | 42 | 13 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |
| `entries` | 42 | 16 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |
| `forEach` | 42 | 13 | 47 | No | 29 | 12.1 | 43 | 42 | 47 | 29 | 12.2 | 4.0 |
| `get` | 42 | 13 | 45 | No | 29 | 12.1 | 43 | 42 | 45 | 29 | 12.2 | 4.0 |
| `has` | 42 | 13 | 45 | No | 29 | 12.1 | 43 | 42 | 45 | 29 | 12.2 | 4.0 |
| `keys` | 42 | 16 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |
| `size` | 42 | 13 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |
| `values` | 42 | 16 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaKeyStatusMap>

MediaKeySystemAccess
====================


The `MediaKeySystemAccess` interface of the [Encrypted Media Extensions API](encrypted_media_extensions_api) provides access to a Key System for decryption and/or a content protection provider. You can request an instance of this object using the [`Navigator.requestMediaKeySystemAccess()`](navigator/requestmediakeysystemaccess) method.


Instance properties
-------------------


 
[`MediaKeySystemAccess.keySystem`](mediakeysystemaccess/keysystem) Read only 
  Returns a string identifying the key system being used.

  
Instance methods
----------------


 [`MediaKeySystemAccess.createMediaKeys()`](mediakeysystemaccess/createmediakeys)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to a new [`MediaKeys`](mediakeys) object.

  [`MediaKeySystemAccess.getConfiguration()`](mediakeysystemaccess/getconfiguration)  Returns an object with the supported combination of configuration options.

  
Specifications
--------------




| Specification |
| --- |
| [Encrypted Media Extensions # mediakeysystemaccess-interface](https://w3c.github.io/encrypted-media/#mediakeysystemaccess-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaKeySystemAccess` | 42 | 13 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |
| `createMediaKeys` | 42 | 13 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |
| `getConfiguration` | 42 | 13 | 43Before Firefox 50, the returned object has neither a `distinctiveIdentifier` nor a `persistentState` property. | No | 29 | 12.1 | 43 | 42 | 43Before Firefox 50, the returned object has neither a `distinctiveIdentifier` nor a `persistentState` property. | 29 | 12.2 | 4.0 |
| `keySystem` | 42 | 13 | 38 | No | 29 | 12.1 | 43 | 42 | 38 | 29 | 12.2 | 4.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess>

MediaList
=========



The `MediaList` interface represents the media queries of a stylesheet, e.g. those set using a [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link) element's `media` attribute.

  **Note:** `MediaList` is a live list; updating the list using properties or methods listed below will immediately update the behavior of the document.

 

Instance properties
-------------------


 [`MediaList.mediaText`](medialist/mediatext)  A [stringifier](https://developer.mozilla.org/en-US/docs/Glossary/Stringifier) that returns a string representing the `MediaList` as text, and also allows you to set a new `MediaList`.

  
[`MediaList.length`](medialist/length) Read only 
  Returns the number of media queries in the `MediaList`.

  
Instance methods
----------------


 [`MediaList.appendMedium()`](medialist/appendmedium)  Adds a media query to the `MediaList`.

  [`MediaList.deleteMedium()`](medialist/deletemedium)  Removes a media query from the `MediaList`.

  [`MediaList.item()`](medialist/item)  A getter that returns a string representing a media query as text, given the media query's index value inside the `MediaList`. This method can also be called using the bracket (`[]`) syntax.

  
Examples
--------



The following would log to the console a textual representation of the `MediaList` of the first stylesheet applied to the current document.

 
```
const stylesheets = document.styleSheets;
let stylesheet = stylesheets[0];
console.log(stylesheet.media.mediaText);

```


Specifications
--------------




| Specification |
| --- |
| [CSS Object Model (CSSOM) # the-medialist-interface](https://w3c.github.io/csswg-drafts/cssom/#the-medialist-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaList` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `appendMedium` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `deleteMedium` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `item` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `length` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `mediaText` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `toString` | 1 | 12 | 1 | No | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | ≤3 | 1.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaList>

MediaQueryList
==============



A `MediaQueryList` object stores information on a [media query](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries) applied to a document, with support for both immediate and event-driven matching against the state of the document.

 You can create a `MediaQueryList` by calling [`matchMedia()`](window/matchmedia) on the [`window`](window) object. The resulting object handles sending notifications to listeners when the media query state changes (i.e. when the media query test starts or stops evaluating to `true`).

 This is very useful for adaptive design, since this makes it possible to observe a document to detect when its media queries change, instead of polling the values periodically, and allows you to programmatically make changes to a document based on media query status.


 EventTarget MediaQueryList

Instance properties
-------------------



*The `MediaQueryList` interface inherits properties from its parent interface, [`EventTarget`](eventtarget).*

  
[`matches`](mediaquerylist/matches) Read only 
  A boolean value that returns `true` if the [`document`](document) currently matches the media query list, or `false` if not.

  
[`media`](mediaquerylist/media) Read only 
  A string representing a serialized media query.

  

Instance methods
----------------



*The `MediaQueryList` interface inherits methods from its parent interface, [`EventTarget`](eventtarget).*

  
[`addListener()`](mediaquerylist/addlistener)  Deprecated 
  Adds to the `MediaQueryList` a callback which is invoked whenever the media query status—whether or not the document matches the media queries in the list—changes. This method exists primarily for backward compatibility; if possible, you should instead use [`addEventListener()`](eventtarget/addeventlistener) to watch for the [`change`](mediaquerylist/change_event) event.

  
[`removeListener()`](mediaquerylist/removelistener)  Deprecated 
  Removes the specified listener callback from the callbacks to be invoked when the `MediaQueryList` changes media query status, which happens any time the document switches between matching and not matching the media queries listed in the `MediaQueryList`. This method has been kept for backward compatibility; if possible, you should generally use [`removeEventListener()`](eventtarget/removeeventlistener) to remove change notification callbacks (which should have previously been added using `addEventListener()`).

  

Events
------



*The following events are delivered to `MediaQueryList` objects:*

  [`change`](mediaquerylist/change_event)  Sent to the `MediaQueryList` when the result of running the media query against the document changes. For example, if the media query is `(min-width: 400px)`, the `change` event is fired any time the width of the document's [viewport](https://developer.mozilla.org/en-US/docs/Glossary/Viewport) changes such that its width moves across the 400px boundary in either direction.

  

Examples
--------



This simple example creates a `MediaQueryList` and then sets up a listener to detect when the media query status changes, running a custom function when it does to change the appearance of the page.

 
```
const para = document.querySelector("p");
const mql = window.matchMedia("(max-width: 600px)");

function screenTest(e) {
  if (e.matches) {
    /\* the viewport is 600 pixels wide or less \*/
    para.textContent = "This is a narrow screen — less than 600px wide.";
    document.body.style.backgroundColor = "red";
  } else {
    /\* the viewport is more than 600 pixels wide \*/
    para.textContent = "This is a wide screen — more than 600px wide.";
    document.body.style.backgroundColor = "blue";
  }
}

mql.addEventListener("change", screenTest);

```
  **Note:** You can find this example on GitHub (see the [source code](https://github.com/mdn/dom-examples/blob/main/mediaquerylist/index.html), and also see it [running live](https://mdn.github.io/dom-examples/mediaquerylist/index.html)).

  You can find other examples on the individual property and method pages.



Specifications
--------------




| Specification |
| --- |
| [CSSOM View Module # the-mediaquerylist-interface](https://w3c.github.io/csswg-drafts/cssom-view/#the-mediaquerylist-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `EventTarget_inheritance` | 39 | 16 | 55 | No | 26 | 14 | 39 | 39 | 55 | 26 | 14 | 4.0 |
| `MediaQueryList` | 9 | 12 | 6 | 10 | 12.1 | 5.1 | ≤37 | 18 | 6 | 12.1 | 5 | 1.0 |
| `addListener` | 9 | 12 | 6 | 10 | 12.1 | 5.1 | ≤37 | 18 | 6 | 12.1 | 5 | 1.0 |
| `change_event` | 39 | 79 | 55 | No | 26 | 14 | 39 | 39 | 55 | 26 | 14 | 4.0 |
| `matches` | 9 | 12 | 6 | 10 | 12.1 | 5.1 | ≤37 | 18 | 6 | 12.1 | 5 | 1.0 |
| `media` | 9 | 12 | 6 | 10 | 12.1 | 5.1 | ≤37 | 18 | 6 | 12.1 | 5 | 1.0 |
| `removeListener` | 9 | 12 | 6 | 10 | 12.1 | 5.1Before Safari 14, `MediaQueryList` is based on `EventTarget`, so you must use `addListener()` and `removeListener()` to observe media query lists. | ≤37 | 18 | 6 | 12.1 | 5Before Safari 14, `MediaQueryList` is based on `EventTarget`, so you must use `addListener()` and `removeListener()` to observe media query lists. | 1.0 |


See also
--------


* [Media queries](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries)
* [Using media queries from code](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Testing_media_queries)
* [`window.matchMedia()`](window/matchmedia)
* [`MediaQueryListEvent`](mediaquerylistevent)
* The article [`Window.devicePixelRatio`](window/devicepixelratio) also has a useful example


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList>

MediaKeyMessageEvent
====================



The `MediaKeyMessageEvent` interface of the [Encrypted Media Extensions API](encrypted_media_extensions_api) contains the content and related data when the content decryption module generates a message for the session.


 Event MediaKeyMessageEvent

Constructor
-----------


 [`MediaKeyMessageEvent()`](mediakeymessageevent/mediakeymessageevent)  Creates a new instance of `MediaKeyMessageEvent`.

  
Instance properties
-------------------



Inherits properties from its parent, [`Event`](event).

  
[`MediaKeyMessageEvent.message`](mediakeymessageevent/message) Read only 
  Returns an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) with a message from the content decryption module. Messages vary by key system.

  
[`MediaKeyMessageEvent.messageType`](mediakeymessageevent/messagetype) Read only 
  Indicates the type of message. May be one of `license-request`, `license-renewal`, `license-release`, or `individualization-request`.

  

Instance methods
----------------


Inherits methods from its parent, [`Event`](event).


Examples
--------



```
// TBD

```

Specifications
--------------




| Specification |
| --- |
| [Encrypted Media Extensions # mediakeymessageevent](https://w3c.github.io/encrypted-media/#mediakeymessageevent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaKeyMessageEvent` | 42 | 13 | 38 | No | 29 | 12.1 | 42 | 42 | 38 | 29 | 12.2 | 4.0 |
| `MediaKeyMessageEvent` | 42 | 13 | 38 | No | 29 | 12.1 | 42 | 42 | 38 | 29 | 12.2 | 4.0 |
| `message` | 42 | 13 | 38 | No | 29 | 12.1 | 42 | 42 | 38 | 29 | 12.2 | 4.0 |
| `messageType` | 42 | 13 | 38 | No | 29 | 12.1 | 42 | 42 | 38 | 29 | 12.2 | 4.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaKeyMessageEvent>

MediaMetadata
=============


The `MediaMetadata` interface of the [Media Session API](media_session_api) allows a web page to provide rich media metadata for display in a platform UI.


Constructor
-----------


 [`MediaMetadata()`](mediametadata/mediametadata)  Creates a new `MediaMetaData` object.

  
Instance properties
-------------------


 [`MediaMetadata.title`](mediametadata/title)  Returns or sets the title of the media to be played.

  [`MediaMetadata.artist`](mediametadata/artist)  Returns or sets the name of the artist, group, creator, etc. of the media to be played.

  [`MediaMetadata.album`](mediametadata/album)  Returns or sets the name of the album or collection containing the media to be played.

  [`MediaMetadata.artwork`](mediametadata/artwork)  Returns or sets an array of images associated with playing media.

  
Examples
--------



The following example checks for browser compatibility and sets the current metadata for the media session.

 
```
if ("mediaSession" in navigator) {
  navigator.mediaSession.metadata = new MediaMetadata({
    title: "Unforgettable",
    artist: "Nat King Cole",
    album: "The Ultimate Collection (Remastered)",
    artwork: [
      {
        src: "https://dummyimage.com/96x96",
        sizes: "96x96",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/128x128",
        sizes: "128x128",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/192x192",
        sizes: "192x192",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/256x256",
        sizes: "256x256",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/384x384",
        sizes: "384x384",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/512x512",
        sizes: "512x512",
        type: "image/png",
      },
    ],
  });
}

```


Specifications
--------------




| Specification |
| --- |
| [Media Session Standard # the-mediametadata-interface](https://w3c.github.io/mediasession/#the-mediametadata-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaMetadata` | 57 | 79 | 82 | No | 44 | 15 | No | 57 | 82 | 43 | 15 | 7.0 |
| `MediaMetadata` | 57 | 79 | 82 | No | 44 | 15 | No | 57 | 82Firefox exposes the API, but does not provide a corresponding user-facing media control interface. | 43 | 15 | 7.0 |
| `album` | 57 | 79 | 82 | No | 44 | 15 | No | 57 | 82 | 43 | 15 | 7.0 |
| `artist` | 57 | 79 | 82 | No | 44 | 15 | No | 57 | 82 | 43 | 15 | 7.0 |
| `artwork` | 57 | 79 | 82 | No | 44 | 15 | No | 57 | 82 | 43 | 15 | 7.0 |
| `title` | 57 | 79 | 82 | No | 44 | 15 | No | 57 | 82 | 43 | 15 | 7.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaMetadata>

MediaRecorder
=============



The `MediaRecorder` interface of the [MediaStream Recording API](mediastream_recording_api) provides functionality to easily record media. It is created using the [`MediaRecorder()`](mediarecorder/mediarecorder) constructor.


 EventTarget MediaRecorder

Constructor
-----------


 [`MediaRecorder()`](mediarecorder/mediarecorder)  Creates a new `MediaRecorder` object, given a [`MediaStream`](mediastream) to record. Options are available to do things like set the container's MIME type (such as `"video/webm"` or `"video/mp4"`) and the bit rates of the audio and video tracks or a single overall bit rate.

  
Instance properties
-------------------


 
[`MediaRecorder.mimeType`](mediarecorder/mimetype) Read only 
  Returns the MIME type that was selected as the recording container for the `MediaRecorder` object when it was created.

  
[`MediaRecorder.state`](mediarecorder/state) Read only 
  Returns the current state of the `MediaRecorder` object (`inactive`, `recording`, or `paused`.)

  
[`MediaRecorder.stream`](mediarecorder/stream) Read only 
  Returns the stream that was passed into the constructor when the `MediaRecorder` was created.

  
[`MediaRecorder.videoBitsPerSecond`](mediarecorder/videobitspersecond) Read only 
  Returns the video encoding bit rate in use. This may differ from the bit rate specified in the constructor (if it was provided).

  
[`MediaRecorder.audioBitsPerSecond`](mediarecorder/audiobitspersecond) Read only 
  Returns the audio encoding bit rate in use. This may differ from the bit rate specified in the constructor (if it was provided).

  
Static methods
--------------


 [`MediaRecorder.isTypeSupported()`](mediarecorder/istypesupported)  A static method which returns a `true` or `false` value indicating if the given MIME media type is supported by the current user agent.

  
Instance methods
----------------


 [`MediaRecorder.pause()`](mediarecorder/pause)  Pauses the recording of media.

  [`MediaRecorder.requestData()`](mediarecorder/requestdata)  Requests a [`Blob`](blob) containing the saved data received thus far (or since the last time `requestData()` was called. After calling this method, recording continues, but in a new `Blob`.

  [`MediaRecorder.resume()`](mediarecorder/resume)  Resumes recording of media after having been paused.

  [`MediaRecorder.start()`](mediarecorder/start)  Begins recording media; this method can optionally be passed a `timeslice` argument with a value in milliseconds. If this is specified, the media will be captured in separate chunks of that duration, rather than the default behavior of recording the media in a single large chunk.

  [`MediaRecorder.stop()`](mediarecorder/stop)  Stops recording, at which point a [`dataavailable`](mediarecorder/dataavailable_event) event containing the final `Blob` of saved data is fired. No more recording occurs.

  
Events
------



Listen to these events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface.

  [`dataavailable`](mediarecorder/dataavailable_event)  Fires periodically each time `timeslice` milliseconds of media have been recorded (or when the entire media has been recorded, if `timeslice` wasn't specified). The event, of type [`BlobEvent`](blobevent), contains the recorded media in its [`data`](blobevent/data) property.

  [`error`](mediarecorder/error_event)  Fired when there are fatal errors that stop recording. The received event is based on the [`MediaRecorderErrorEvent`](mediarecordererrorevent) interface, whose [`error`](mediarecordererrorevent/error) property contains a [`DOMException`](domexception) that describes the actual error that occurred.

  [`pause`](mediarecorder/pause_event)  Fired when media recording is paused.

  [`resume`](mediarecorder/resume_event)  Fired when media recording resumes after being paused.

  [`start`](mediarecorder/start_event)  Fired when media recording starts.

  [`stop`](mediarecorder/stop_event)  Fired when media recording ends, either when the [`MediaStream`](mediastream) ends, or after the [`MediaRecorder.stop()`](mediarecorder/stop) method is called.

  
[`warning`](mediarecorder/warning_event)  Deprecated 
  Fired when media recording has a non-fatal error, or after the [`MediaRecorder.onwarning()`](mediarecorder/warning_event) method is called.

  

Example
-------




```
if (navigator.mediaDevices) {
  console.log("getUserMedia supported.");

  const constraints = { audio: true };
  let chunks = [];

  navigator.mediaDevices
    .getUserMedia(constraints)
    .then((stream) => {
      const mediaRecorder = new MediaRecorder(stream);

      visualize(stream);

      record.onclick = () => {
        mediaRecorder.start();
        console.log(mediaRecorder.state);
        console.log("recorder started");
        record.style.background = "red";
        record.style.color = "black";
      };

      stop.onclick = () => {
        mediaRecorder.stop();
        console.log(mediaRecorder.state);
        console.log("recorder stopped");
        record.style.background = "";
        record.style.color = "";
      };

      mediaRecorder.onstop = (e) => {
        console.log("data available after MediaRecorder.stop() called.");

        const clipName = prompt("Enter a name for your sound clip");

        const clipContainer = document.createElement("article");
        const clipLabel = document.createElement("p");
        const audio = document.createElement("audio");
        const deleteButton = document.createElement("button");

        clipContainer.classList.add("clip");
        audio.setAttribute("controls", "");
        deleteButton.textContent = "Delete";
        clipLabel.textContent = clipName;

        clipContainer.appendChild(audio);
        clipContainer.appendChild(clipLabel);
        clipContainer.appendChild(deleteButton);
        soundClips.appendChild(clipContainer);

        audio.controls = true;
        const blob = new Blob(chunks, { type: "audio/ogg; codecs=opus" });
        chunks = [];
        const audioURL = URL.createObjectURL(blob);
        audio.src = audioURL;
        console.log("recorder stopped");

        deleteButton.onclick = (e) => {
          const evtTgt = e.target;
          evtTgt.parentNode.parentNode.removeChild(evtTgt.parentNode);
        };
      };

      mediaRecorder.ondataavailable = (e) => {
        chunks.push(e.data);
      };
    })
    .catch((err) => {
      console.error(`The following error occurred: ${err}`);
    });
}

```
  **Note:** This code sample is inspired by the Web Dictaphone demo. Some lines have been omitted for brevity; [refer to the source](https://github.com/mdn/dom-examples/tree/main/media/web-dictaphone) for the complete code.

 

Specifications
--------------




| Specification |
| --- |
| [MediaStream Recording # mediarecorder-api](https://w3c.github.io/mediacapture-record/#mediarecorder-api) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaRecorder` | 47 | 79 | 25 | No | 36 | 14 | 47 | 47 | 25 | 36 | 14 | 5.0 |
| `MediaRecorder` | 47 | 79 | 25Before Firefox 58, using `MediaStream.addTrack()` on a stream obtained using `getUserMedia()`, then attempting to record the resulting stream would result in only recording the original stream without the added tracks (severe bug). | No | 36 | 14 | 47 | 47 | 25Before Firefox 58, using `MediaStream.addTrack()` on a stream obtained using `getUserMedia()`, then attempting to record the resulting stream would result in only recording the original stream without the added tracks (severe bug). | 36 | 14 | 5.0 |
| `audioBitrateMode` | 89 | 89 | No | No | 75 | No | 89 | 89 | No | 63 | No | 15.0 |
| `audioBitsPerSecond` | 49 | 79 | 71 | No | 36 | 14.1 | 49 | 49 | 79 | 36 | 14.5 | 5.0 |
| `dataavailable_event` | 49 | 79 | 25 | No | 36 | 14 | 49 | 49 | 25 | 36 | 14 | 5.0 |
| `error_event` | 49The interface for this event is a plain [`Event`](https://developer.mozilla.org/docs/Web/API/Event), not [`MediaRecorderErrorEvent`](https://developer.mozilla.org/docs/Web/API/MediaRecorderErrorEvent). See [bug 1250432](https://crbug.com/1250432). | 79The interface for this event is a plain [`Event`](https://developer.mozilla.org/docs/Web/API/Event), not [`MediaRecorderErrorEvent`](https://developer.mozilla.org/docs/Web/API/MediaRecorderErrorEvent). See [bug 1250432](https://crbug.com/1250432). | 25 | No | 36The interface for this event is a plain [`Event`](https://developer.mozilla.org/docs/Web/API/Event), not [`MediaRecorderErrorEvent`](https://developer.mozilla.org/docs/Web/API/MediaRecorderErrorEvent). See [bug 1250432](https://crbug.com/1250432). | 14 | 49The interface for this event is a plain [`Event`](https://developer.mozilla.org/docs/Web/API/Event), not [`MediaRecorderErrorEvent`](https://developer.mozilla.org/docs/Web/API/MediaRecorderErrorEvent). See [bug 1250432](https://crbug.com/1250432). | 49The interface for this event is a plain [`Event`](https://developer.mozilla.org/docs/Web/API/Event), not [`MediaRecorderErrorEvent`](https://developer.mozilla.org/docs/Web/API/MediaRecorderErrorEvent). See [bug 1250432](https://crbug.com/1250432). | 25 | 36The interface for this event is a plain [`Event`](https://developer.mozilla.org/docs/Web/API/Event), not [`MediaRecorderErrorEvent`](https://developer.mozilla.org/docs/Web/API/MediaRecorderErrorEvent). See [bug 1250432](https://crbug.com/1250432). | 14 | 5.0The interface for this event is a plain [`Event`](https://developer.mozilla.org/docs/Web/API/Event), not [`MediaRecorderErrorEvent`](https://developer.mozilla.org/docs/Web/API/MediaRecorderErrorEvent). See [bug 1250432](https://crbug.com/1250432). |
| `isTypeSupported` | 47 | 79 | 25 | No | 36 | 14 | 47 | 47 | 25 | 36 | 14 | 5.0 |
| `mimeType` | 4947–49Before Chrome 49, only video is supported, not audio. | 79 | 25Starting with Firefox 71, the behavior of `mimeType` is more consistent. For example, it now returns the media type even after recording has stopped. | No | 36 | 14 | 4947–49Before Chrome 49, only video is supported, not audio. | 4947–49Before Chrome 49, only video is supported, not audio. | 25 | 36 | 14 | 5.0 |
| `pause` | 49 | 79 | 25 | No | 36 | 14.1 | 49 | 49 | 25 | 36 | 14.5 | 5.0 |
| `pause_event` | 49 | 79 | 65 | No | 36 | 14.1 | 49 | 49 | 65 | 36 | 14.5 | 5.0 |
| `requestData` | 49 | 79 | 25 | No | 36 | 14 | 49 | 49 | 25 | 36 | 14 | 5.0 |
| `resume` | 49 | 79 | 25 | No | 36 | 14.1 | 49 | 49 | 25 | 36 | 14.5 | 5.0 |
| `resume_event` | 49 | 79 | 65 | No | 36 | 14.1 | 49 | 49 | 65 | 36 | 14.5 | 5.0 |
| `start` | 47 | 79 | 25 | No | 36 | 14 | 47 | 47 | 25 | 36 | 14 | 5.0 |
| `start_event` | 49 | 79 | 25 | No | 36 | 14 | 49 | 49 | 25 | 36 | 14 | 5.0 |
| `state` | 4947–49Before Chrome 49, only video is supported, not audio. | 79 | 25 | No | 36 | 14 | 4947–49Before Chrome 49, only video is supported, not audio. | 4947–49Before Chrome 49, only video is supported, not audio. | 25 | 36 | 14 | 5.0 |
| `stop` | 49 | 79 | 25 | No | 36 | 14 | 49 | 49 | 25 | 36 | 14 | 5.0 |
| `stop_event` | 49 | 79 | 25 | No | 36 | 14 | 49 | 49 | 25 | 36 | 14 | 5.0 |
| `stream` | 4947–49Before Chrome 49, only video is supported, not audio. | 79 | 25 | No | 36 | 14 | 49 | 4947–49Before Chrome 49, only video is supported, not audio. | 25 | 36 | 14 | 5.0 |
| `videoBitsPerSecond` | 49 | 79 | 71 | No | 36 | 14.1 | 49 | 49 | 79 | 36 | 14.5 | 5.0 |
| `warning_event` | 49 | 79 | 25–71 | No | 36 | No | 49 | 49 | 25 | 36 | No | 5.0 |


See also
--------


* [Using the MediaStream Recording API](mediastream_recording_api/using_the_mediastream_recording_api)
* [Web Dictaphone](https://mdn.github.io/dom-examples/media/web-dictaphone/): MediaRecorder + getUserMedia + Web Audio API visualization demo, by [Chris Mills](https://twitter.com/chrisdavidmills) ([source on GitHub](https://github.com/mdn/dom-examples/tree/main/media/web-dictaphone).)
* [Recording a media element](mediastream_recording_api/recording_a_media_element)
* [simpl.info MediaStream Recording demo](https://simpl.info/mediarecorder/), by [Sam Dutton](https://twitter.com/sw12).
* [`MediaDevices.getUserMedia`](mediadevices/getusermedia)
* [OpenLang](https://github.com/chrisjohndigital/OpenLang): HTML video language lab web application using MediaDevices and the MediaStream Recording API for video recording ([source on GitHub](https://github.com/chrisjohndigital/OpenLang))


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder>

MediaStream
===========



The `MediaStream` interface represents a stream of media content. A stream consists of several **tracks**, such as video or audio tracks. Each track is specified as an instance of [`MediaStreamTrack`](mediastreamtrack).

 You can obtain a `MediaStream` object either by using the constructor or by calling functions such as [`MediaDevices.getUserMedia()`](mediadevices/getusermedia), [`MediaDevices.getDisplayMedia()`](mediadevices/getdisplaymedia), or [`HTMLCanvasElement.captureStream()`](htmlcanvaselement/capturestream).

 Some user agents subclass this interface to provide more precise information or functionality, like in [`CanvasCaptureMediaStreamTrack`](canvascapturemediastreamtrack).


 EventTarget MediaStream

Constructor
-----------


 [`MediaStream()`](mediastream/mediastream)  Creates and returns a new MediaStream object. You can create an empty stream, a stream which is based upon an existing stream, or a stream that contains a specified list of tracks (specified as an array of [`MediaStreamTrack`](mediastreamtrack) objects).

  
Instance properties
-------------------



*This interface inherits properties from its parent, [`EventTarget`](eventtarget).*

  
[`MediaStream.active`](mediastream/active) Read only 
  A Boolean value that returns `true` if the `MediaStream` is active, or `false` otherwise.

  
[`MediaStream.id`](mediastream/id) Read only 
  A string containing a 36-character universally unique identifier ([UUID](https://developer.mozilla.org/en-US/docs/Glossary/UUID)) for the object.

  

Instance methods
----------------



*This interface inherits methods from its parent, [`EventTarget`](eventtarget).*

  [`MediaStream.addTrack()`](mediastream/addtrack)  Stores a copy of the [`MediaStreamTrack`](mediastreamtrack) given as argument. If the track has already been added to the `MediaStream` object, nothing happens.

  [`MediaStream.clone()`](mediastream/clone)  Returns a clone of the `MediaStream` object. The clone will, however, have a unique value for [`id`](mediastream/id).

  [`MediaStream.getAudioTracks()`](mediastream/getaudiotracks)  Returns a list of the [`MediaStreamTrack`](mediastreamtrack) objects stored in the `MediaStream` object that have their `kind` attribute set to `audio`. The order is not defined, and may not only vary from one browser to another, but also from one call to another.

  [`MediaStream.getTrackById()`](mediastream/gettrackbyid)  Returns the track whose ID corresponds to the one given in parameters, `trackid`. If no parameter is given, or if no track with that ID does exist, it returns `null`. If several tracks have the same ID, it returns the first one.

  [`MediaStream.getTracks()`](mediastream/gettracks)  Returns a list of all [`MediaStreamTrack`](mediastreamtrack) objects stored in the `MediaStream` object, regardless of the value of the `kind` attribute. The order is not defined, and may not only vary from one browser to another, but also from one call to another.

  [`MediaStream.getVideoTracks()`](mediastream/getvideotracks)  Returns a list of the [`MediaStreamTrack`](mediastreamtrack) objects stored in the `MediaStream` object that have their `kind` attribute set to `"video"`. The order is not defined, and may not only vary from one browser to another, but also from one call to another.

  [`MediaStream.removeTrack()`](mediastream/removetrack)  Removes the [`MediaStreamTrack`](mediastreamtrack) given as argument. If the track is not part of the `MediaStream` object, nothing happens.

  

Events
------


 [`addtrack`](mediastream/addtrack_event)  Fired when a new [`MediaStreamTrack`](mediastreamtrack) object is added.

  [`removetrack`](mediastream/removetrack_event)  Fired when a [`MediaStreamTrack`](mediastreamtrack) object has been removed.

  `active`  Fired when the MediaStream is activated.

  `inactive`  Fired when the MediaStream is inactivated.

  
Specifications
--------------




| Specification |
| --- |
| [Media Capture and Streams # mediastream](https://w3c.github.io/mediacapture-main/#mediastream) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaStream` | 5521 | 7912 | 44 | No | 4215 | 11 | 554.4 | 5525 | 42 | 4214 | 11 | 6.01.5 |
| `MediaStream` | 5521 | 7912 | 15 | No | 4215 | 11 | 554.4 | 5525 | 15 | 4214 | 11 | 6.01.5 |
| `active` | 42 | 12 | 52 | No | 29 | 11 | 42 | 42 | 52 | 29 | 11 | 4.0 |
| `active_event` | 42 | 12 | No | No | 29 | No | 42 | 42 | No | 29 | No | 4.0 |
| `addTrack` | 26 | 12 | 44 | No | No | 11 | 37 | 26 | No | No | 11 | 1.5 |
| `addtrack_event` | 26 | 12 | 50 | No | No | 11 | 4.4 | 26 | 50 | No | 11 | 1.5 |
| `clone` | 35 | 12 | 48 | No | 22 | 11 | 37 | 35 | 48 | 22 | 11 | 3.0 |
| `getAudioTracks` | 26 | 12 | 22Before Firefox 64, this method returned an array of `AudioStreamTrack` objects. However, `MediaStreamTrack` has now subsumed that interface's functionality. | No | 15 | 11 | 37 | 26 | 22Before Firefox 64, this method returned an array of `AudioStreamTrack` objects. However, `MediaStreamTrack` has now subsumed that interface's functionality. | No | 11 | 1.5 |
| `getTrackById` | 26 | 12 | 49 | No | No | 11 | 37 | 26 | 49 | No | 11 | 1.5 |
| `getTracks` | 38 | 12 | 34 | No | 25 | 11 | 38 | 38 | 34 | 25 | 11 | 3.0 |
| `getVideoTracks` | 26 | 12 | 22Before Firefox 64, this method returned an array of `VideoStreamTrack` objects. However, `MediaStreamTrack` has now subsumed that interface's functionality. | No | 15 | 11 | 37 | 26 | 22Before Firefox 64, this method returned an array of `VideoStreamTrack` objects. However, `MediaStreamTrack` has now subsumed that interface's functionality. | No | 11 | 1.5 |
| `id` | 26 | 12 | 41 | No | 15 | 11 | 4.4 | 26 | 41 | 14 | 11 | 1.5 |
| `inactive_event` | 42 | 12 | No | No | 29 | No | 42 | 42 | No | 29 | No | 4.0 |
| `removeTrack` | 26 | 12 | 44 | No | 15 | 11 | 37 | 26 | 44 | No | 11 | 1.5 |
| `removetrack_event` | 26 | 12 | 7259–72Before Firefox 72, the event handler was exposed but had no effect. | No | No | 11 | 4.4 | 26 | 7959–79Before Firefox 72, the event handler was exposed but had no effect. | No | 11 | 1.5 |


See also
--------


* [Using the MediaStream Recording API](mediastream_recording_api/using_the_mediastream_recording_api)
* [WebRTC API](webrtc_api)
* [Web Audio API](web_audio_api)
* [`MediaStreamTrack`](mediastreamtrack)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaStream>

MediaStreamAudioDestinationNode
===============================



The `MediaStreamAudioDestinationNode` interface represents an audio destination consisting of a [WebRTC](webrtc_api) [`MediaStream`](mediastream) with a single `AudioMediaStreamTrack`, which can be used in a similar way to a `MediaStream` obtained from [`navigator.mediaDevices.getUserMedia()`](mediadevices/getusermedia).

 It is an [`AudioNode`](audionode) that acts as an audio destination, created using the [`AudioContext.createMediaStreamDestination()`](audiocontext/createmediastreamdestination) method.


 EventTarget AudioNode MediaStreamAudioDestinationNode 

|  |  |
| --- | --- |
| Number of inputs | `1` |
| Number of outputs | `0` |
| Channel count | `2` |
| Channel count mode | `"explicit"` |
| Channel count interpretation | `"speakers"` |



Constructor
-----------


 [`MediaStreamAudioDestinationNode()`](mediastreamaudiodestinationnode/mediastreamaudiodestinationnode)  Creates a new `MediaStreamAudioDestinationNode` object instance.

  
Instance properties
-------------------



*Inherits properties from its parent, [`AudioNode`](audionode)*.

  [`MediaStreamAudioDestinationNode.stream`](mediastreamaudiodestinationnode/stream)  A [`MediaStream`](mediastream) containing a single [`MediaStreamTrack`](mediastreamtrack) whose [`kind`](mediastreamtrack/kind) is `audio` and with the same number of channels as the node. You can use this property to get a stream out of the audio graph and feed it into another construct, such as a [Media Recorder](mediastream_recording_api).

  

Instance methods
----------------


*Inherits methods from its parent, [`AudioNode`](audionode)*.


Example
-------


See [`AudioContext.createMediaStreamDestination()`](audiocontext/createmediastreamdestination#examples) for example code that creates a `MediaStreamAudioDestinationNode` and uses it as a source for audio to be recorded.


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # MediaStreamAudioDestinationNode](https://webaudio.github.io/web-audio-api/#MediaStreamAudioDestinationNode) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaStreamAudioDestinationNode` | 57 | 79 | 53 | No | 44 | 14.1 | 57 | 57 | 53 | 43 | 14.5 | 7.0 |
| `MediaStreamAudioDestinationNode` | 25 | 18 | 25 | No | 15 | 11 | ≤37 | 25 | 25 | 14 | 11 | 1.5 |
| `stream` | 25 | 18 | 25 | No | 15 | 11 | ≤37 | 25 | 25 | 14 | 11 | 1.5 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamAudioDestinationNode>

MediaQueryListEvent
===================



The `MediaQueryListEvent` object stores information on the changes that have happened to a [`MediaQueryList`](mediaquerylist) object — instances are available as the event object on a function referenced by a [`change`](mediaquerylist/change_event) event.


 Event MediaQueryListEvent

Constructor
-----------


 [`MediaQueryListEvent()`](mediaquerylistevent/mediaquerylistevent)  Creates a new `MediaQueryListEvent` instance.

  
Instance properties
-------------------



*The `MediaQueryListEvent` interface inherits properties from its parent interface, [`Event`](event).*

  
[`MediaQueryListEvent.matches`](mediaquerylistevent/matches) Read only 
  A boolean value that is `true` if the [`document`](document) currently matches the media query list, or `false` if not.

  
[`MediaQueryListEvent.media`](mediaquerylistevent/media) Read only 
  A string representing a serialized media query.

  

Instance methods
----------------


*The `MediaQueryListEvent` interface inherits methods from its parent interface, [`Event`](event).*


Examples
--------



```
const para = document.querySelector("p"); // This is the UI element where to display the text
const mql = window.matchMedia("(max-width: 600px)");

mql.addEventListener("change", (event) => {
  if (event.matches) {
    // The viewport is 600 pixels wide or less
    para.textContent = "This is a narrow screen — less than 600px wide.";
    document.body.style.backgroundColor = "red";
  } else {
    // The viewport is more than 600 pixels wide
    para.textContent = "This is a wide screen — more than 600px wide.";
    document.body.style.backgroundColor = "blue";
  }
});

```

Specifications
--------------




| Specification |
| --- |
| [CSSOM View Module # the-mediaquerylist-interface](https://w3c.github.io/csswg-drafts/cssom-view/#the-mediaquerylist-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaQueryListEvent` | 39 | 79 | 55 | No | 26 | 14 | 39 | 39 | 55 | 26 | 14 | 4.0 |
| `MediaQueryListEvent` | 39 | 79 | 55 | No | 26 | 14 | 39 | 39 | 55 | 26 | 14 | 4.0 |
| `matches` | 39 | 79 | 55 | No | 26 | 14 | 39 | 39 | 55 | 26 | 14 | 4.0 |
| `media` | 39 | 79 | 55 | No | 26 | 14 | 39 | 39 | 55 | 26 | 14 | 4.0 |


See also
--------


* [Media queries](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries)
* [Using media queries from code](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Testing_media_queries)
* [`window.matchMedia()`](window/matchmedia)
* [`MediaQueryList`](mediaquerylist)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryListEvent>

MediaRecorderErrorEvent
=======================



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.


**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The `MediaRecorderErrorEvent` interface represents errors returned by the [MediaStream Recording API.](mediastream_recording_api) It is an [`Event`](event) object that encapsulates a reference to a [`DOMException`](domexception) describing the error that occurred.



Instance properties
-------------------



*Inherits properties from its parent interface, [`Event`](event)*.

  
[`error`](mediarecordererrorevent/error) Read only   Deprecated   Non-standard 
  A [`DOMException`](domexception) containing information about the error that occurred. Read only.

  

Constructor
-----------


 
[`MediaStreamRecorderEvent()`](mediarecordererrorevent/mediarecordererrorevent)  Deprecated   Non-standard 
  Creates and returns a new `MediaRecorderErrorEvent` event object with the given parameters.

  
Instance methods
----------------


*Inherits methods from its parent interface, [`Event`](event)*.


### Specifications


This feature is no longer part of any specification, and longer on track to become standard.


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaRecorderErrorEvent` | No | No | 57 | No | No | 14 | No | No | 57 | No | 14 | No |
| `MediaRecorderErrorEvent` | NoSee [bug 1250432](https://crbug.com/1250432). | NoSee [bug 1250432](https://crbug.com/1250432). | 57 | No | NoSee [bug 1250432](https://crbug.com/1250432). | 14 | NoSee [bug 1250432](https://crbug.com/1250432). | NoSee [bug 1250432](https://crbug.com/1250432). | 57 | NoSee [bug 1250432](https://crbug.com/1250432). | 14 | NoSee [bug 1250432](https://crbug.com/1250432). |
| `error` | No | No | 57 | No | No | 14 | No | No | 57 | No | 14 | No |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorderErrorEvent>

MediaSession
============



The `MediaSession` interface of the [Media Session API](media_session_api) allows a web page to provide custom behaviors for standard media playback interactions, and to report metadata that can be sent by the user agent to the device or operating system for presentation in standardized user interface elements.

 For example, a smartphone might have a standard panel in its lock screen that provides controls for media playback and information display. A browser on the device can use `MediaSession` to make browser playback controllable from that standard/global user interface.



Instance properties
-------------------


 [`metadata`](mediasession/metadata)  Returns an instance of [`MediaMetadata`](mediametadata), which contains rich media metadata for display in a platform UI.

  [`playbackState`](mediasession/playbackstate)  Indicates whether the current media session is playing. Valid values are `none`, `paused`, or `playing`.

  
Instance methods
----------------


 [`setActionHandler()`](mediasession/setactionhandler)  Sets an action handler for a media session action, such as play or pause.

  [`setPositionState()`](mediasession/setpositionstate)  Sets the current playback position and speed of the media currently being presented.

  
Examples
--------


### Setting up action handlers for a music player



The following example creates a new media session and assigns action handlers to it:

 
```
if ("mediaSession" in navigator) {
  navigator.mediaSession.metadata = new MediaMetadata({
    title: "Unforgettable",
    artist: "Nat King Cole",
    album: "The Ultimate Collection (Remastered)",
    artwork: [
      {
        src: "https://dummyimage.com/96x96",
        sizes: "96x96",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/128x128",
        sizes: "128x128",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/192x192",
        sizes: "192x192",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/256x256",
        sizes: "256x256",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/384x384",
        sizes: "384x384",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/512x512",
        sizes: "512x512",
        type: "image/png",
      },
    ],
  });

  navigator.mediaSession.setActionHandler("play", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("pause", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("stop", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("seekbackward", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("seekforward", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("seekto", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("previoustrack", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("nexttrack", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("skipad", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("togglecamera", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("togglemicrophone", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("hangup", () => {
    /\* Code excerpted. \*/
  });
}

```
 The following example sets up two functions for playing and pausing, then uses them as callbacks with the relevant action handlers.

 
```
const actionHandlers = [
  // play
  [
    "play",
    async () => {
      // play our audio
      await audioEl.play();
      // set playback state
      navigator.mediaSession.playbackState = "playing";
      // update our status element
      updateStatus(allMeta[index], "Action: play | Track is playing…");
    },
  ],
  [
    "pause",
    () => {
      // pause out audio
      audioEl.pause();
      // set playback state
      navigator.mediaSession.playbackState = "paused";
      // update our status element
      updateStatus(allMeta[index], "Action: pause | Track has been paused…");
    },
  ],
];

for (const [action, handler] of actionHandlers) {
  try {
    navigator.mediaSession.setActionHandler(action, handler);
  } catch (error) {
    console.log(`The media session action "${action}" is not supported yet.`);
  }
}

```


### Using action handlers to control a slide presentation



The `"previousslide"` and `"nextslide"` action handlers can be used to handle moving forward and backward through a slide presentation, for example when the user puts their presentation into a [Picture-in-Picture](picture-in-picture_api) window, and presses the browser-supplied controls for navigating through slides.

 
```
try {
  navigator.mediaSession.setActionHandler("previousslide", () => {
    log('> User clicked "Previous Slide" icon.');
    if (slideNumber > 1) slideNumber--;
    updateSlide();
  });
} catch (error) {
  log('Warning! The "previousslide" media session action is not supported.');
}

try {
  navigator.mediaSession.setActionHandler("nextslide", () => {
    log('> User clicked "Next Slide" icon.');
    slideNumber++;
    updateSlide();
  });
} catch (error) {
  log('Warning! The "nextslide" media session action is not supported.');
}

```
 See [Presenting Slides / Media Session Sample](https://googlechrome.github.io/samples/media-session/slides.html) for a working example.



Specifications
--------------




| Specification |
| --- |
| [Media Session Standard # the-mediasession-interface](https://w3c.github.io/mediasession/#the-mediasession-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaSession` | 73 | 79 | 82 | No | 60 | 15 | No | 57 | 82Firefox exposes the API, but does not provide a corresponding user-facing media control interface. | 43 | 15 | 7.0 |
| `metadata` | 73 | 79 | 82 | No | 60 | 15 | No | 57 | 82Firefox exposes the API, but does not provide a corresponding user-facing media control interface. | 43 | 15 | 7.0 |
| `playbackState` | 73 | 79 | 82 | No | 60 | 15 | No | 57 | 82Firefox exposes the API, but does not provide a corresponding user-facing media control interface. | 43 | 15 | 7.0 |
| `setActionHandler` | 73 | 79 | 82Firefox does not support the `togglemicrophone`, `togglecamera`, and `hangup` action types. | No | 60 | 15Safari does not support for the `togglemicrophone`, `togglecamera`, and `hangup` action types. | No | 57 | 82Firefox exposes the API, but does not provide a corresponding user-facing media control interface. | 43 | 15Safari does not support for the `togglemicrophone`, `togglecamera`, and `hangup` action types. | 7.0 |
| `setCameraActive` | 93 | 93 | No | No | 79 | No | No | 93 | No | 66 | No | 17.0 |
| `setMicrophoneActive` | 93 | 93 | No | No | 79 | No | No | 93 | No | 66 | No | 17.0 |
| `setPositionState` | 81 | 81 | 82 | No | 68 | 15 | No | 57 | 82Firefox exposes the API, but does not provide a corresponding user-facing media control interface. | 43 | 15 | 7.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaSession>

MediaSource
===========



The `MediaSource` interface of the [Media Source Extensions API](media_source_extensions_api) represents a source of media data for an [`HTMLMediaElement`](htmlmediaelement) object. A `MediaSource` object can be attached to a [`HTMLMediaElement`](htmlmediaelement) to be played in the user agent.


 EventTarget MediaSource

Constructor
-----------


 [`MediaSource()`](mediasource/mediasource)  Constructs and returns a new `MediaSource` object with no associated source buffers.

  
Instance properties
-------------------


 
[`MediaSource.activeSourceBuffers`](mediasource/activesourcebuffers) Read only 
  Returns a [`SourceBufferList`](sourcebufferlist) object containing a subset of the [`SourceBuffer`](sourcebuffer) objects contained within [`MediaSource.sourceBuffers`](mediasource/sourcebuffers) — the list of objects providing the selected video track, enabled audio tracks, and shown/hidden text tracks.

  [`MediaSource.duration`](mediasource/duration)  Gets and sets the duration of the current media being presented.

  
[`MediaSource.handle`](mediasource/handle) Read only   Experimental 
  Inside a dedicated worker, returns a [`MediaSourceHandle`](mediasourcehandle) object, a proxy for the `MediaSource` that can be transferred from the worker back to the main thread and attached to a media element via its [`HTMLMediaElement.srcObject`](htmlmediaelement/srcobject) property.

  
[`MediaSource.readyState`](mediasource/readystate) Read only 
  Returns an enum representing the state of the current `MediaSource`, whether it is not currently attached to a media element (`closed`), attached and ready to receive [`SourceBuffer`](sourcebuffer) objects (`open`), or attached but the stream has been ended via [`MediaSource.endOfStream()`](mediasource/endofstream) (`ended`.)

  
[`MediaSource.sourceBuffers`](mediasource/sourcebuffers) Read only 
  Returns a [`SourceBufferList`](sourcebufferlist) object containing the list of [`SourceBuffer`](sourcebuffer) objects associated with this `MediaSource`.

  
Static properties
-----------------


 
[`MediaSource.canConstructInDedicatedWorker`](mediasource/canconstructindedicatedworker) Read only   Experimental 
  A boolean; returns `true` if `MediaSource` worker support is implemented, providing a low-latency feature detection mechanism.

  
Instance methods
----------------



*Inherits methods from its parent interface, [`EventTarget`](eventtarget).*

  [`MediaSource.addSourceBuffer()`](mediasource/addsourcebuffer)  Creates a new [`SourceBuffer`](sourcebuffer) of the given MIME type and adds it to the [`MediaSource.sourceBuffers`](mediasource/sourcebuffers) list.

  [`MediaSource.clearLiveSeekableRange()`](mediasource/clearliveseekablerange)  Clears a seekable range previously set with a call to `setLiveSeekableRange()`.

  [`MediaSource.endOfStream()`](mediasource/endofstream)  Signals the end of the stream.

  [`MediaSource.removeSourceBuffer()`](mediasource/removesourcebuffer)  Removes the given [`SourceBuffer`](sourcebuffer) from the [`MediaSource.sourceBuffers`](mediasource/sourcebuffers) list.

  [`MediaSource.setLiveSeekableRange()`](mediasource/setliveseekablerange)  Sets the range that the user can seek to in the media element.

  

Static methods
--------------


 [`MediaSource.isTypeSupported()`](mediasource/istypesupported)  Returns a boolean value indicating if the given MIME type is supported by the current user agent — this is, if it can successfully create [`SourceBuffer`](sourcebuffer) objects for that MIME type.

  
Events
------


 `sourceclose`  Fired when the `MediaSource` instance is not attached to a media element anymore.

  `sourceended`  Fired when the `MediaSource` instance is still attached to a media element, but [`endOfStream()`](mediasource/endofstream) has been called.

  `sourceopen`  Fired when the `MediaSource` instance has been opened by a media element and is ready for data to be appended to the [`SourceBuffer`](sourcebuffer) objects in [`sourceBuffers`](mediasource/sourcebuffers).

  
Examples
--------


### Complete basic example



The following simple example loads a video with [`XMLHttpRequest`](xmlhttprequest), playing it as soon as it can. This example was written by Nick Desaulniers and can be [viewed live here](https://nickdesaulniers.github.io/netfix/demo/bufferAll.html) (you can also [download the source](https://github.com/nickdesaulniers/netfix/blob/gh-pages/demo/bufferAll.html) for further investigation). The function `getMediaSource()`, which is not defined here, returns a `MediaSource`.

 
```
const video = document.querySelector("video");

const assetURL = "frag\_bunny.mp4";
// Need to be specific for Blink regarding codecs
// ./mp4info frag\_bunny.mp4 | grep Codec
const mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
let mediaSource;

if ("MediaSource" in window && MediaSource.isTypeSupported(mimeCodec)) {
  mediaSource = getMediaSource();
  console.log(mediaSource.readyState); // closed
  video.src = URL.createObjectURL(mediaSource);
  mediaSource.addEventListener("sourceopen", sourceOpen);
} else {
  console.error("Unsupported MIME type or codec: ", mimeCodec);
}

function sourceOpen() {
  console.log(this.readyState); // open
  const sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
  fetchAB(assetURL, (buf) => {
    sourceBuffer.addEventListener("updateend", () => {
      mediaSource.endOfStream();
      video.play();
      console.log(mediaSource.readyState); // ended
    });
    sourceBuffer.appendBuffer(buf);
  });
}

function fetchAB(url, cb) {
  console.log(url);
  const xhr = new XMLHttpRequest();
  xhr.open("get", url);
  xhr.responseType = "arraybuffer";
  xhr.onload = () => {
    cb(xhr.response);
  };
  xhr.send();
}

```


### Constructing a `MediaSource` in a dedicated worker and passing it to the main thread



The [`handle`](mediasource/handle) property can be accessed inside a dedicated worker and the resulting [`MediaSourceHandle`](mediasourcehandle) object is then transferred over to the thread that created the worker (in this case the main thread) via a [`postMessage()`](dedicatedworkerglobalscope/postmessage) call:

 
```
// Inside dedicated worker
let mediaSource = new MediaSource();
let handle = mediaSource.handle;
// Transfer the handle to the context that created the worker
postMessage({ arg: handle }, [handle]);

mediaSource.addEventListener("sourceopen", () => {
  // Await sourceopen on MediaSource before creating SourceBuffers
  // and populating them with fetched media — MediaSource won't
  // accept creation of SourceBuffers until it is attached to the
  // HTMLMediaElement and its readyState is "open"
});

```
 Over in the main thread, we receive the handle via a [`message`](worker/message_event) event handler, attach it to a [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) via its [`HTMLMediaElement.srcObject`](htmlmediaelement/srcobject) property, and [`play`](htmlmediaelement/play) the video:

 
```
worker.addEventListener("message", (msg) => {
  let mediaSourceHandle = msg.data.arg;
  video.srcObject = mediaSourceHandle;
  video.play();
});

```
  **Note:** [`MediaSourceHandle`](mediasourcehandle)s cannot be successfully transferred into or via a shared worker or service worker.

 

Specifications
--------------




| Specification |
| --- |
| [Media Source Extensions™ # mediasource](https://w3c.github.io/media-source/#mediasource) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaSource` | 3123–31 | 12 | 42 | 11Only works on Windows 8+. | 15 | 8 | 4.4.3 | 33 | 41 | 14 | 13Exposed in Mobile Safari on iPad but not on iPhone. | 2.0 |
| `MediaSource` | 3123–31 | 12 | 42 | 11 | 1815–18 | 8 | 4.4.34.4–4.4.3 | 3125–31 | 41 | 1814–18 | 13Exposed in Mobile Safari on iPad but not on iPhone. | 2.01.5–2.0 |
| `activeSourceBuffers` | 23 | 12 | 42 | 11Only works on Windows 8+. | 15 | 8 | 4.4.3 | 25 | 41 | 14 | 13Exposed in Mobile Safari on iPad but not on iPhone. | 1.5 |
| `addSourceBuffer` | 23 | 12 | 42 | 11Only works on Windows 8+. | 15 | 8 | 4.4.3 | 25 | 41 | 14 | 13Exposed in Mobile Safari on iPad but not on iPhone. | 1.5 |
| `canConstructInDedicatedWorker` | 108 | 108 | No | No | 94 | No | 108 | 108 | No | 73 | No | No |
| `clearLiveSeekableRange` | 62 | 17 | 50 | No | 49 | 10.1 | 62 | 62 | 50 | 46 | 13Exposed in Mobile Safari on iPad but not on iPhone. | 8.0 |
| `duration` | 23 | 12 | 42 | 11Only works on Windows 8+. | 15 | 8 | 4.4.3 | 25 | 41 | 14 | 13Exposed in Mobile Safari on iPad but not on iPhone. | 1.5 |
| `endOfStream` | 23 | 12 | 42 | 11Only works on Windows 8+. | 15 | 8 | 4.4.3 | 25 | 41 | 14 | 13Exposed in Mobile Safari on iPad but not on iPhone. | 1.5 |
| `handle` | 108 | 108 | No | No | 94 | No | 108 | 108 | No | 73 | No | No |
| `isTypeSupported` | 23["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 12["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 42Before Firefox 101, `isTypeSupported()` ignored `codecs` parameter options for `av01` codecs (treating them as `av1`). | 11Only works on Windows 8+. | 15["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 8 | 4.4.3["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 25["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 41Before Firefox 101, `isTypeSupported()` ignored `codecs` parameter options for `av01` codecs (treating them as `av1`). | 14["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] | 13Exposed in Mobile Safari on iPad but not on iPhone. | 1.5["`codecs` string can contain any subset of optional parameters (should be all or none).", "Errors if `codecs` string contains unexpected characters (should evaluate string up to character)."] |
| `readyState` | 23 | 12 | 42 | 11Only works on Windows 8+. | 15 | 8 | 4.4.3 | 33 | 41 | 14 | 13Exposed in Mobile Safari on iPad but not on iPhone. | 2.0 |
| `removeSourceBuffer` | 23 | 12 | 42 | 11Only works on Windows 8+. | 15 | 8 | 4.4.3 | 25 | 41 | 14 | 13Exposed in Mobile Safari on iPad but not on iPhone. | 1.5 |
| `setLiveSeekableRange` | 62 | 17 | 50 | No | 49 | 10.1 | 62 | 62 | 50 | 46 | 13Exposed in Mobile Safari on iPad but not on iPhone. | 8.0 |
| `sourceBuffers` | 23 | 12 | 42 | 11Only works on Windows 8+. | 15 | 8 | 4.4.3 | 25 | 41 | 14 | 13Exposed in Mobile Safari on iPad but not on iPhone. | 1.5 |
| `sourceclose_event` | 5331–53The `onsourceclose` event handler property is not supported. | 1712–17The `onsourceclose` event handler property is not supported. | 8742–87The `onsourceclose` event handler property is not supported. | 11Only works on Windows 8+. | 4018–40The `onsourceclose` event handler property is not supported. | 10.18–10.1The `onsourceclose` event handler property is not supported. | 534.4.3–53The `onsourceclose` event handler property is not supported. | 5331–53The `onsourceclose` event handler property is not supported. | 8741–87The `onsourceclose` event handler property is not supported. | 4118–41The `onsourceclose` event handler property is not supported. | 13Exposed in Mobile Safari on iPad but not on iPhone. | 6.02.0–6.0The `onsourceclose` event handler property is not supported. |
| `sourceended_event` | 5331–53The `onsourceended` event handler property is not supported. | 1712–17The `onsourceended` event handler property is not supported. | 42 | 11Only works on Windows 8+. | 4018–40The `onsourceended` event handler property is not supported. | 10.18–10.1The `onsourceended` event handler property is not supported. | 534.4.3–53The `onsourceclose` event handler property is not supported. | 5331–53The `onsourceended` event handler property is not supported. | 41 | 4118–41The `onsourceended` event handler property is not supported. | 13Exposed in Mobile Safari on iPad but not on iPhone. | 6.02.0–6.0The `onsourceended` event handler property is not supported. |
| `sourceopen_event` | 5331–53The `onsourceopen` event handler property is not supported. | 1712–17The `onsourceopen` event handler property is not supported. | 42 | 11Only works on Windows 8+. | 4018–40The `onsourceopen` event handler property is not supported. | 10.18–10.1The `onsourceopen` event handler property is not supported. | 534.4.3–53The `onsourceopen` event handler property is not supported. | 5331–53The `onsourceopen` event handler property is not supported. | 41 | 4118–41The `onsourceopen` event handler property is not supported. | 13Exposed in Mobile Safari on iPad but not on iPhone. | 6.02.0–6.0The `onsourceopen` event handler property is not supported. |
| `worker_support` | 108 | 108 | No | No | 94 | No | 108 | 108 | No | 73 | No | No |


See also
--------


* [`SourceBuffer`](sourcebuffer)
* [`SourceBufferList`](sourcebufferlist)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaSource>

MediaSourceHandle
=================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `MediaSourceHandle` interface of the [Media Source Extensions API](media_source_extensions_api) is a proxy for a [`MediaSource`](mediasource) that can be transferred from a dedicated worker back to the main thread and attached to a media element via its [`HTMLMediaElement.srcObject`](htmlmediaelement/srcobject) property. `MediaSource` objects are not transferable because they are event targets, hence the need for `MediaSourceHandle`s.

 It can be accessed via the [`MediaSource.handle`](mediasource/handle) property.

 Each `MediaSource` object created inside a dedicated worker has its own distinct `MediaSourceHandle`. The `MediaSource.handle` getter will always return the `MediaSourceHandle` instance specific to the associated dedicated worker `MediaSource` instance. If the handle has already been transferred to the main thread using [`postMessage()`](dedicatedworkerglobalscope/postmessage), the handle instance in the worker is technically detached and can't be transferred again.


 **Note:** This feature is available in [Web Workers](web_workers_api)

 

Instance properties
-------------------


None.


Instance methods
----------------


None.


Examples
--------



The [`handle`](mediasource/handle) property can be accessed inside a dedicated worker and the resulting `MediaSourceHandle` object is then transferred over to the thread that created the worker (in this case the main thread) via a [`postMessage()`](dedicatedworkerglobalscope/postmessage) call:

 
```
// Inside dedicated worker
let mediaSource = new MediaSource();
let handle = mediaSource.handle;
// Transfer the handle to the context that created the worker
postMessage({ arg: handle }, [handle]);

mediaSource.addEventListener("sourceopen", () => {
  // Await sourceopen on MediaSource before creating SourceBuffers
  // and populating them with fetched media — MediaSource won't
  // accept creation of SourceBuffers until it is attached to the
  // HTMLMediaElement and its readyState is "open"
});

```
 Over in the main thread, we receive the handle via a [`message`](worker/message_event) event handler, attach it to a [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) via its [`HTMLMediaElement.srcObject`](htmlmediaelement/srcobject) property, and [`play`](htmlmediaelement/play) the video:

 
```
worker.addEventListener("message", (msg) => {
  let mediaSourceHandle = msg.data.arg;
  video.srcObject = mediaSourceHandle;
  video.play();
});

```
  **Note:** [`MediaSourceHandle`](mediasourcehandle)s cannot be successfully transferred into or via a shared worker or service worker.

 

Specifications
--------------




| Specification |
| --- |
| [Media Source Extensions™ # mediasourcehandle](https://w3c.github.io/media-source/#mediasourcehandle) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaSourceHandle` | 108 | 108 | No | No | 94 | No | 108 | 108 | No | 73 | No | No |


See also
--------


* [MSE-in-Workers Demo by Matt Wolenetz](https://wolenetz.github.io/mse-in-workers-demo/mse-in-workers-demo.html)
* [Media Source Extensions API](media_source_extensions_api)
* [`MediaSource`](mediasource)
* [`SourceBuffer`](sourcebuffer)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaSourceHandle>

MediaStreamAudioSourceNode
==========================



The `MediaStreamAudioSourceNode` interface is a type of [`AudioNode`](audionode) which operates as an audio source whose media is received from a [`MediaStream`](mediastream) obtained using the WebRTC or Media Capture and Streams APIs.

 This media could be from a microphone (through [`getUserMedia()`](mediadevices/getusermedia)) or from a remote peer on a WebRTC call (using the [`RTCPeerConnection`](rtcpeerconnection)'s audio tracks).

 A `MediaStreamAudioSourceNode` has no inputs and exactly one output, and is created using the [`AudioContext.createMediaStreamSource()`](audiocontext/createmediastreamsource) method.

 The `MediaStreamAudioSourceNode` takes the audio from the *first* [`MediaStreamTrack`](mediastreamtrack) whose [`kind`](mediastreamtrack/kind) attribute's value is `audio`. See [Track ordering](#track_ordering) for more information about the order of tracks.

 The number of channels output by the node matches the number of tracks found in the selected audio track.


 EventTarget AudioNode MediaStreamAudioSourceNode 

|  |  |
| --- | --- |
| Number of inputs | `0` |
| Number of outputs | `1` |
| Channel count | 2 (but note that [`AudioNode.channelCount`](audionode/channelcount) is only used for up-mixing and down-mixing [`AudioNode`](audionode) inputs, and [`MediaStreamAudioSourceNode`](mediastreamaudiosourcenode) doesn't have any input) |



Constructor
-----------


 [`new MediaStreamAudioSourceNode()`](mediastreamaudiosourcenode/mediastreamaudiosourcenode)  Creates a new `MediaStreamAudioSourceNode` object instance with the specified options.

  
Instance properties
-------------------



*In addition to the following properties, `MediaStreamAudioSourceNode` inherits the properties of its parent, [`AudioNode`](audionode).*

  
[`mediaStream`](mediastreamaudiosourcenode/mediastream) Read only 
  The [`MediaStream`](mediastream) used when constructing this `MediaStreamAudioSourceNode`.

  

Instance methods
----------------


*Inherits methods from its parent, [`AudioNode`](audionode)*.


Exceptions
----------


 
`InvalidStateError` [`DOMException`](domexception)
  Thrown if the stream specified by the `mediaStream` parameter does not contain any audio tracks.

  
Usage notes
-----------


### Track ordering



For the purposes of the `MediaStreamTrackAudioSourceNode` interface, the order of the audio tracks on the stream is determined by taking the tracks whose [`kind`](mediastreamtrack/kind) is `audio`, then sorting the tracks by their [`id`](mediastreamtrack/id) property's values, in Unicode code point order (essentially, in alphabetical or lexicographical order, for IDs which are simple alphanumeric strings).

 The **first** track, then, is the track whose `id` comes first when the tracks' IDs are all sorted by Unicode code point.

 However, it's important to note that the rule establishing this ordering was added long after this interface was first introduced into the [Web Audio API](web_audio_api). As such, you can't easily rely on the order matching between any two browsers or browser versions.

 The [`MediaStreamTrackAudioSourceNode`](mediastreamtrackaudiosourcenode) interface is similar to `MediaStreamAudioSourceNode`, but avoids this problem by letting you specify which track you want to use.



Example
-------


See [`AudioContext.createMediaStreamSource()`](audiocontext/createmediastreamsource#examples) for example code that uses this object.


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # MediaStreamAudioSourceNode](https://webaudio.github.io/web-audio-api/#MediaStreamAudioSourceNode) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaStreamAudioSourceNode` | 55 | 79 | 53 | No | 42 | 14.1 | 55 | 55 | 53 | 42 | 14.5 | 6.0 |
| `MediaStreamAudioSourceNode` | 22 | 12 | 25 | No | 15 | 11 | 4.4 | 25 | 25 | 14 | 11 | 1.5 |
| `mediaStream` | 22 | 79 | 70 | No | 15 | 11 | 4.4 | 25 | 79 | 14 | 11 | 1.5 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)
* [WebRTC API](webrtc_api)
* [Media Capture and Streams API (Media Streams)](media_capture_and_streams_api)
* [`MediaStreamTrackAudioSourceNode`](mediastreamtrackaudiosourcenode)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamAudioSourceNode>

MediaStreamEvent
================



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.


**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The `MediaStreamEvent` interface represents events that occurs in relation to a [`MediaStream`](mediastream). Two events of this type can be thrown: [`addstream`](rtcpeerconnection/addstream_event) and [`removestream`](rtcpeerconnection/removestream_event).



Instance properties
-------------------



*A [`MediaStreamEvent`](mediastreamevent) being an [`Event`](event), this event also implements these properties*.

  
[`MediaStreamEvent.stream`](mediastreamevent/stream) Read only   Deprecated   Non-standard 
  Contains the [`MediaStream`](mediastream) containing the stream associated with the event.

  

Constructors
------------


 
[`MediaStreamEvent()`](mediastreamevent/mediastreamevent)  Deprecated   Non-standard 
  Returns a new `MediaStreamEvent`. It takes two parameters, the first being a string representing the type of the event; the second a dictionary containing the [`MediaStream`](mediastream) it refers to.

  
Instance methods
----------------


A [`MediaStreamEvent`](mediastreamevent) being an [`Event`](event), this event also implements these properties. There is no specific [`MediaStreamEvent`](mediastreamevent) method.


Examples
--------



```
pc.onaddstream = (ev) => {
  alert(`A stream (id: '${ev.stream.id}') has been added to this connection.`);
};

```

Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaStreamEvent` | 26 | 15 | 24 | No | 15 | 11–12 | 4.4 | 26 | 24 | 14 | 11–12 | 1.5 |
| `MediaStreamEvent` | 26See [bug 697059](https://crbug.com/697059). | 15 | 24 | No | 15 | 11–12 | ≤37 | 26See [bug 697059](https://crbug.com/697059). | 24 | 14 | 11–12 | 1.5 |
| `stream` | 26 | 15 | 24 | No | 15 | 11–12 | 4.4 | 26 | 24 | 14 | 11–12 | 1.5 |


See also
--------


* [WebRTC](webrtc_api)
* Its usual target: [`RTCPeerConnection`](rtcpeerconnection).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamEvent>

MediaStreamTrackAudioSourceNode
===============================



The `MediaStreamTrackAudioSourceNode` interface is a type of [`AudioNode`](audionode) which represents a source of audio data taken from a specific [`MediaStreamTrack`](mediastreamtrack) obtained through the [WebRTC](webrtc_api) or [Media Capture and Streams](media_capture_and_streams_api) APIs.

 The audio itself might be input from a microphone or other audio sampling device, or might be received through a [`RTCPeerConnection`](rtcpeerconnection), among other possible options.

 A `MediaStreamTrackAudioSourceNode` has no inputs and exactly one output, and is created using the [`AudioContext.createMediaStreamTrackSource()`](audiocontext/createmediastreamtracksource) method. This interface is similar to [`MediaStreamAudioSourceNode`](mediastreamaudiosourcenode), except it lets you specifically state the track to use, rather than assuming the first audio track on a stream.


 EventTarget AudioNode MediaStreamTrackAudioSourceNode 

|  |  |
| --- | --- |
| Number of inputs | `0` |
| Number of outputs | `1` |
| Channel count |  defined by the first audio [`MediaStreamTrack`](mediastreamtrack) passed to the [`AudioContext.createMediaStreamTrackSource()`](audiocontext/createmediastreamtracksource) method that created it.  |



Constructor
-----------


 [`new MediaStreamTrackAudioSourceNode()`](mediastreamtrackaudiosourcenode/mediastreamtrackaudiosourcenode)  Creates a new `MediaStreamTrackAudioSourceNode` object instance with the specified options.

  
Instance properties
-------------------


*The `MediaStreamTrackAudioSourceNode` interface has no properties of its own; however, it inherits the properties of its parent, [`AudioNode`](audionode).*


Instance methods
----------------


*Inherits methods from its parent, [`AudioNode`](audionode)*.


Example
-------


See [`AudioContext.createMediaStreamSource()`](audiocontext/createmediastreamsource#examples) for example code that uses this object.


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # MediaStreamTrackAudioSourceNode](https://webaudio.github.io/web-audio-api/#MediaStreamTrackAudioSourceNode) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaStreamTrackAudioSourceNode` | No | No | 68Firefox 68 implements the updated standard's definition of the "first" audio track; now the first track is the one whose ID comes first lexicographically. | No | No | No | No | No | 68Firefox 68 implements the updated standard's definition of the "first" audio track; now the first track is the one whose ID comes first lexicographically. | No | No | No |
| `MediaStreamTrackAudioSourceNode` | No | No | 68 | No | No | No | No | No | 68 | No | No | No |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)
* [WebRTC API](webrtc_api)
* [Media Capture and Streams API (Media Streams)](media_capture_and_streams_api)
* [`MediaStreamAudioSourceNode`](mediastreamaudiosourcenode)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrackAudioSourceNode>

MediaStreamTrackEvent
=====================



The `MediaStreamTrackEvent` interface represents events which indicate that a [`MediaStream`](mediastream) has had tracks added to or removed from the stream through calls to [Media Capture and Streams API](media_capture_and_streams_api) methods. These events are sent to the stream when these changes occur.


 Event MediaStreamTrackEvent The events based on this interface are [`addtrack`](mediastream/addtrack_event) and [`removetrack`](mediastream/removetrack_event).



Instance properties
-------------------



*Also inherits properties from its parent interface, [`Event`](event).*

  
[`MediaStreamTrackEvent.track`](mediastreamtrackevent/track) Read only 
  Returns a [`MediaStreamTrack`](mediastreamtrack) object representing the track associated with the event.

  

Constructor
-----------


 [`MediaStreamTrackEvent()`](mediastreamtrackevent/mediastreamtrackevent)  Constructs a new `MediaStreamTrackEvent` with the specified configuration.

  
Instance methods
----------------


*Also inherits methods from its parent [`Event`](event).*


Specifications
--------------




| Specification |
| --- |
| [Media Capture and Streams # mediastreamtrackevent](https://w3c.github.io/mediacapture-main/#mediastreamtrackevent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaStreamTrackEvent` | 55 | 12 | 50 | No | 42 | 11 | 55 | 55 | 50 | 42 | 11 | 6.0 |
| `MediaStreamTrackEvent` | 26 | 12 | 50 | No | 15 | 11 | 4.4 | 26 | 50 | 14 | 11 | 1.5 |
| `track` | 26 | 12 | 50 | No | 15 | 11 | 4.4 | 26 | 50 | 14 | 11 | 1.5 |


See also
--------


* [`MediaStream`](mediastream): [`addtrack`](mediastream/addtrack_event) and [`removetrack`](mediastream/removetrack_event) events
* [`MediaStreamTrack`](mediastreamtrack)
* [Media Capture and Streams API](media_capture_and_streams_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrackEvent>

MediaStreamTrackGenerator
=========================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.


**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

  The `MediaStreamTrackGenerator` interface of the [`Insertable Streams for MediaStreamTrack API`](insertable_streams_for_mediastreamtrack_api) creates a [`WritableStream`](writablestream) that acts as a [`MediaStreamTrack`](mediastreamtrack) source. The object consumes a stream of media frames as input, which can be audio or video frames. 



Constructor
-----------


 
[`MediaStreamTrackGenerator()`](mediastreamtrackgenerator/mediastreamtrackgenerator)  Experimental   Non-standard 
  Creates a new `MediaStreamTrackGenerator` object which accepts either [`VideoFrame`](videoframe) or [`AudioData`](audiodata) objects.

  
Instance properties
-------------------



*This interface also inherits properties from [`MediaStreamTrack`](mediastreamtrack).*

  
[`MediaStreamTrackGenerator.writable`](mediastreamtrackgenerator/writable)  Experimental   Non-standard 
  A [`WritableStream`](writablestream).

  

Instance methods
----------------


*This interface doesn't implement any specific methods, but inherits methods from [`MediaStreamTrack`](mediastreamtrack).*


Examples
--------



The following example is from the article [Insertable streams for MediaStreamTrack](https://web.dev/mediastreamtrack-insertable-media-processing/), and demonstrates a barcode scanner application, which process barcodes and highlights them before writing the transformed frames to the writable stream of [`MediaStreamTrackGenerator.writable`](mediastreamtrackgenerator/writable).

 
```
const stream = await getUserMedia({ video: true });
const videoTrack = stream.getVideoTracks()[0];

const trackProcessor = new MediaStreamTrackProcessor({ track: videoTrack });
const trackGenerator = new MediaStreamTrackGenerator({ kind: "video" });

const transformer = new TransformStream({
  async transform(videoFrame, controller) {
    const barcodes = await detectBarcodes(videoFrame);
    const newFrame = highlightBarcodes(videoFrame, barcodes);
    videoFrame.close();
    controller.enqueue(newFrame);
  },
});

trackProcessor.readable
  .pipeThrough(transformer)
  .pipeTo(trackGenerator.writable);

```


Specifications
--------------



**No specification found**No specification data found for `api.MediaStreamTrackGenerator`.  
[Check for problems with this page](#on-github) or contribute a missing `spec_url` to [mdn/browser-compat-data](https://github.com/mdn/browser-compat-data). Also make sure the specification is included in [w3c/browser-specs](https://github.com/w3c/browser-specs).



Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaStreamTrackGenerator` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `MediaStreamTrackGenerator` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `writable` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrackGenerator>

MediaStreamTrackProcessor
=========================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `MediaStreamTrackProcessor` interface of the [`Insertable Streams for MediaStreamTrack API`](insertable_streams_for_mediastreamtrack_api) consumes a [`MediaStreamTrack`](mediastreamtrack) object's source and generates a stream of media frames.



Constructor
-----------


 
[`MediaStreamTrackProcessor()`](mediastreamtrackprocessor/mediastreamtrackprocessor)  Experimental 
  Creates a new `MediaStreamTrackProcessor` object.

  
Instance properties
-------------------


 
[`MediaStreamTrackProcessor.readable`](mediastreamtrackprocessor/readable)  Experimental 
  Returns a [`ReadableStream`](readablestream).

  
Examples
--------



The following example is from the article [Insertable streams for MediaStreamTrack](https://web.dev/mediastreamtrack-insertable-media-processing/), and demonstrates a barcode scanner application, which transforms the stream accessed via [`MediaStreamTrackProcessor.readable`](mediastreamtrackprocessor/readable) by highlighting the barcode.

 
```
const stream = await getUserMedia({ video: true });
const videoTrack = stream.getVideoTracks()[0];

const trackProcessor = new MediaStreamTrackProcessor({ track: videoTrack });
const trackGenerator = new MediaStreamTrackGenerator({ kind: "video" });

const transformer = new TransformStream({
  async transform(videoFrame, controller) {
    const barcodes = await detectBarcodes(videoFrame);
    const newFrame = highlightBarcodes(videoFrame, barcodes);
    videoFrame.close();
    controller.enqueue(newFrame);
  },
});

trackProcessor.readable
  .pipeThrough(transformer)
  .pipeTo(trackGenerator.writable);

```


Specifications
--------------




| Specification |
| --- |
| [MediaStreamTrack Insertable Media Processing using Streams # track-processor-interface](https://w3c.github.io/mediacapture-transform/#track-processor-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaStreamTrackProcessor` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `MediaStreamTrackProcessor` | 94Chrome incorrectly exposes this interface only on the Window scope, rather than the DedicatedWorker scope as defined in the spec. | 94Edge incorrectly exposes this interface only on the Window scope, rather than the DedicatedWorker scope as defined in the spec. | No | No | 80Opera incorrectly exposes this interface only on the Window scope, rather than the DedicatedWorker scope as defined in the spec. | No | 94Chrome incorrectly exposes this interface only on the Window scope, rather than the DedicatedWorker scope as defined in the spec. | 94Chrome incorrectly exposes this interface only on the Window scope, rather than the DedicatedWorker scope as defined in the spec. | No | 66Opera incorrectly exposes this interface only on the Window scope, rather than the DedicatedWorker scope as defined in the spec. | No | 17.0Samsung Internet incorrectly exposes this interface only on the Window scope, rather than the DedicatedWorker scope as defined in the spec. |
| `readable` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrackProcessor>

MediaStreamTrack
================



The `MediaStreamTrack` interface represents a single media track within a stream; typically, these are audio or video tracks, but other track types may exist as well.


 EventTarget MediaStreamTrack

Instance properties
-------------------



In addition to the properties listed below, `MediaStreamTrack` has constrainable properties which can be set using [`applyConstraints()`](mediastreamtrack/applyconstraints) and accessed using [`getConstraints()`](mediastreamtrack/getconstraints) and [`getSettings()`](mediastreamtrack/getsettings). See [Capabilities, constraints, and settings](media_capture_and_streams_api/constraints) to learn how to correctly work with constrainable properties. Not doing so correctly will result in your code being unreliable.

  [`MediaStreamTrack.contentHint`](mediastreamtrack/contenthint)  A string that may be used by the web application to provide a hint as to what type of content the track contains to guide how it should be treated by API consumers.

  [`MediaStreamTrack.enabled`](mediastreamtrack/enabled)  A Boolean whose value of `true` if the track is enabled, that is allowed to render the media source stream; or `false` if it is disabled, that is not rendering the media source stream but silence and blackness. If the track has been disconnected, this value can be changed but has no more effect.

  **Note:** You can implement standard "mute" functionality by setting `enabled` to `false`. The `muted` property refers to a condition in which there's no media because of a technical issue.

   
[`MediaStreamTrack.id`](mediastreamtrack/id) Read only 
  Returns a string containing a unique identifier (GUID) for the track; it is generated by the browser.

  
[`MediaStreamTrack.kind`](mediastreamtrack/kind) Read only 
  Returns a string set to `"audio"` if the track is an audio track and to `"video"`, if it is a video track. It doesn't change if the track is disassociated from its source.

  
[`MediaStreamTrack.label`](mediastreamtrack/label) Read only 
  Returns a string containing a user agent-assigned label that identifies the track source, as in `"internal microphone"`. The string may be left empty and is empty as long as no source has been connected. When the track is disassociated from its source, the label is not changed.

  
[`MediaStreamTrack.muted`](mediastreamtrack/muted) Read only 
  Returns a Boolean value indicating whether the track is unable to provide media data due to a technical issue.

  **Note:** You can implement standard "mute" functionality by setting `enabled` to `false`, and unmute the media by setting it back to `true` again.

   
[`MediaStreamTrack.readyState`](mediastreamtrack/readystate) Read only 
  Returns an enumerated value giving the status of the track. This will be one of the following values:

 * `"live"` which indicates that an input is connected and does its best-effort in providing real-time data. In that case, the output of data can be switched on or off using the [`enabled`](mediastreamtrack/enabled) attribute.
* `"ended"` which indicates that the input is not giving any more data and will never provide new data.

  

Instance methods
----------------


 [`MediaStreamTrack.applyConstraints()`](mediastreamtrack/applyconstraints)  Lets the application specify the ideal and/or ranges of acceptable values for any number of the available constrainable properties of the `MediaStreamTrack`.

  [`MediaStreamTrack.clone()`](mediastreamtrack/clone)  Returns a duplicate of the `MediaStreamTrack`.

  [`MediaStreamTrack.getCapabilities()`](mediastreamtrack/getcapabilities)  Returns the a list of constrainable properties available for the `MediaStreamTrack`.

  [`MediaStreamTrack.getConstraints()`](mediastreamtrack/getconstraints)  Returns a [`MediaTrackConstraints`](mediatrackconstraints) object containing the currently set constraints for the track; the returned value matches the constraints last set using [`applyConstraints()`](mediastreamtrack/applyconstraints).

  [`MediaStreamTrack.getSettings()`](mediastreamtrack/getsettings)  Returns a [`MediaTrackSettings`](mediatracksettings) object containing the current values of each of the `MediaStreamTrack`'s constrainable properties.

  [`MediaStreamTrack.stop()`](mediastreamtrack/stop)  Stops playing the source associated to the track, both the source and the track are disassociated. The track state is set to `ended`.

  
Events
------



Listen to these events using [`addEventListener()`](eventtarget/addeventlistener) or by assigning an event listener to the `oneventname` property of this interface:

  [`ended`](mediastreamtrack/ended_event)  Sent when playback of the track ends (when the value [`readyState`](mediastreamtrack/readystate) changes to `ended`).

  [`mute`](mediastreamtrack/mute_event)  Sent to the `MediaStreamTrack` when the value of the [`muted`](mediastreamtrack/muted) property is changed to `true`, indicating that the track is unable to provide data temporarily (such as when the network is experiencing a service malfunction).

  
[`overconstrained`](mediastreamtrack/overconstrained_event)  Deprecated   Non-standard 
  Sent when the constraints specified for the track cause the track to be incompatible and therefore to not be used.

  [`unmute`](mediastreamtrack/unmute_event)  Sent to the track when data becomes available again, ending the `muted` state.

  

Specifications
--------------




| Specification |
| --- |
| [Media Capture and Streams # mediastreamtrack](https://w3c.github.io/mediacapture-main/#mediastreamtrack) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaStreamTrack` | 26 | 12 | 22 | No | 15 | 11 | 4.4 | 26 | 22 | 14 | 11 | 1.5 |
| `applyConstraints` | 59 | 12 | 43 | No | 46 | 11 | 59 | 59 | 43 | 43 | 11 | 7.0 |
| `capturehandlechange_event` | 102 | 102 | No | No | 88 | No | No | No | No | No | No | No |
| `clone` | 35 | 12 | 48 | No | 22 | 11 | 37 | 35 | 48 | 22 | 11 | 3.0 |
| `contentHint` | 70 | 79 | No | No | 57 | 12.1 | 70 | 70 | No | 49 | 12.2 | 10.0 |
| `enabled` | 26 | 12 | 24 | No | 15 | 11 | 4.4 | 26 | 24 | 14 | 11 | 1.5 |
| `ended_event` | 26 | 12 | 50 | No | 15 | 11 | 4.4 | 26 | 50 | 14 | 11 | 1.5 |
| `getCapabilities` | 59 | 12 | No | No | 46 | 11 | 59 | 59 | No | 43 | 11 | 7.0 |
| `getCaptureHandle` | 102 | 102 | No | No | 88 | No | No | No | No | No | No | No |
| `getConstraints` | 53 | 12 | 50 | No | 40 | 11 | 53 | 52 | 50 | 41 | 11 | 6.0 |
| `getSettings` | 59 | 12 | 50 | No | 46 | 11 | 59 | 59 | 50 | 43 | 11 | 7.0 |
| `id` | 26 | 12 | 22 | No | 15 | 11 | 4.4 | 26 | 22 | 14 | 11 | 1.5 |
| `kind` | 26 | 12 | 22 | No | 15 | 11 | 4.4 | 26 | 22 | 14 | 11 | 1.5 |
| `label` | 26 | 12 | 22 | No | 15 | 11 | 4.4 | 26 | 22 | 14 | 11 | 1.5 |
| `mute_event` | 26 | 12 | 59 | No | 15 | 11 | 4.4 | 26 | 59 | 14 | 11 | 1.5 |
| `muted` | 38 | 12 | 59 | No | 25 | 11 | 38 | 38 | 59 | 25 | 11 | 3.0 |
| `overconstrained_event` | No | 12–79 | No | No | No | 11 | No | No | No | No | 11 | No |
| `readyState` | 26 | 12 | 50 | No | 15 | 11 | 4.4 | 26 | 50 | 14 | 11 | 1.5 |
| `stop` | 32 | 12 | 34 | No | 19 | 11 | 4.4.3 | 32 | 34 | 19 | 11 | 2.0 |
| `unmute_event` | 26 | 12 | 59 | No | 15 | 11 | 4.4 | 26 | 59 | 14 | 11 | 1.5 |


See also
--------


* [Media Capture and Streams API](media_capture_and_streams_api)
* [`MediaStream`](mediastream)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack>

MediaTrackConstraints
=====================


The `MediaTrackConstraints` dictionary is used to describe a set of capabilities and the value or values each can take on. A constraints dictionary is passed into [`applyConstraints()`](mediastreamtrack/applyconstraints) to allow a script to establish a set of exact (required) values or ranges and/or preferred values or ranges of values for the track, and the most recently-requested set of custom constraints can be retrieved by calling [`getConstraints()`](mediastreamtrack/getconstraints).


Constraints
-----------



The following types are used to specify a constraint for a property. They allow you to specify one or more `exact` values from which one must be the parameter's value, or a set of `ideal` values which should be used if possible. You can also specify a single value (or an array of values) which the user agent will do its best to match once all more stringent constraints have been applied.

 To learn more about how constraints work, see [Capabilities, constraints, and settings](media_capture_and_streams_api/constraints).

  **Note:** `min` and `exact` values are not permitted in constraints used in [`MediaDevices.getDisplayMedia()`](mediadevices/getdisplaymedia) calls — they produce a `TypeError` — but they are allowed in constraints used in [`MediaStreamTrack.applyConstraints()`](mediastreamtrack/applyconstraints) calls.

 

### ConstrainBoolean



The `ConstrainBoolean` constraint type is used to specify a constraint for a property whose value is a Boolean value. Its value may either be set to a Boolean (`true` or `false`) or an object containing the following properties:

  `exact`  A Boolean which must be the value of the property. If the property can't be set to this value, matching will fail.

  `ideal`  A Boolean specifying an ideal value for the property. If possible, this value will be used, but if it's not possible, the user agent will use the closest possible match.

  

### ConstrainDouble



The `ConstrainDouble` constraint type is used to specify a constraint for a property whose value is a double-precision floating-point number. Its value may either be set to a number or an object containing the following properties:

  `max`  A decimal number specifying the largest permissible value of the property it describes. If the value cannot remain equal to or less than this value, matching will fail.

  `min`  A decimal number specifying the smallest permissible value of the property it describes. If the value cannot remain equal to or greater than this value, matching will fail.

  `exact`  A decimal number specifying a specific, required, value the property must have to be considered acceptable.

  `ideal`  A decimal number specifying an ideal value for the property. If possible, this value will be used, but if it's not possible, the user agent will use the closest possible match.

  

### ConstrainDOMString



The `ConstrainDOMString` constraint type is used to specify a constraint for a property whose value is a string. Its value may either be set to a string, an array of strings, or an object containing the following properties:

  `exact`  A string or an array of strings, one of which must be the value of the property. If the property can't be set to one of the listed values, matching will fail.

  `ideal`  A string or an array of strings, specifying ideal values for the property. If possible, one of the listed values will be used, but if it's not possible, the user agent will use the closest possible match.

  

### ConstrainULong



The `ConstrainULong` constraint type is used to specify a constraint for a property whose value is an integer. Its value may either be set to a number or an object containing the following properties:

  `max`  An integer specifying the largest permissible value of the property it describes. If the value cannot remain equal to or less than this value, matching will fail.

  `min`  An integer specifying the smallest permissible value of the property it describes. If the value cannot remain equal to or greater than this value, matching will fail.

  `exact`  An integer specifying a specific, required, value the property must have to be considered acceptable.

  `ideal`  An integer specifying an ideal value for the property. If possible, this value will be used, but if it's not possible, the user agent will use the closest possible match.

  

Instance properties
-------------------


Some combination—but not necessarily all—of the following properties will exist on the object. This may be because a given browser doesn't support the property, or because it doesn't apply. For example, because [RTP](https://developer.mozilla.org/en-US/docs/Glossary/RTP) doesn't provide some of these values during negotiation of a WebRTC connection, a track associated with a [`RTCPeerConnection`](rtcpeerconnection) will not include certain values, such as [`facingMode`](mediatrackconstraints/facingmode) or [`groupId`](mediatrackconstraints/groupid).


### Instance properties of all media tracks


 [`deviceId`](mediatrackconstraints/deviceid)  A [`ConstrainDOMString`](#constraindomstring) object specifying a device ID or an array of device IDs which are acceptable and/or required.

  [`groupId`](mediatrackconstraints/groupid)  A [`ConstrainDOMString`](#constraindomstring) object specifying a group ID or an array of group IDs which are acceptable and/or required.

  
### Instance properties of audio tracks


 [`autoGainControl`](mediatrackconstraints/autogaincontrol)  A [`ConstrainBoolean`](#constrainboolean) object which specifies whether automatic gain control is preferred and/or required.

  [`channelCount`](mediatrackconstraints/channelcount)  A [`ConstrainULong`](#constrainulong) specifying the channel count or range of channel counts which are acceptable and/or required.

  [`echoCancellation`](mediatrackconstraints/echocancellation)  A [`ConstrainBoolean`](#constrainboolean) object specifying whether or not echo cancellation is preferred and/or required.

  [`latency`](mediatrackconstraints/latency)  A [`ConstrainDouble`](#constraindouble) specifying the latency or range of latencies which are acceptable and/or required.

  [`noiseSuppression`](mediatrackconstraints/noisesuppression)  A [`ConstrainBoolean`](#constrainboolean) which specifies whether noise suppression is preferred and/or required.

  [`sampleRate`](mediatrackconstraints/samplerate)  A [`ConstrainULong`](#constrainulong) specifying the sample rate or range of sample rates which are acceptable and/or required.

  [`sampleSize`](mediatrackconstraints/samplesize)  A [`ConstrainULong`](#constrainulong) specifying the sample size or range of sample sizes which are acceptable and/or required.

  
[`volume`](mediatrackconstraints/volume)  Deprecated   Non-standard 
  A [`ConstrainDouble`](#constraindouble) specifying the volume or range of volumes which are acceptable and/or required.

  
### Instance properties of image tracks


 whiteBalanceMode  A [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) specifying one of `"none"`, `"manual"`, `"single-shot"`, or `"continuous"`.

  exposureMode  A [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) specifying one of `"none"`, `"manual"`, `"single-shot"`, or `"continuous"`.

  focusMode  A [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) specifying one of `"none"`, `"manual"`, `"single-shot"`, or `"continuous"`.

  pointsOfInterest  The pixel coordinates on the sensor of one or more points of interest. This is either an object in the form { x:*value*, y:*value* } or an array of such objects, where *value* is a double-precision integer.

  exposureCompensation  A [`ConstrainDouble`](#constraindouble) (a double-precision integer) specifying f-stop adjustment by up to ±3.

  colorTemperature  A [`ConstrainDouble`](#constraindouble) (a double-precision integer) specifying a desired color temperature in degrees kelvin.

  iso  A [`ConstrainDouble`](#constraindouble) (a double-precision integer) specifying a desired iso setting.

  brightness  A [`ConstrainDouble`](#constraindouble) (a double-precision integer) specifying a desired brightness setting.

  contrast  A [`ConstrainDouble`](#constraindouble) (a double-precision integer) specifying the degree of difference between light and dark.

  saturation  A [`ConstrainDouble`](#constraindouble) (a double-precision integer) specifying the degree of color intensity.

  sharpness  A [`ConstrainDouble`](#constraindouble) (a double-precision integer) specifying the intensity of edges.

  focusDistance  A [`ConstrainDouble`](#constraindouble) (a double-precision integer) specifying distance to a focused object.

  zoom  A [`ConstrainDouble`](#constraindouble) (a double-precision integer) specifying the desired focal length.

  torch  A boolean value defining whether the fill light is continuously connected, meaning it stays on as long as the track is active.

  
### Instance properties of video tracks


 [`aspectRatio`](mediatrackconstraints/aspectratio)  A [`ConstrainDouble`](#constraindouble) specifying the video aspect ratio or range of aspect ratios which are acceptable and/or required.

  [`facingMode`](mediatrackconstraints/facingmode)  A [`ConstrainDOMString`](#constraindomstring) object specifying a facing or an array of facings which are acceptable and/or required.

  [`frameRate`](mediatrackconstraints/framerate)  A [`ConstrainDouble`](#constraindouble) specifying the frame rate or range of frame rates which are acceptable and/or required.

  [`height`](mediatrackconstraints/height)  A [`ConstrainULong`](#constrainulong) specifying the video height or range of heights which are acceptable and/or required.

  [`width`](mediatrackconstraints/width)  A [`ConstrainULong`](#constrainulong) specifying the video width or range of widths which are acceptable and/or required.

  resizeMode  A [`ConstrainDOMString`](#constraindomstring) object specifying a mode or an array of modes the UA can use to derive the resolution of a video track. Allowed values are `none` and `crop-and-scale`. `none` means that the user agent uses the resolution provided by the camera, its driver or the OS. `crop-and-scale` means that the user agent can use cropping and downscaling on the camera output in order to satisfy other constraints that affect the resolution.

  
### Instance properties of shared screen tracks



These constraints apply to the `video` property of the object passed into [`getDisplayMedia()`](mediadevices/getdisplaymedia) to obtain a stream for screen sharing.

  [`displaySurface`](mediatrackconstraints/displaysurface)  A [`ConstrainDOMString`](#constraindomstring) which specifies the types of display surface that may be selected by the user. This may be a single one of the following strings, or a list of them to allow multiple source surfaces:

  `browser`  The stream contains the contents of a single browser tab selected by the user.

  `monitor`  The stream's video track contains the entire contents of one or more of the user's screens.

  `window`  The stream contains a single window selected by the user for sharing.

    [`logicalSurface`](mediatrackconstraints/logicalsurface)  A [`ConstrainBoolean`](#constrainboolean) value which may contain a single Boolean value or a set of them, indicating whether or not to allow the user to choose source surfaces which do not directly correspond to display areas. These may include backing buffers for windows to allow capture of window contents that are hidden by other windows in front of them, or buffers containing larger documents that need to be scrolled through to see the entire contents in their windows.

  
[`suppressLocalAudioPlayback`](mediatrackconstraints/suppresslocalaudioplayback)  Experimental 
  A [`ConstrainBoolean`](#constrainboolean) value describing the requested or mandatory constraints placed upon the value of the [`suppressLocalAudioPlayback`](mediatracksettings/suppresslocalaudioplayback) constrainable property. This property controls whether the audio playing in a tab will continue to be played out of a user's local speakers when the tab is captured.

  

Specifications
--------------




| Specification |
| --- |
| [Media Capture and Streams # dom-mediatrackconstraints](https://w3c.github.io/mediacapture-main/#dom-mediatrackconstraints) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaTrackConstraints` | 59 | ≤18 | 29 | No | 46 | 11 | 59 | 59 | 29 | 43 | 11 | 7.0 |
| `aspectRatio` | 59 | ≤79 | No | No | 46 | 11 | 59 | 59 | 29 | 43 | 11 | 7.0 |
| `autoGainControl` | 67 | ≤79 | 5546 | No | 54 | No | 67 | 67 | 5546 | 48 | No | 9.0 |
| `channelCount` | 59 | ≤79 | No | No | 46 | 11 | 59 | 59 | No | 43 | 11 | 7.0 |
| `deviceId` | 59 | ≤79 | 36Before Firefox 69, Firefox only supported `deviceId` in constraints passed into `getUserMedia()`. | No | 46 | 11 | 59 | 59 | 36Firefox for Android only supports `deviceId` when used in constraints passed into `getUserMedia()`. | 43 | 11 | 7.0 |
| `displaySurface` | 107 | 107 | No | No | 93 | 11.1 | 107 | 107 | No | 73 | 11.3 | No |
| `echoCancellation` | 59 | ≤79 | 50 | No | 46 | 11 | 59 | 59 | 50 | 43 | 11 | 7.0 |
| `facingMode` | 59 | ≤79 | 50 | No | 46 | 11 | 59 | 59 | 50 | 43 | 11 | 7.0 |
| `frameRate` | 59 | ≤79 | 50 | No | 46 | 11 | 59 | 59 | 50 | 43 | 11 | 7.0 |
| `groupId` | 59 | ≤79 | 70 | No | 46 | 11 | 59 | 59 | No | 43 | 11 | 7.0 |
| `height` | 59 | ≤79 | 50 | No | 46 | 11 | 59 | 59 | 50 | 43 | 11 | 7.0 |
| `latency` | 59 | ≤79 | 50 | No | 46 | 11 | 59 | 59 | 50 | 43 | 11 | 7.0 |
| `logicalSurface` | No | No | No | No | No | 11.1 | No | No | No | No | 11.3 | No |
| `noiseSuppression` | 67 | ≤79 | 5546 | No | 54 | No | 67 | 67 | 5546 | 48 | No | 9.0 |
| `resizeMode` | 72 | 79 | No | No | 60 | No | 72 | 72 | No | 51 | No | 11.0 |
| `sampleRate` | 59 | ≤79 | No | No | 46 | 11 | 59 | 59 | No | 43 | 11 | 7.0 |
| `sampleSize` | 59 | ≤79 | No | No | 46 | 11 | 59 | 59 | No | 43 | 11 | 7.0 |
| `suppressLocalAudioPlayback` | 109 | 109 | No | No | 95 | No | 109 | 109 | No | 74 | No | No |
| `volume` | 59 | ≤79 | No | No | 46 | 11 | 59 | 59 | No | 43 | 11 | 7.0 |
| `width` | 59 | ≤79 | 50 | No | 46 | 11 | 59 | 59 | 50 | 43 | 11 | 7.0 |


See also
--------


* [Media Capture and Streams API](media_capture_and_streams_api)
* [Capabilities, constraints, and settings](media_capture_and_streams_api/constraints)
* [Screen Capture API](screen_capture_api)
* [Using the Screen Capture API](screen_capture_api/using_screen_capture)
* [`MediaDevices.getUserMedia()`](mediadevices/getusermedia)
* [`MediaStreamTrack.getConstraints()`](mediastreamtrack/getconstraints)
* [`MediaStreamTrack.applyConstraints()`](mediastreamtrack/applyconstraints)
* [`MediaDevices.getSupportedConstraints()`](mediadevices/getsupportedconstraints)
* [`MediaTrackSupportedConstraints`](mediatracksupportedconstraints)
* [`MediaStreamTrack.getSettings()`](mediastreamtrack/getsettings)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints>

MediaTrackSettings
==================



The `MediaTrackSettings` dictionary is used to return the current values configured for each of a [`MediaStreamTrack`](mediastreamtrack)'s settings. These values will adhere as closely as possible to any constraints previously described using a [`MediaTrackConstraints`](mediatrackconstraints) object and set using [`applyConstraints()`](mediastreamtrack/applyconstraints), and will adhere to the default constraints for any properties whose constraints haven't been changed, or whose customized constraints couldn't be matched.

 To learn more about how constraints and settings work, see [Capabilities, constraints, and settings](media_capture_and_streams_api/constraints).



Instance properties
-------------------


Some or all of the following will be included in the object, either because it's not supported by the browser or because it's not available due to context. For example, because [RTP](https://developer.mozilla.org/en-US/docs/Glossary/RTP) doesn't provide some of these values during negotiation of a WebRTC connection, a track associated with a [`RTCPeerConnection`](rtcpeerconnection) will not include certain values, such as [`facingMode`](mediatracksettings/facingmode) or [`groupId`](mediatracksettings/groupid).


### Instance properties of all media tracks


 [`deviceId`](mediatracksettings/deviceid)  A string indicating the current value of the [`deviceId`](mediatrackconstraints/deviceid) property. The device ID is an origin-unique string identifying the source of the track; this is usually a [GUID](https://en.wikipedia.org/wiki/Universally_unique_identifier). This value is specific to the source of the track's data and is not usable for setting constraints; it can, however, be used for initially selecting media when calling [`MediaDevices.getUserMedia()`](mediadevices/getusermedia).

  [`groupId`](mediatracksettings/groupid)  A string indicating the current value of the [`groupId`](mediatrackconstraints/groupid) property. The group ID is a browsing session-unique string identifying the source group of the track. Two devices (as identified by the [`deviceId`](mediatracksettings/deviceid)) are considered part of the same group if they are from the same physical device. For instance, the audio input and output devices for the speaker and microphone built into a phone would share the same group ID, since they're part of the same physical device. The microphone on a headset would have a different ID, though. This value is specific to the source of the track's data and is not usable for setting constraints; it can, however, be used for initially selecting media when calling [`MediaDevices.getUserMedia()`](mediadevices/getusermedia).

  
### Instance properties of audio tracks


 [`autoGainControl`](mediatracksettings/autogaincontrol)  A Boolean which indicates the current value of the [`autoGainControl`](mediatrackconstraints/autogaincontrol) property, which is `true` if automatic gain control is enabled and is `false` otherwise.

  [`channelCount`](mediatracksettings/channelcount)  A long integer value indicating the current value of the [`channelCount`](mediatrackconstraints/channelcount) property, specifying the number of audio channels present on the track (therefore indicating how many audio samples exist in each audio frame). This is 1 for mono, 2 for stereo, and so forth.

  [`echoCancellation`](mediatracksettings/echocancellation)  A Boolean indicating the current value of the [`echoCancellation`](mediatrackconstraints/echocancellation) property, specifying `true` if echo cancellation is enabled, otherwise `false`.

  [`latency`](mediatracksettings/latency)  A double-precision floating point value indicating the current value of the [`latency`](mediatrackconstraints/latency) property, specifying the audio latency, in seconds. Latency is the amount of time which elapses between the start of processing the audio and the data being available to the next stop in the audio utilization process. This value is a target value; actual latency may vary to some extent for various reasons.

  [`noiseSuppression`](mediatracksettings/noisesuppression)  A Boolean which indicates the current value of the [`noiseSuppression`](mediatrackconstraints/noisesuppression) property, which is `true` if noise suppression is enabled and is `false` otherwise.

  [`sampleRate`](mediatracksettings/samplerate)  A long integer value indicating the current value of the [`sampleRate`](mediatrackconstraints/samplerate) property, specifying the sample rate in samples per second of the audio data. Standard CD-quality audio, for example, has a sample rate of 41,000 samples per second.

  [`sampleSize`](mediatracksettings/samplesize)  A long integer value indicating the current value of the [`sampleSize`](mediatrackconstraints/samplesize) property, specifying the linear size, in bits, of each audio sample. CD-quality audio, for example, is 16-bit, so this value would be 16 in that case.

  
[`volume`](mediatracksettings/volume)  Deprecated   Non-standard 
  A double-precision floating point value indicating the current value of the [`volume`](mediatrackconstraints/volume) property, specifying the volume level of the track. This value will be between 0.0 (silent) to 1.0 (maximum supported volume).

  
### Instance properties of video tracks


 [`aspectRatio`](mediatracksettings/aspectratio)  A double-precision floating point value indicating the current value of the [`aspectRatio`](mediatrackconstraints/aspectratio) property, specified precisely to 10 decimal places. This is the width of the image in pixels divided by its height in pixels. Common values include 1.3333333333 (for the classic television 4:3 "standard" aspect ratio, also used on tablets such as Apple's iPad), 1.7777777778 (for the 16:9 high-definition widescreen aspect ratio), and 1.6 (for the 16:10 aspect ratio common among widescreen computers and tablets).

  [`facingMode`](mediatracksettings/facingmode)  A string indicating the current value of the [`facingMode`](mediatrackconstraints/facingmode) property, specifying the direction the camera is facing. The value will be one of:

  `"user"`  A camera facing the user (commonly known as a "selfie cam"), used for self-portraiture and video calling.

  `"environment"`  A camera facing away from the user (when the user is looking at the screen). This is typically the highest quality camera on the device, used for general photography.

  `"left"`  A camera facing toward the environment to the user's left.

  `"right"`  A camera facing toward the environment to the user's right.

    [`frameRate`](mediatracksettings/framerate)  A double-precision floating point value indicating the current value of the [`frameRate`](mediatrackconstraints/framerate) property, specifying how many frames of video per second the track includes. If the value can't be determined for any reason, the value will match the vertical sync rate of the device the user agent is running on.

  [`height`](mediatracksettings/height)  A long integer value indicating the current value of the [`height`](mediatrackconstraints/height) property, specifying the height of the track's video data in pixels.

  [`width`](mediatracksettings/width)  A long integer value indicating the current value of the [`width`](mediatracksettings/width) property, specifying the width of the track's video data in pixels.

  `resizeMode`  A string indicating the current value of the `resizeMode` property, specifying the mode used by the user agent to derive the resolution of the track. The value will be one of:

  `"none"`  The track has the resolution offered by the camera, its driver or the OS.

  `"crop-and-scale"`  The track's resolution might be the result of the user agent using cropping or downscaling from a higher camera resolution.

    
### Instance properties of shared screen tracks



Tracks containing video shared from a user's screen (regardless of whether the screen data comes from the entire screen or a portion of a screen, like a window or tab) are generally treated like video tracks, with the exception that they also support the following added settings:

  [`cursor`](mediatracksettings/cursor)  A string which indicates whether or not the mouse cursor is being included in the generated stream and under what conditions. Possible values are:

  `always`  The mouse is always visible in the video content of the {domxref("MediaStream"), unless the mouse has moved outside the area of the content.

  `motion`  The mouse cursor is always included in the video if it's moving, and for a short time after it stops moving.

  `never`  The mouse cursor is never included in the shared video.

    [`displaySurface`](mediatracksettings/displaysurface)  A string which specifies the type of source the track contains; one of:

  `application`  The stream contains all of the windows of the application chosen by the user rendered into the one video track.

  `browser`  The stream contains the contents of a single browser tab selected by the user.

  `monitor`  The stream's video track contains the entire contents of one or more of the user's screens.

  `window`  The stream contains a single window selected by the user for sharing.

    [`logicalSurface`](mediatracksettings/logicalsurface)  A Boolean value which, if `true`, indicates that the video contained in the stream's video track contains a background rendering context, rather than a user-visible one. This is `false` if the video being captured is coming from a foreground (user-visible) source.

  

Specifications
--------------




| Specification |
| --- |
| [Media Capture and Streams # media-track-settings](https://w3c.github.io/mediacapture-main/#media-track-settings) |
| [Screen Capture # extensions-to-mediatracksettings](https://w3c.github.io/mediacapture-screen-share/#extensions-to-mediatracksettings) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaTrackSettings` | 59 | ≤79 | 36 | No | 46 | 11 | 59 | 59 | 36 | 43 | 11 | 7.0 |
| `aspectRatio` | 59 | ≤79 | No | No | 46 | 11 | 59 | 59 | No | 43 | 11 | 7.0 |
| `autoGainControl` | 67 | ≤79 | 5550–55 | No | 54 | No | 67 | 67 | 5550–55 | 48 | No | 9.0 |
| `channelCount` | No | No | No | No | No | 11 | No | No | No | No | 11 | No |
| `cursor` | 71 | ≤79 | No | No | 58 | No | 71 | 71 | No | 50 | No | 10.0 |
| `deviceId` | 59 | ≤79 | 69 | No | 46 | 11 | 59 | 59 | No | 43 | 11 | 7.0 |
| `displaySurface` | 71 | ≤79 | No | No | 58 | 11.1 | 71 | 71 | No | 50 | 11.3 | 10.0 |
| `echoCancellation` | 59 | ≤79 | 50 | No | 46 | 11 | 59 | 59 | 50 | 43 | 11 | 7.0 |
| `facingMode` | 59 | ≤79 | 69 | No | 46 | 11 | 59 | 59 | No | 43 | 11 | 7.0 |
| `frameRate` | 59 | ≤79 | 36 | No | 46 | 11 | 59 | 59 | 36 | 43 | 11 | 7.0 |
| `groupId` | 59 | ≤79 | 69 | No | 46 | 11 | 59 | 59 | No | 43 | 11 | 7.0 |
| `height` | 59 | ≤79 | 36 | No | 46 | 11 | 59 | 59 | 36 | 43 | 11 | 7.0 |
| `latency` | No | No | No | No | No | 11 | No | No | No | No | 11 | No |
| `logicalSurface` | 71 | ≤79 | No | No | 58 | 11.1 | 71 | 71 | No | 50 | 11.3 | 10.0 |
| `noiseSuppression` | 67 | ≤79 | 5550–55 | No | 54 | No | 67 | 67 | 5550–55 | 48 | No | 9.0 |
| `resizeMode` | 72 | 79 | No | No | 60 | No | 72 | 72 | No | 51 | No | 11.0 |
| `sampleRate` | 59 | ≤79 | No | No | 46 | 11 | 59 | 59 | No | 43 | 11 | 7.0 |
| `sampleSize` | 59 | ≤79 | No | No | 46 | 11 | 59 | 59 | No | 43 | 11 | 7.0 |
| `suppressLocalAudioPlayback` | 109 | 109 | No | No | 95 | No | 109 | 109 | No | 74 | No | No |
| `volume` | No | No | No | No | No | 11 | No | No | No | No | 11 | No |
| `width` | 59 | ≤79 | 36 | No | 46 | 11 | 59 | 59 | 36 | 43 | 11 | 7.0 |


See also
--------


* [`MediaDevices.getUserMedia()`](mediadevices/getusermedia)
* [`MediaDevices.getDisplayMedia()`](mediadevices/getdisplaymedia)
* [`MediaStreamTrack.getConstraints()`](mediastreamtrack/getconstraints)
* [`MediaStreamTrack.applyConstraints()`](mediastreamtrack/applyconstraints)
* [`MediaStreamTrack.getSettings()`](mediastreamtrack/getsettings)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackSettings>

MediaTrackSupportedConstraints
==============================



The `MediaTrackSupportedConstraints` dictionary establishes the list of constrainable properties recognized by the [user agent](https://developer.mozilla.org/en-US/docs/Glossary/User_agent) or browser in its implementation of the [`MediaStreamTrack`](mediastreamtrack) object. An object conforming to `MediaTrackSupportedConstraints` is returned by [`MediaDevices.getSupportedConstraints()`](mediadevices/getsupportedconstraints).

 Because of the way interface definitions in WebIDL work, if a constraint is requested but not supported, no error will occur. Instead, the specified constraints will be applied, with any unrecognized constraints stripped from the request. That can lead to confusing and hard to debug errors, so be sure to use `getSupportedConstraints()` to retrieve this information before attempting to establish constraints if you need to know the difference between silently ignoring a constraint and a constraint being accepted.

 An actual constraint set is described using an object based on the [`MediaTrackConstraints`](mediatrackconstraints) dictionary.

 To learn more about how constraints work, see [Capabilities, constraints, and settings](media_capture_and_streams_api/constraints).



Instance properties
-------------------



Some combination—but not necessarily all—of the following properties will exist on the object.

  [`autoGainControl`](mediatracksupportedconstraints/autogaincontrol)  A Boolean whose value is `true` if the [`autoGainControl`](mediatrackconstraints#autogaincontrol) constraint is supported in the current environment.

  [`width`](mediatracksupportedconstraints/width)  A Boolean value whose value is `true` if the [`width`](mediatrackconstraints#width) constraint is supported in the current environment.

  [`height`](mediatracksupportedconstraints/height)  A Boolean value whose value is `true` if the [`height`](mediatrackconstraints#height) constraint is supported in the current environment.

  [`aspectRatio`](mediatracksupportedconstraints/aspectratio)  A Boolean value whose value is `true` if the [`aspectRatio`](mediatrackconstraints#aspectratio) constraint is supported in the current environment.

  [`frameRate`](mediatracksupportedconstraints/framerate)  A Boolean value whose value is `true` if the [`frameRate`](mediatrackconstraints#framerate) constraint is supported in the current environment.

  [`facingMode`](mediatracksupportedconstraints/facingmode)  A Boolean value whose value is `true` if the [`facingMode`](mediatrackconstraints#facingmode) constraint is supported in the current environment.

  `resizeMode`  A Boolean value whose value is `true` if the [`resizeMode`](mediatrackconstraints#resizemode) constraint is supported in the current environment.

  
[`volume`](mediatracksupportedconstraints/volume)  Deprecated   Non-standard 
  A Boolean value whose value is `true` if the [`volume`](mediatrackconstraints#volume) constraint is supported in the current environment.

  [`sampleRate`](mediatracksupportedconstraints/samplerate)  A Boolean value whose value is `true` if the [`sampleRate`](mediatrackconstraints#samplerate) constraint is supported in the current environment.

  [`sampleSize`](mediatracksupportedconstraints/samplesize)  A Boolean value whose value is `true` if the [`sampleSize`](mediatrackconstraints#samplesize) constraint is supported in the current environment.

  [`echoCancellation`](mediatracksupportedconstraints/echocancellation)  A Boolean value whose value is `true` if the [`echoCancellation`](mediatrackconstraints#echocancellation) constraint is supported in the current environment.

  [`latency`](mediatracksupportedconstraints/latency)  A Boolean value whose value is `true` if the [`latency`](mediatrackconstraints#latency) constraint is supported in the current environment.

  [`noiseSuppression`](mediatracksupportedconstraints/noisesuppression)  A Boolean whose value is `true` if the [`noiseSuppression`](mediatrackconstraints#noisesuppression) constraint is supported in the current environment.

  [`channelCount`](mediatracksupportedconstraints/channelcount)  A Boolean value whose value is `true` if the [`channelCount`](mediatrackconstraints#channelcount) constraint is supported in the current environment.

  [`deviceId`](mediatracksupportedconstraints/deviceid)  A Boolean value whose value is `true` if the [`deviceId`](mediatrackconstraints#deviceid) constraint is supported in the current environment.

  [`groupId`](mediatracksupportedconstraints/groupid)  A Boolean value whose value is `true` if the [`groupId`](mediatrackconstraints#groupid) constraint is supported in the current environment.

  

### Instance properties specific to shared screen tracks



For tracks containing video sources from the user's screen contents, the following additional properties are may be included in addition to those available for video tracks.

  [`displaySurface`](mediatracksupportedconstraints/displaysurface)  A Boolean value which is `true` if the [`displaySurface`](mediatrackconstraints/displaysurface) constraint is supported in the current environment.

  [`logicalSurface`](mediatracksupportedconstraints/logicalsurface)  A Boolean value which is `true` if the [`logicalSurface`](mediatrackconstraints/logicalsurface) constraint is supported in the current environment.

  

Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MediaTrackSupportedConstraints` | 52 | ≤79 | 42 | No | 39 | 11 | 52 | 52 | 42 | 41 | 11 | 6.0 |
| `aspectRatio` | 52 | ≤79 | No | No | 39 | 11 | 52 | 52 | No | 41 | 11 | 6.0 |
| `autoGainControl` | 69 | ≤79 | 5546–55 | No | 56 | No | 69 | 69 | 5546–55 | 48 | No | 10.0 |
| `channelCount` | 52 | ≤79 | 56 | No | 39 | 11 | 52 | 52 | 56 | 41 | 11 | 6.0 |
| `deviceId` | 52 | ≤79 | 42 | No | 39 | 11 | 52 | 52 | 42 | 41 | 11 | 6.0 |
| `displaySurface` | 107 | 107 | No | No | 93 | 11.1 | 107 | 107 | No | 73 | 11.3 | No |
| `echoCancellation` | 52 | ≤79 | 46 | No | 39 | 11 | 52 | 52 | 46 | 41 | 11 | 6.0 |
| `facingMode` | 52 | ≤79 | 42 | No | 39 | 11 | 52 | 52 | 42 | 41 | 11 | 6.0 |
| `frameRate` | 52 | ≤79 | 42 | No | 39 | 11 | 52 | 52 | 42 | 41 | 11 | 6.0 |
| `groupId` | 52 | ≤79 | 70 | No | 39 | 11 | 52 | 52 | No | 41 | 11 | 6.0 |
| `height` | 52 | ≤79 | 42 | No | 39 | 11 | 52 | 52 | 42 | 41 | 11 | 6.0 |
| `latency` | 52 | ≤79 | No | No | 39 | 11 | 52 | 52 | No | 41 | 11 | 6.0 |
| `logicalSurface` | No | No | No | No | No | 11.1 | No | No | No | No | 11.3 | No |
| `noiseSuppression` | 69 | ≤79 | 5546–55 | No | 56 | No | 69 | 69 | 5546–55 | 48 | No | 10.0 |
| `resizeMode` | 72 | 79 | No | No | 60 | No | 72 | 72 | No | 51 | No | 11.0 |
| `sampleRate` | 52 | ≤79 | No | No | 39 | 11 | 52 | 52 | No | 41 | 11 | 6.0 |
| `sampleSize` | 52 | ≤79 | No | No | 39 | 11 | 52 | 52 | No | 41 | 11 | 6.0 |
| `suppressLocalAudioPlayback` | 109 | 109 | No | No | 95 | No | 109 | 109 | No | 74 | No | No |
| `volume` | 52 | ≤79 | No | No | 39 | 11 | 52 | 52 | No | 41 | 11 | 6.0 |
| `width` | 52 | ≤79 | 42 | No | 39 | 11 | 52 | 52 | 42 | 41 | 11 | 6.0 |


See also
--------


* [Media Capture and Streams API](media_capture_and_streams_api)
* [Capabilities, constraints, and settings](media_capture_and_streams_api/constraints)
* [Screen Capture API](screen_capture_api)
* [Using the Screen Capture API](screen_capture_api/using_screen_capture)
* [`MediaTrackConstraints`](mediatrackconstraints)
* [`MediaDevices.getUserMedia()`](mediadevices/getusermedia)
* [`MediaStreamTrack.getConstraints()`](mediastreamtrack/getconstraints)
* [`MediaStreamTrack.applyConstraints()`](mediastreamtrack/applyconstraints)
* [`MediaStreamTrack.getSettings()`](mediastreamtrack/getsettings)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackSupportedConstraints>

MerchantValidationEvent
=======================



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.


**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `MerchantValidationEvent` interface of the [Payment Request API](payment_request_api) enables a merchant to verify themselves as allowed to use a particular payment handler.

 Learn more about [merchant validation](payment_request_api/concepts#merchant_validation).



Constructor
-----------


 
[`MerchantValidationEvent()`](merchantvalidationevent/merchantvalidationevent) Secure context  Deprecated 
  Creates a new `MerchantValidationEvent` object describing a [`merchantvalidation`](paymentrequest/merchantvalidation_event) event that will be sent to the payment handler to request that it validate the merchant.

  
Instance properties
-------------------


 
[`MerchantValidationEvent.methodName`](merchantvalidationevent/methodname) Secure context  Deprecated 
  A string providing a unique payment method identifier for the payment handler that's requiring validation. This may be either one of the standard payment method identifier strings or a URL that both identifies and handles requests for the payment handler, such as `https://apple.com/apple-pay`.

  
[`MerchantValidationEvent.validationURL`](merchantvalidationevent/validationurl) Secure context  Deprecated 
  A string specifying a URL from which the site or app can fetch payment handler specific validation information. Once this data is retrieved, the data (or a promise resolving to the validation data) should be passed into [`complete()`](merchantvalidationevent/complete) to validate that the payment request is coming from an authorized merchant.

  
Instance methods
----------------


 
[`MerchantValidationEvent.complete()`](merchantvalidationevent/complete) Secure context  Deprecated 
  Pass the data retrieved from the URL specified by [`validationURL`](merchantvalidationevent/validationurl) into `complete()` to complete the validation process for the [`PaymentRequest`](paymentrequest).

  
Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MerchantValidationEvent` | No | No | 64Available only in Nightly builds. | No | No | 12.1 | No | No | No | No | 12.2 | No |
| `MerchantValidationEvent` | No | No | 64Available only in Nightly builds. | No | No | 11.1 | No | No | No | No | 11.3 | No |
| `complete` | No | No | 64Available only in Nightly builds. | No | No | 11.1 | No | No | No | No | 11.3 | No |
| `methodName` | No | No | 64Available only in Nightly builds. | No | No | 12.1 | No | No | No | No | 12.2 | No |
| `validationURL` | No | No | 64Available only in Nightly builds. | No | No | 11.1 | No | No | No | No | 11.3 | No |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MerchantValidationEvent>

MessageChannel
==============



The `MessageChannel` interface of the [Channel Messaging API](channel_messaging_api) allows us to create a new message channel and send data through it via its two [`MessagePort`](messageport) properties.


 **Note:** This feature is available in [Web Workers](web_workers_api)

 

Instance properties
-------------------


 
[`MessageChannel.port1`](messagechannel/port1) Read only 
  Returns port1 of the channel.

  
[`MessageChannel.port2`](messagechannel/port2) Read only 
  Returns port2 of the channel.

  
Constructor
-----------


 [`MessageChannel()`](messagechannel/messagechannel)  Returns a new `MessageChannel` object with two new [`MessagePort`](messageport) objects.

  
Example
-------



In the following example, you can see a new channel being created using the [`MessageChannel.MessageChannel`](messagechannel) constructor.

 When the IFrame has loaded, we register an `onmessage` handler for [`MessageChannel.port1`](messagechannel/port1) and transfer [`MessageChannel.port2`](messagechannel/port2) to the IFrame using the [`window.postMessage`](window/postmessage) method along with a message.

 When a message is received back from the IFrame, the `onMessage` function outputs the message to a paragraph.

 
```
const channel = new MessageChannel();
const output = document.querySelector(".output");
const iframe = document.querySelector("iframe");

// Wait for the iframe to load
iframe.addEventListener("load", onLoad);

function onLoad() {
  // Listen for messages on port1
  channel.port1.onmessage = onMessage;

  // Transfer port2 to the iframe
  iframe.contentWindow.postMessage("Hello from the main page!", "\*", [
    channel.port2,
  ]);
}

// Handle messages received on port1
function onMessage(e) {
  output.innerHTML = e.data;
}

```
 For a full working example, see our [channel messaging basic demo](https://github.com/mdn/dom-examples/tree/main/channel-messaging-basic) on GitHub ([run it live too](https://mdn.github.io/dom-examples/channel-messaging-basic/)).



Specifications
--------------




| Specification |
| --- |
| [HTML Standard # message-channels](https://html.spec.whatwg.org/multipage/web-messaging.html#message-channels) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MessageChannel` | 2 | 12 | 41 | 10 | 10.6 | 5 | 4.4 | 18 | 41 | 11 | 4.2 | 1.0 |
| `MessageChannel` | 2 | 12 | 41 | 10 | 10.6 | 5 | 4.4 | 18 | 41 | 11 | 4.2 | 1.0 |
| `port1` | 2 | 12 | 41 | 10 | 10.6 | 5 | 4.4 | 18 | 41 | 11 | 4.2 | 1.0 |
| `port2` | 2 | 12 | 41 | 10 | 10.6 | 5 | 4.4 | 18 | 41 | 11 | 4.2 | 1.0 |


See also
--------


* [Using channel messaging](channel_messaging_api/using_channel_messaging)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel>

MessageEvent
============



The `MessageEvent` interface represents a message received by a target object.

 This is used to represent messages in:

 * [Server-sent events](server-sent_events) (see [`EventSource.message_event`](eventsource/message_event)).
* [Web sockets](websockets_api) (see the `onmessage` property of the [WebSocket](websocket) interface).
* Cross-document messaging (see [`Window.postMessage()`](window/postmessage) and [`Window.message_event`](window/message_event)).
* [Channel messaging](channel_messaging_api) (see [`MessagePort.postMessage()`](messageport/postmessage) and [`MessagePort.message_event`](messageport/message_event)).
* Cross-worker/document messaging (see the above two entries, but also [`Worker.postMessage()`](worker/postmessage), [`Worker.message_event`](worker/message_event), [`ServiceWorkerGlobalScope.message_event`](serviceworkerglobalscope/message_event), etc.)
* [Broadcast channels](broadcast_channel_api) (see [`Broadcastchannel.postMessage()`](broadcastchannel/postmessage)) and [`BroadcastChannel.message_event`](broadcastchannel/message_event)).
* WebRTC data channels (see [`onmessage`](rtcdatachannel/message_event)).

 The action triggered by this event is defined in a function set as the event handler for the relevant `message` event (e.g. using an `onmessage` handler as listed above).


 **Note:** This feature is available in [Web Workers](web_workers_api)

   Event MessageEvent

Constructor
-----------


 [`MessageEvent()`](messageevent/messageevent)  Creates a new `MessageEvent`.

  
Instance properties
-------------------



*This interface also inherits properties from its parent, [`Event`](event).*

  
[`MessageEvent.data`](messageevent/data) Read only 
  The data sent by the message emitter.

  
[`MessageEvent.origin`](messageevent/origin) Read only 
  A string representing the origin of the message emitter.

  
[`MessageEvent.lastEventId`](messageevent/lasteventid) Read only 
  A string representing a unique ID for the event.

  
[`MessageEvent.source`](messageevent/source) Read only 
  A `MessageEventSource` (which can be a [WindowProxy](https://developer.mozilla.org/en-US/docs/Glossary/WindowProxy), [`MessagePort`](messageport), or [`ServiceWorker`](serviceworker) object) representing the message emitter.

  
[`MessageEvent.ports`](messageevent/ports) Read only 
  An array of [`MessagePort`](messageport) objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker).

  

Instance methods
----------------



*This interface also inherits methods from its parent, [`Event`](event).*

  
`initMessageEvent()`  Deprecated 
  Initializes a message event. **Do not use this anymore** — **use the [`MessageEvent()`](messageevent/messageevent) constructor instead.**

  

Examples
--------



In our [Basic shared worker example](https://github.com/mdn/dom-examples/tree/main/web-workers/simple-shared-worker) ([run shared worker](https://mdn.github.io/dom-examples/web-workers/simple-shared-worker/)), we have two HTML pages, each of which uses some JavaScript to perform a simple calculation. The different scripts are using the same worker file to perform the calculation — they can both access it, even if their pages are running inside different windows.

 The following code snippet shows creation of a [`SharedWorker`](sharedworker) object using the [`SharedWorker()`](sharedworker/sharedworker) constructor. Both scripts contain this:

 
```
const myWorker = new SharedWorker("worker.js");

```
 Both scripts then access the worker through a [`MessagePort`](messageport) object created using the [`SharedWorker.port`](sharedworker/port) property. If the onmessage event is attached using addEventListener, the port is manually started using its `start()` method:

 
```
myWorker.port.start();

```
 When the port is started, both scripts post messages to the worker and handle messages sent from it using `port.postMessage()` and `port.onmessage`, respectively:

 
```
first.onchange = () => {
  myWorker.port.postMessage([first.value, second.value]);
  console.log("Message posted to worker");
};

second.onchange = () => {
  myWorker.port.postMessage([first.value, second.value]);
  console.log("Message posted to worker");
};

myWorker.port.onmessage = (e) => {
  result1.textContent = e.data;
  console.log("Message received from worker");
};

```
 Inside the worker we use the [`onconnect`](sharedworkerglobalscope/connect_event) handler to connect to the same port discussed above. The ports associated with that worker are accessible in the [`connect`](sharedworkerglobalscope/connect_event) event's `ports` property — we then use [`MessagePort`](messageport) `start()` method to start the port, and the `onmessage` handler to deal with messages sent from the main threads.

 
```
onconnect = (e) => {
  const port = e.ports[0];

  port.addEventListener("message", (e) => {
    const workerResult = `Result: ${e.data[0] \* e.data[1]}`;
    port.postMessage(workerResult);
  });

  port.start(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter.
};

```


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-messageevent-interface](https://html.spec.whatwg.org/multipage/comms.html#the-messageevent-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MessageEvent` | 16 | 14 | 26 | No | ≤12.1 | 6 | 4.4 | 18 | 26 | ≤12.1 | 6 | 1.0 |
| `MessageEvent` | 2 | 12 | 3 | 9 | 10.6 | 4 | ≤37 | 18 | 4 | 11 | 3.2 | 1.0 |
| `data` | 2 | 12 | 3 | 9 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `initMessageEvent` | 2 | 12 | 3 | 9 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `lastEventId` | 2 | 17 | 3 | 9 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `origin` | 2 | 12 | 3 | 9 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `ports` | 4 | 12 | 3 | 9 | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `source` | 2 | 12 | 3 | No | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |


See also
--------


* [`ExtendableMessageEvent`](extendablemessageevent) — similar to this interface but used in interfaces that needs to give more flexibility to authors.


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent>

MessagePort
===========



The `MessagePort` interface of the [Channel Messaging API](channel_messaging_api) represents one of the two ports of a [`MessageChannel`](messagechannel), allowing messages to be sent from one port and listening out for them arriving at the other.

 `MessagePort` is a [transferable object](web_workers_api/transferable_objects).


 **Note:** This feature is available in [Web Workers](web_workers_api)

   EventTarget MessagePort

Instance methods
----------------



*Inherits methods from its parent, [`EventTarget`](eventtarget)*.

  [`postMessage()`](messageport/postmessage)  Sends a message from the port, and optionally, transfers ownership of objects to other browsing contexts.

  [`start()`](messageport/start)  Starts the sending of messages queued on the port (only needed when using [`EventTarget.addEventListener`](eventtarget/addeventlistener); it is implied when using [`onmessage`](messageport/message_event)).

  [`close()`](messageport/close)  Disconnects the port, so it is no longer active.

  

Events
------


 [`message`](messageport/message_event)  Fired when a `MessagePort` object receives a message.

  [`messageerror`](messageport/messageerror_event)  Fired when a `MessagePort` object receives a message that can't be deserialized.

  
Example
-------



In the following example, you can see a new channel being created using the [`MessageChannel()`](messagechannel/messagechannel) constructor.

 When the IFrame has loaded, we register an [`onmessage`](messageport/message_event) handler for [`MessageChannel.port1`](messagechannel/port1) and transfer [`MessageChannel.port2`](messagechannel/port2) to the IFrame using the [`window.postMessage`](window/postmessage) method along with a message.

 When a message is received back from the IFrame, the `onMessage` function outputs the message to a paragraph.

 
```
const channel = new MessageChannel();
const output = document.querySelector(".output");
const iframe = document.querySelector("iframe");

// Wait for the iframe to load
iframe.addEventListener("load", onLoad);

function onLoad() {
  // Listen for messages on port1
  channel.port1.onmessage = onMessage;

  // Transfer port2 to the iframe
  iframe.contentWindow.postMessage("Hello from the main page!", "\*", [
    channel.port2,
  ]);
}

// Handle messages received on port1
function onMessage(e) {
  output.innerHTML = e.data;
}

```
 For a full working example, see our [channel messaging basic demo](https://github.com/mdn/dom-examples/tree/main/channel-messaging-basic) on GitHub ([run it live too](https://mdn.github.io/dom-examples/channel-messaging-basic/)).



Specifications
--------------




| Specification |
| --- |
| [HTML Standard # message-ports](https://html.spec.whatwg.org/multipage/web-messaging.html#message-ports) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MessagePort` | 2 | 12 | 41 | 10 | 10.6 | 5 | 4.4 | 18 | 41 | 11 | 4.2 | 1.0 |
| `close` | 2 | 12 | 41 | 10 | 10.6 | 5 | 4.4 | 18 | 41 | 11 | 4.2 | 1.0 |
| `message_event` | 2 | 12 | 41 | 10 | 10.6 | 5 | ≤37 | 18 | 41 | 11.5 | 4.2 | 1.0 |
| `messageerror_event` | 60 | 18 | 57 | No | 47 | 16.4See [bug 171216](https://webkit.org/b/171216). | 60 | 60 | 57 | 47 | 16.4See [bug 171216](https://webkit.org/b/171216). | 8.0 |
| `postMessage` | 2 | 12 | 41 | 10 | 10.6 | 5 | 4.4 | 18 | 41 | 11 | 4.2 | 1.0 |
| `start` | 2 | 12 | 41 | 10 | 10.6 | 5 | 4.4 | 18 | 41 | 11 | 4.2 | 1.0 |
| `worker_support` | 4 | 12 | 41 | 10 | ≤15 | 5 | ≤37 | 18 | 41 | ≤14 | 5 | 1.0 |


See also
--------


* [Using channel messaging](channel_messaging_api/using_channel_messaging)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MessagePort>

Metadata
========



**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `Metadata` interface contains information about a file system entry. This metadata includes the file's size and modification date and time.

  **Note:** This interface isn't available through the global scope; instead, you obtain a `Metadata` object describing a [`FileSystemEntry`](filesystementry) using the method [`FileSystemEntry.getMetadata()`](filesystementry/getmetadata).

 

Instance properties
-------------------


 
[`modificationTime`](metadata/modificationtime) Read only   Experimental   Non-standard 
  A [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) object indicating the date and time the entry was modified.

  
[`size`](metadata/size) Read only   Experimental   Non-standard 
  A 64-bit unsigned integer indicating the size of the entry in bytes.

  
Specifications
--------------


This feature has been removed from all specification and is not in the process of being standardized.


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Metadata` | 13 | 79 | No | No | No | No | No | 18 | No | No | No | 1.0 |
| `modificationTime` | 13 | 79 | No | No | No | No | No | 18 | No | No | No | 1.0 |
| `size` | 13 | 79 | No | No | No | No | No | 18 | No | No | No | 1.0 |


See also
--------


* [File and Directory Entries API](file_and_directory_entries_api)
* [Introduction to the File and Directory Entries API](file_and_directory_entries_api/introduction)
* [`FileSystemEntry`](filesystementry)
* [`FileSystemFileEntry`](filesystemfileentry) and [`FileSystemDirectoryEntry`](filesystemdirectoryentry)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Metadata>

MIDIConnectionEvent
===================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `MIDIConnectionEvent` interface of the [Web MIDI API](web_midi_api) is the event passed to the [`statechange`](midiaccess/statechange_event) event of the [`MIDIAccess`](midiaccess) interface and the [`statechange`](midiport/statechange_event) event of the [`MIDIPort`](midiport) interface. This occurs any time a new port becomes available, or when a previously available port becomes unavailable. For example, this event is fired whenever a MIDI device is either plugged in to or unplugged from a computer.


 Event MIDIConnectionEvent

Constructor
-----------


 [`MIDIConnectionEvent()`](midiconnectionevent/midiconnectionevent)  Creates a new `MIDIConnectionEvent` object.

  
Instance properties
-------------------


 
[`MIDIConnectionEvent.port`](midiconnectionevent/port) Read only 
  Returns a reference to a [`MIDIPort`](midiport) instance for a port that has been connected or disconnected."

  
Examples
--------



The [`Navigator.requestMIDIAccess()`](navigator/requestmidiaccess) method returns a promise that resolves with a [`MIDIAccess`](midiaccess) object. When a port changes state, a `MIDIConnectionEvent` is passed to [`statechange`](midiaccess/statechange_event) event. Information about the port can then be printed to the console.

 
```
navigator.requestMIDIAccess().then((access) => {
  access.onstatechange = (event) => {
    console.log(event.port.name, event.port.manufacturer, event.port.state);
  };
});

```


Specifications
--------------




| Specification |
| --- |
| [Web MIDI API # midiconnectionevent-interface](https://webaudio.github.io/web-midi-api/#midiconnectionevent-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MIDIConnectionEvent` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `MIDIConnectionEvent` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `port` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MIDIConnectionEvent>

MIDIInput
=========



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `MIDIInput` interface of the [Web MIDI API](web_midi_api) receives messages from a MIDI input port.


 EventTarget MIDIPort MIDIInput

Instance properties
-------------------


*This interface doesn't implement any specific properties, but inherits properties from [`MIDIPort`](midiport).*


Instance methods
----------------


*This interface doesn't implement any specific methods, but inherits methods from [`MIDIPort`](midiport).*


### Events


 [`midimessage`](midiinput/midimessage_event)  Fired when the current port receives a MIDI message.

  
Examples
--------



In the following example the name of each `MIDIInput` is printed to the console. Then, `midimessage` events are listened for on all input ports. When a message is received the [`MIDIMessageEvent.data`](midimessageevent/data) property is printed to the console.

 
```
inputs.forEach((input) => {
  console.log(input.name); /\* inherited property from MIDIPort \*/
  input.onmidimessage = (message) => {
    console.log(message.data);
  };
});

```


Specifications
--------------




| Specification |
| --- |
| [Web MIDI API # midiinput-interface](https://webaudio.github.io/web-midi-api/#midiinput-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MIDIInput` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `midimessage_event` | 43 | 79 | 10897–108 | No | 30 | No | No | 43 | No | 30 | No | 4.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MIDIInput>

MIDIInputMap
============


The `MIDIInputMap` read-only interface of the [Web MIDI API](web_midi_api) provides a [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)-like interface to the currently available MIDI input ports. Though it works generally like a map, because it is read-only it does **not** contain `clear()`, `delete()`, or `set()` functions.


Specifications
--------------




| Specification |
| --- |
| [Web MIDI API # midiinputmap-interface](https://webaudio.github.io/web-midi-api/#midiinputmap-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@iterator` | 43 | 79 | 108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `MIDIInputMap` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `entries` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `forEach` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `get` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `has` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `keys` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `size` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `values` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MIDIInputMap>

MIDIMessageEvent
================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `MIDIMessageEvent` interface of the [Web MIDI API](web_midi_api) represents the event passed to the [`midimessage`](midiinput/midimessage_event) event of the [`MIDIInput`](midiinput) interface. A `midimessage` event is fired every time a MIDI message is sent from a device represented by a [`MIDIInput`](midiinput), for example when a MIDI keyboard key is pressed, a knob is tweaked, or a slider is moved.


 Event MIDIMessageEvent

Constructor
-----------


 [`MIDIMessageEvent()`](midimessageevent/midimessageevent)  Creates a new `MIDIMessageEvent` object instance.

  
Instance properties
-------------------



*This interface also inherits properties from [`Event`](event).*

  [`MIDIMessageEvent.data`](midimessageevent/data)  A [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) containing the data bytes of a single MIDI message. See the [MIDI specification](https://www.midi.org/specifications-old/item/table-1-summary-of-midi-message) for more information on its form.

  

Instance methods
----------------


*This interface doesn't implement any specific methods, but inherits methods from [`Event`](event).*


Examples
--------



The following example prints all MIDI messages to the console.

 
```
navigator.requestMIDIAccess().then((midiAccess) => {
  Array.from(midiAccess.inputs).forEach((input) => {
    input[1].onmidimessage = (msg) => {
      console.log(msg);
    };
  });
});

```


Specifications
--------------




| Specification |
| --- |
| [Web MIDI API # midimessageevent-interface](https://webaudio.github.io/web-midi-api/#midimessageevent-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MIDIMessageEvent` | 43 | 79 | 10897–108 | No | 30 | No | No | 43 | No | 30 | No | 4.0 |
| `MIDIMessageEvent` | 43 | 79 | 10897–108 | No | 30 | No | No | 43 | No | 30 | No | 4.0 |
| `data` | 43 | 79 | 10897–108 | No | 30 | No | No | 43 | No | 30 | No | 4.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MIDIMessageEvent>

MIDIOutput
==========



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `MIDIOutput` interface of the [Web MIDI API](web_midi_api) provides methods to add messages to the queue of an output device, and to clear the queue of messages.


 EventTarget MIDIPort MIDIOutput

Instance properties
-------------------


*This interface doesn't implement any specific properties, but inherits properties from [`MIDIPort`](midiport).*


Instance methods
----------------



*This interface also inherits methods from [`MIDIPort`](midiport).*

  [`MIDIoutput.send()`](midioutput/send)  Queues a message to be sent to the MIDI port.

  [`MIDIOutput.clear()`](midioutput/clear)  Clears any pending send data from the queue.

  

Examples
--------



The following example sends a middle C immediately on MIDI channel 1.

 
```
function sendMiddleC(midiAccess, portID) {
  const noteOnMessage = [0x90, 60, 0x7f]; // note on, middle C, full velocity
  const output = midiAccess.outputs.get(portID);
  output.send(noteOnMessage); // sends the message.
}

```


Specifications
--------------




| Specification |
| --- |
| [Web MIDI API # MIDIOutput](https://webaudio.github.io/web-midi-api/#MIDIOutput) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MIDIOutput` | 43 | 79 | 10897–108 | No | 30 | No | No | 43 | No | 30 | No | 4.0 |
| `clear` | NoSee [bug 471798](https://crbug.com/471798). | NoSee [bug 471798](https://crbug.com/471798). | 10897–108 | No | NoSee [bug 471798](https://crbug.com/471798). | No | NoSee [bug 471798](https://crbug.com/471798). | NoSee [bug 471798](https://crbug.com/471798). | No | NoSee [bug 471798](https://crbug.com/471798). | No | NoSee [bug 471798](https://crbug.com/471798). |
| `send` | 43 | 79 | 10897–108 | No | 30 | No | No | 43 | No | 30 | No | 4.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MIDIOutput>

MIDIOutputMap
=============


The `MIDIOutputMap` read-only interface of the [Web MIDI API](web_midi_api) provides a [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)-like interface to the currently available MIDI output ports. Although it works like a map, because it is read-only, it does **not** contain `clear()`, `delete()`, or `set()` functions.


Specifications
--------------




| Specification |
| --- |
| [Web MIDI API # midiinputmap-interface](https://webaudio.github.io/web-midi-api/#midiinputmap-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@iterator` | 43 | 79 | 108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `MIDIOutputMap` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `entries` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `forEach` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `get` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `has` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `keys` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `size` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `values` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MIDIOutputMap>

MouseEvent
==========



 The `MouseEvent` interface represents events that occur due to the user interacting with a pointing device (such as a mouse). Common events using this interface include [`click`](element/click_event), [`dblclick`](element/dblclick_event), [`mouseup`](element/mouseup_event), [`mousedown`](element/mousedown_event). 

  `MouseEvent` derives from [`UIEvent`](uievent), which in turn derives from [`Event`](event). Though the [`MouseEvent.initMouseEvent()`](mouseevent/initmouseevent) method is kept for backward compatibility, creating of a `MouseEvent` object should be done using the [`MouseEvent()`](mouseevent/mouseevent) constructor. 

 Several more specific events are based on `MouseEvent`, including [`WheelEvent`](wheelevent), [`DragEvent`](dragevent), and [`PointerEvent`](pointerevent).


 Event UIEvent MouseEvent

Constructor
-----------


 [`MouseEvent()`](mouseevent/mouseevent)  Creates a `MouseEvent` object.

  
Static properties
-----------------


 
[`MouseEvent.WEBKIT_FORCE_AT_MOUSE_DOWN`](mouseevent/webkit_force_at_mouse_down)  Non-standard  Read only 
  Minimum force necessary for a normal click.

  
[`MouseEvent.WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN`](mouseevent/webkit_force_at_force_mouse_down)  Non-standard  Read only 
  Minimum force necessary for a force click.

  
Instance properties
-------------------



*This interface also inherits properties of its parents, [`UIEvent`](uievent) and [`Event`](event).*

  
[`MouseEvent.altKey`](mouseevent/altkey) Read only 
  Returns `true` if the `alt` key was down when the mouse event was fired.

  
[`MouseEvent.button`](mouseevent/button) Read only 
  The button number that was pressed (if applicable) when the mouse event was fired.

  
[`MouseEvent.buttons`](mouseevent/buttons) Read only 
  The buttons being pressed (if any) when the mouse event was fired.

  
[`MouseEvent.clientX`](mouseevent/clientx) Read only 
  The X coordinate of the mouse pointer in local (DOM content) coordinates.

  
[`MouseEvent.clientY`](mouseevent/clienty) Read only 
  The Y coordinate of the mouse pointer in local (DOM content) coordinates.

  
[`MouseEvent.ctrlKey`](mouseevent/ctrlkey) Read only 
  Returns `true` if the `control` key was down when the mouse event was fired.

  
[`MouseEvent.layerX`](mouseevent/layerx)  Non-standard  Read only 
  Returns the horizontal coordinate of the event relative to the current layer.

  
[`MouseEvent.layerY`](mouseevent/layery)  Non-standard  Read only 
  Returns the vertical coordinate of the event relative to the current layer.

  
[`MouseEvent.metaKey`](mouseevent/metakey) Read only 
  Returns `true` if the `meta` key was down when the mouse event was fired.

  
[`MouseEvent.movementX`](mouseevent/movementx) Read only 
  The X coordinate of the mouse pointer relative to the position of the last [`mousemove`](element/mousemove_event) event.

  
[`MouseEvent.movementY`](mouseevent/movementy) Read only 
  The Y coordinate of the mouse pointer relative to the position of the last [`mousemove`](element/mousemove_event) event.

  
[`MouseEvent.offsetX`](mouseevent/offsetx) Read only 
  The X coordinate of the mouse pointer relative to the position of the padding edge of the target node.

  
[`MouseEvent.offsetY`](mouseevent/offsety) Read only 
  The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node.

  
[`MouseEvent.pageX`](mouseevent/pagex) Read only 
  The X coordinate of the mouse pointer relative to the whole document.

  
[`MouseEvent.pageY`](mouseevent/pagey) Read only 
  The Y coordinate of the mouse pointer relative to the whole document.

  
[`MouseEvent.relatedTarget`](mouseevent/relatedtarget) Read only 
  The secondary target for the event, if there is one.

  
[`MouseEvent.screenX`](mouseevent/screenx) Read only 
  The X coordinate of the mouse pointer in global (screen) coordinates.

  
[`MouseEvent.screenY`](mouseevent/screeny) Read only 
  The Y coordinate of the mouse pointer in global (screen) coordinates.

  
[`MouseEvent.shiftKey`](mouseevent/shiftkey) Read only 
  Returns `true` if the `shift` key was down when the mouse event was fired.

  
`MouseEvent.mozPressure`  Non-standard   Deprecated  Read only 
   The amount of pressure applied to a touch or tablet device when generating the event; this value ranges between `0.0` (minimum pressure) and `1.0` (maximum pressure). Instead of using this deprecated (and non-standard) property, you should use [`PointerEvent`](pointerevent) and look at its [`pressure`](pointerevent/pressure) property. 

  
[`MouseEvent.mozInputSource`](mouseevent/mozinputsource)  Non-standard  Read only 
   The type of device that generated the event (one of the `MOZ_SOURCE_*` constants). This lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event). 

  
[`MouseEvent.webkitForce`](mouseevent/webkitforce)  Non-standard  Read only 
  The amount of pressure applied when clicking.

  
[`MouseEvent.x`](mouseevent/x) Read only 
  Alias for [`MouseEvent.clientX`](mouseevent/clientx).

  
[`MouseEvent.y`](mouseevent/y) Read only 
  Alias for [`MouseEvent.clientY`](mouseevent/clienty).

  

Instance methods
----------------



*This interface also inherits methods of its parents, [`UIEvent`](uievent) and [`Event`](event).*

  [`MouseEvent.getModifierState()`](mouseevent/getmodifierstate)  Returns the current state of the specified modifier key. See [`KeyboardEvent.getModifierState()`](keyboardevent/getmodifierstate) for details.

  
[`MouseEvent.initMouseEvent()`](mouseevent/initmouseevent)  Deprecated 
  Initializes the value of a `MouseEvent` created. If the event has already been dispatched, this method does nothing.

  

Example
-------


 This example demonstrates simulating a click (programmatically generating a click event) on a checkbox using DOM methods. Event state (canceled or not) is then determined with the return value of method [`EventTarget.dispatchEvent()`](eventtarget/dispatchevent). 


### HTML



```
<p>
  <label><input type="checkbox" id="checkbox" /> Checked</label>
</p>
<p>
  <button id="button">Click me to send a MouseEvent to the checkbox</button>
</p>

```

### JavaScript



```
function simulateClick() {
  // Get the element to send a click event
  const cb = document.getElementById("checkbox");

  // Create a synthetic click MouseEvent
  let evt = new MouseEvent("click", {
    bubbles: true,
    cancelable: true,
    view: window,
  });

  // Send the event to the checkbox element
  cb.dispatchEvent(evt);
}
document.getElementById("button").addEventListener("click", simulateClick);

```

### Result



Specifications
--------------




| Specification |
| --- |
| [UI Events # interface-mouseevent](https://w3c.github.io/uievents/#interface-mouseevent) |
| [CSSOM View Module # extensions-to-the-mouseevent-interface](https://w3c.github.io/csswg-drafts/cssom-view/#extensions-to-the-mouseevent-interface) |
| [Pointer Lock 2.0 # extensions-to-the-mouseevent-interface](https://w3c.github.io/pointerlock/#extensions-to-the-mouseevent-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MouseEvent` | 26 | 12 | 11 | No | 15 | 7 | 4.4 | 26 | 14 | 14 | 7 | 1.5 |
| `MouseEvent` | 1 | 12 | 1 | 9 | 10.6 | 1 | 4.4 | 18 | 4 | 11 | 1 | 1.0 |
| `altKey` | 1 | 12 | 1.5 | 9 | ≤12.1 | 1 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `button` | 1 | 12 | 1 | 9 | 10.6 | 1 | ≤37 | 18 | 4 | 11 | 1 | 1.0 |
| `buttons` | 43 | 12 | 15Restrictions apply depending on OS. | 9 | 30 | 11.1 | 43 | 43 | 15 | 30 | 11.3 | 4.0 |
| `clientX` | 1 | 12 | 1 | 9 | 10.6 | 1 | ≤37 | 18 | 4 | 11 | 1 | 1.0 |
| `clientY` | 1 | 12 | 1.5 | 9 | ≤12.1 | 1 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `ctrlKey` | 1 | 12 | 1.5 | 9 | ≤12.1 | 1 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `getModifierState` | 47 | 12 | 15 | 9 | 34 | 12.1 | 47 | 47 | 15 | 34 | 12.2 | 5.0 |
| `initMouseEvent` | 1 | 12 | 1.5 | 9 | ≤12.1 | 1 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `layerX` | 1 | 12 | 1 | 9 | 15 | 1 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `layerY` | 1 | 12 | 1 | 9 | 15 | 1 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `metaKey` | 1 | 12 | 1.5 | 9 | ≤12.1 | 1 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `movementX` | 3722–37 | 13 | 411–41 | No | 2415–24 | 96–8 | 374.4–37 | 3725–37 | 414–41 | 2414–24 | 86–8 | 3.01.0–3.0 |
| `movementY` | 3722–37 | 13 | 411–41 | No | 2415–24 | 96–8 | 374.4–37 | 3725–37 | 414–41 | 2414–24 | 86–8 | 3.01.0–3.0 |
| `offsetX` | 1 | 12 | 39 | 9 | ≤12.1 | 1 | ≤37 | 18 | 43 | ≤12.1 | 1 | 1.0 |
| `offsetY` | 1 | 12 | 39 | 9 | ≤12.1 | 1 | ≤37 | 18 | 43 | ≤12.1 | 1 | 1.0 |
| `pageX` | 1 | 12 | 1.5 | 9 | ≤12.1 | 1 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `pageY` | 1 | 12 | 1.5 | 9 | ≤12.1 | 1 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `region` | 51 | 79 | 32 | No | 38 | No | No | 51 | 32 | No | No | No |
| `relatedTarget` | 1 | 12 | 1.5 | 9 | ≤12.1 | 1 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `screenX` | 1 | 12 | 1.5 | 9 | ≤12.1 | 1 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `screenY` | 1 | 12 | 1.5 | 9 | ≤12.1 | 1 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `shiftKey` | 1 | 12 | 1.5 | 9 | ≤12.1 | 1 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `x` | 1 | 12 | 53 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 53 | ≤12.1 | 2 | 1.0 |
| `y` | 1 | 12 | 53 | 9 | ≤12.1 | 3.1 | ≤37 | 18 | 53 | ≤12.1 | 2 | 1.0 |


See also
--------


* Its direct parent, [`UIEvent`](uievent)
* [`PointerEvent`](pointerevent): For advanced pointer events, including multi-touch


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent>

MIDIAccess
==========



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `MIDIAccess` interface of the [Web MIDI API](web_midi_api) provides methods for listing MIDI input and output devices, and obtaining access to those devices.


 EventTarget MIDIAccess

Instance properties
-------------------


 
[`MIDIAccess.inputs`](midiaccess/inputs) Read only 
  Returns an instance of [`MIDIInputMap`](midiinputmap) which provides access to any available MIDI input ports.

  
[`MIDIAccess.outputs`](midiaccess/outputs) Read only 
  Returns an instance of [`MIDIOutputMap`](midioutputmap) which provides access to any available MIDI output ports.

  
[`MIDIAccess.sysexEnabled`](midiaccess/sysexenabled) Read only 
  A boolean attribute indicating whether system exclusive support is enabled on the current MIDIAccess instance.

  
### Events


 [`MIDIAccess.statechange_event`](midiaccess/statechange_event)  Called whenever a new MIDI port is added or an existing port changes state.

  
Examples
--------



The [`Navigator.requestMIDIAccess()`](navigator/requestmidiaccess) method returns a promise that resolves with a [`MIDIAccess`](midiaccess) object. Information about the input and output ports is returned.

 When a port changes state, information about that port is printed to the console.

 
```
navigator.requestMIDIAccess().then((access) => {
  // Get lists of available MIDI controllers
  const inputs = access.inputs.values();
  const outputs = access.outputs.values();

  access.onstatechange = (event) => {
    // Print information about the (dis)connected MIDI controller
    console.log(event.port.name, event.port.manufacturer, event.port.state);
  };
});

```


Specifications
--------------




| Specification |
| --- |
| [Web MIDI API # midiaccess-interface](https://webaudio.github.io/web-midi-api/#midiaccess-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MIDIAccess` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `inputs` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `outputs` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `statechange_event` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `sysexEnabled` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MIDIAccess>

MIDIPort
========



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `MIDIPort` interface of the [Web MIDI API](web_midi_api) represents a MIDI input or output port.

 A `MIDIPort` instance is created when a new MIDI device is connected. Therefore it has no constructor.


 EventTarget MIDIPort

Instance properties
-------------------


 
[`MIDIPort.id`](midiport/id) Read only 
  Returns a string containing the unique ID of the port.

  
[`MIDIPort.manufacturer`](midiport/manufacturer) Read only 
  Returns a string containing the manufacturer of the port.

  
[`MIDIPort.name`](midiport/name) Read only 
  Returns a string containing the system name of the port.

  
[`MIDIPort.type`](midiport/type) Read only 
  Returns a string containing the type of the port, one of:

  `"input"`  The `MIDIPort` is an input port.

  `"output"`  The `MIDIPort` is an output port.

    
[`MIDIPort.version`](midiport/version) Read only 
  Returns a string containing the version of the port.

  
[`MIDIPort.state`](midiport/state) Read only 
  Returns a string containing the state of the port, one of:

  `"disconnected"`  The device that this `MIDIPort` represents is disconnected from the system.

  `"connected"`  The device that this `MIDIPort` represents is currently connected.

    
[`MIDIPort.connection`](midiport/connection) Read only 
  Returns a string containing the connection state of the port, one of:

  `"open"`  The device that this `MIDIPort` represents has been opened and is available.

  `"closed"`  The device that this `MIDIPort` represents has not been opened, or has been closed.

  `"pending"`  The device that this `MIDIPort` represents has been opened but has subsequently disconnected .

    
Instance methods
----------------



*This interface also inherits methods from [`EventTarget`](eventtarget).*

  [`MIDIPort.open()`](midiport/open)  Makes the MIDI device connected to this `MIDIPort` explicitly available, and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which resolves once access to the port has been successful.

  [`MIDIPort.close()`](midiport/close)  Makes the MIDI device connected to this `MIDIPort` unavailable, changing the [`state`](midiport/state) from `"open"` to `"closed"`. This returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which resolves once the port has been closed.

  

Events
------


 [`MIDIPort.statechange_event`](midiport/statechange_event)  Called when an existing port changes its state or connection.

  
Examples
--------


### List ports and their information



The following example lists input and output ports, and displays information about them using properties of `MIDIPort`.

 
```
function listInputsAndOutputs(midiAccess) {
  for (const entry of midiAccess.inputs) {
    const input = entry[1];
    console.log(
      `Input port [type:'${input.type}'] id:'${input.id}' manufacturer: '${input.manufacturer}' name: '${input.name}' version: '${input.version}'`
    );
  }

  for (const entry of midiAccess.outputs) {
    const output = entry[1];
    console.log(
      `Output port [type:'${output.type}'] id: '${output.id}' manufacturer: '${output.manufacturer}' name: '${output.name}' version: '${output.version}'`
    );
  }
}

```


### Add available ports to a select list



The following example takes the list of input ports and adds them to a select list, in order that a user can choose the device they want to use.

 
```
inputs.forEach((port, key) => {
  const opt = document.createElement("option");
  opt.text = port.name;
  document.getElementById("inputportselector").add(opt);
});

```


Specifications
--------------




| Specification |
| --- |
| [Web MIDI API # MIDIPort](https://webaudio.github.io/web-midi-api/#MIDIPort) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MIDIPort` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `close` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `connection` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `id` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `manufacturer` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `name` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `open` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `state` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `statechange_event` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `type` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `version` | 43 | 79 | 10897–108 | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MIDIPort>

MimeType
========



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The `MimeType` interface provides contains information about a MIME type associated with a particular plugin. [`Navigator.mimeTypes`](navigator/mimetypes) returns an array of this object.



Instance properties
-------------------


 
`MimeType.type`  Deprecated 
  Returns the MIME type of the associated plugin.

  
`MimeType.description`  Deprecated 
  Returns a description of the associated plugin or an empty string if there is none.

  
`MimeType.suffixes`  Deprecated 
  A string containing valid file extensions for the data displayed by the plugin, or an empty string if an extension is not valid for the particular module. For example, a browser's content decryption module may appear in the plugin list but support more file extensions than can be anticipated. It might therefore return an empty string.

  
`MimeType.enabledPlugin`  Deprecated 
  Returns an instance of [`Plugin`](plugin) containing information about the plugin itself.

  
Specifications
--------------




| Specification |
| --- |
| [HTML Standard # mimetype](https://html.spec.whatwg.org/multipage/obsolete.html#mimetype) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MimeType` | 1 | 12 | 1 | 11 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1–8 | 1.0 |
| `description` | 1 | 12 | 1 | 11 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1–8 | 1.0 |
| `enabledPlugin` | 1 | 12 | 1 | 11 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1–8 | 1.0 |
| `suffixes` | 1 | 12 | 1 | 11 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1–8 | 1.0 |
| `type` | 1 | 12 | 1 | 11 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1–8 | 1.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MimeType>

MimeTypeArray
=============



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The `MimeTypeArray` interface returns an array of [`MimeType`](mimetype) instances, each of which contains information about a supported browser plugins. This object is returned by [`Navigator.mimeTypes`](navigator/mimetypes).

  **Note:** This interface was an [attempt to create an unmodifiable list](https://stackoverflow.com/questions/74630989/why-use-domstringlist-rather-than-an-array/74641156#74641156) and only continues to be supported to not break code that's already using it. Modern APIs use types that wrap around ECMAScript array types instead, so you can treat them like ECMAScript arrays, and at the same time impose additional semantics on their usage (such as making their items read-only).

 

Instance properties
-------------------


 
`MimeTypeArray.length`  Deprecated 
  The number of items in the array.

  
Instance methods
----------------


 
`MimeTypeArray.item()`  Deprecated 
  Returns the `MimeType` object with the specified index.

  
`MimeTypeArray.namedItem()`  Deprecated 
  Returns the `MimeType` object with the specified name.

  
Example
-------



The following example tests whether a plugin is available for the 'application/pdf' mime type and if so, logs its description.

 
```
const mimeTypes = navigator.mimeTypes;
const pdf = mimeTypes.namedItem("application/pdf");

if (pdf) {
  console.log(pdf.description);
}

```


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # mimetypearray](https://html.spec.whatwg.org/multipage/obsolete.html#mimetypearray) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MimeTypeArray` | 1 | 12 | 1 | 4 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `item` | 1Before version 59, method parameters were optional | 12 | 1 | 11 | ≤12.1 | 4 | ≤37Before version 59, method parameters were optional | 18Before version 59, method parameters were optional | 4 | ≤12.1 | 3.2 | 1.0Before Samsung Internet 7.0, method parameters were optional |
| `length` | 1 | 12 | 1 | 4 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `namedItem` | 1Before version 59, method parameters were optional | 12 | 1 | 11 | ≤12.1 | 4 | ≤37Before version 59, method parameters were optional | 18Before version 59, method parameters were optional | 4 | ≤12.1 | 3.2 | 1.0Before Samsung Internet 7.0, method parameters were optional |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MimeTypeArray>

NavigateEvent
=============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `NavigateEvent` interface of the [Navigation API](navigation_api) is the event object for the [`navigate`](navigation/navigate_event) event, which fires when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated (this includes usage of [History API](history_api) features like [`History.go()`](history/go)). `NavigateEvent` provides access to information about that navigation, and allows developers to intercept and control the navigation handling.


 Event NavigateEvent

Constructor
-----------


 
[`NavigateEvent()`](navigateevent/navigateevent)  Experimental 
  Creates a new `NavigateEvent` object instance.

  
Instance properties
-------------------



*Inherits properties from its parent, [`Event`](event).*

  
[`canIntercept`](navigateevent/canintercept) Read only   Experimental 
  Returns `true` if the navigation can be intercepted, or `false` otherwise (e.g. you can't intercept a cross-origin navigation).

  
[`destination`](navigateevent/destination) Read only   Experimental 
  Returns a [`NavigationDestination`](navigationdestination) object representing the destination being navigated to.

  
[`downloadRequest`](navigateevent/downloadrequest) Read only   Experimental 
  Returns the filename of the file requested for download, in the case of a download navigation (e.g. an [`<a>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a) or [`<area>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area) element with a `download` attribute), or `null` otherwise.

  
[`formData`](navigateevent/formdata) Read only   Experimental 
  Returns the [`FormData`](formdata) object representing the submitted data in the case of a `POST` form submission, or `null` otherwise.

  
[`hashChange`](navigateevent/hashchange) Read only   Experimental 
  Returns `true` if the navigation is a fragment navigation (i.e. to a fragment identifier in the same document), or `false` otherwise.

  
[`info`](navigateevent/info) Read only   Experimental 
  Returns the `info` data value passed by the initiating navigation operation (e.g. [`Navigation.back()`](navigation/back), or [`Navigation.navigate()`](navigation/navigate)), or `undefined` if no `info` data was passed.

  
[`navigationType`](navigateevent/navigationtype) Read only   Experimental 
  Returns the type of the navigation — `push`, `reload`, `replace`, or `traverse`.

  
[`signal`](navigateevent/signal) Read only   Experimental 
  Returns an [`AbortSignal`](abortsignal), which will become aborted if the navigation is cancelled (e.g. by the user pressing the browser's "Stop" button, or another navigation starting and thus cancelling the ongoing one).

  
[`userInitiated`](navigateevent/userinitiated) Read only   Experimental 
  Returns `true` if the navigation was initiated by the user (e.g. by clicking a link, submitting a form, or pressing the browser's "Back"/"Forward" buttons), or `false` otherwise.

  

Instance methods
----------------



*Inherits methods from its parent, [`Event`](event).*

  
[`intercept()`](navigateevent/intercept)  Experimental 
  Intercepts this navigation, turning it into a same-document navigation to the [`destination`](navigationdestination/url) URL. It can accept a handler function that defines what the navigation handling behavior should be, plus `focusReset` and `scroll` options to control behavior as desired.

  
[`scroll()`](navigateevent/scroll)  Experimental 
  Can be called to manually trigger the browser-driven scrolling behavior that occurs in response to the navigation, if you want it to happen before the navigation handling has completed.

  

Examples
--------


### Handling a navigation using `intercept()`




```
navigation.addEventListener("navigate", (event) => {
  // Exit early if this navigation shouldn't be intercepted,
  // e.g. if the navigation is cross-origin, or a download request
  if (shouldNotIntercept(event)) return;

  const url = new URL(event.destination.url);

  if (url.pathname.startsWith("/articles/")) {
    event.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);
        renderArticlePage(articleContent);
      },
    });
  }
});

```
  **Note:** Before the Navigation API was available, to do something similar you'd have to listen for all click events on links, run `e.preventDefault()`, perform the appropriate [`History.pushState()`](history/pushstate) call, then set up the page view based on the new URL. And this wouldn't handle all navigations — only user-initiated link clicks.

 

### Handling scrolling using `scroll()`



In this example of intercepting a navigation, the `handler()` function starts by fetching and rendering some article content, but then fetches and renders some secondary content afterwards. It makes sense to scroll the page to the main article content as soon as it is available so the user can interact with it, rather than waiting until the secondary content is also rendered. To achieve this, we have added a [`scroll()`](navigateevent/scroll) call between the two.

 
```
navigation.addEventListener("navigate", (event) => {
  if (shouldNotIntercept(navigateEvent)) return;
  const url = new URL(event.destination.url);

  if (url.pathname.startsWith("/articles/")) {
    event.intercept({
      async handler() {
        const articleContent = await getArticleContent(url.pathname);
        renderArticlePage(articleContent);

        event.scroll();

        const secondaryContent = await getSecondaryContent(url.pathname);
        addSecondaryContent(secondaryContent);
      },
    });
  }
});

```


Specifications
--------------




| Specification |
| --- |
| [Unknown specification # navigate-event-class](https://wicg.github.io/navigation-api/#navigate-event-class) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `NavigateEvent` | 102 | 102 | No | No | No | No | 102 | 102 | No | 70 | No | 19.0 |
| `NavigateEvent` | 102 | 102 | No | No | No | No | 102 | 102 | No | 70 | No | 19.0 |
| `canIntercept` | 105 | 105 | No | No | No | No | 105 | 105 | No | 72 | No | 20.0 |
| `canTransition` | 102–108 | 102–108 | No | No | No | No | 102–108 | 102–108 | No | 70–73 | No | 19.0 |
| `destination` | 102 | 102 | No | No | No | No | 102 | 102 | No | 70 | No | 19.0 |
| `downloadRequest` | 102 | 102 | No | No | No | No | 102 | 102 | No | 70 | No | 19.0 |
| `formData` | 102 | 102 | No | No | No | No | 102 | 102 | No | 70 | No | 19.0 |
| `hashChange` | 102 | 102 | No | No | No | No | 102 | 102 | No | 70 | No | 19.0 |
| `info` | 102 | 102 | No | No | No | No | 102 | 102 | No | 70 | No | 19.0 |
| `intercept` | 105 | 105 | No | No | No | No | 105 | 105 | No | 72 | No | 20.0 |
| `navigationType` | 102 | 102 | No | No | No | No | 102 | 102 | No | 70 | No | 19.0 |
| `restoreScroll` | 102–108 | 102–108 | No | No | No | No | 102–108 | 102–108 | No | 70–73 | No | 19.0 |
| `scroll` | 105 | 105 | No | No | No | No | 105 | 105 | No | 72 | No | 20.0 |
| `signal` | 102 | 102 | No | No | No | No | 102 | 102 | No | 70 | No | 19.0 |
| `transitionWhile` | 102–108 | 102–108 | No | No | No | No | 102–108 | 102–108 | No | 70–73 | No | 19.0 |
| `userInitiated` | 102 | 102 | No | No | No | No | 102 | 102 | No | 70 | No | 19.0 |


See also
--------


* [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/)
* [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md)
* Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/NavigateEvent>

Navigation
==========



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `Navigation` interface of the [Navigation API](navigation_api) allows control over all navigation actions for the current `window` in one central place, including initiating navigations programmatically, examining navigation history entries, and managing navigations as they happen.

 It is accessed via the [`Window.navigation`](window/navigation) property.

 The Navigation API only exposes history entries created in the current browsing context that have the same origin as the current page (e.g. not navigations inside embedded [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe)s, or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than with the older [History API](history_api).


 EventTarget Navigation

Instance properties
-------------------



*Inherits properties from its parent, [`EventTarget`](eventtarget).*

  
[`canGoBack`](navigation/cangoback) Read only   Experimental 
   Returns `true` if it is possible to navigate backwards in the navigation history (i.e. the [`currentEntry`](navigation/currententry) is not the first one in the history entry list), and `false` if it is not. 

  
[`canGoForward`](navigation/cangoforward) Read only   Experimental 
   Returns `true` if it is possible to navigate forwards in the navigation history (i.e. the [`currentEntry`](navigation/currententry) is not the last one in the history entry list), and `false` if it is not. 

  
[`currentEntry`](navigation/currententry) Read only   Experimental 
   Returns a [`NavigationHistoryEntry`](navigationhistoryentry) object representing the location the user is currently navigated to right now. 

  
[`transition`](navigation/transition) Read only   Experimental 
   Returns a [`NavigationTransition`](navigationtransition) object representing the status of an in-progress navigation, which can be used to track it. Returns `null` if no navigation is currently in progress. 

  

Instance methods
----------------



*Inherits methods from its parent, [`EventTarget`](eventtarget).*

  
[`back()`](navigation/back)  Experimental 
  Navigates backwards by one entry in the navigation history.

  
[`entries()`](navigation/entries)  Experimental 
  Returns an array of [`NavigationHistoryEntry`](navigationhistoryentry) objects representing all existing history entries.

  
[`forward()`](navigation/forward)  Experimental 
  Navigates forwards by one entry in the navigation history.

  
[`navigate()`](navigation/navigate)  Experimental 
  Navigates to a specific URL, updating any provided state in the history entries list.

  
[`reload()`](navigation/reload)  Experimental 
  Reloads the current URL, updating any provided state in the history entries list.

  
[`traverseTo()`](navigation/traverseto)  Experimental 
  Navigates to a specific [`NavigationHistoryEntry`](navigationhistoryentry) identified by [`key`](navigationhistoryentry/key).

  
[`updateCurrentEntry()`](navigation/updatecurrententry)  Experimental 
   Updates the state of the [`currentEntry`](navigation/currententry); used in cases where the state change will be independent from a navigation or reload. 

  

Events
------


 
[`currententrychange`](navigation/currententrychange_event)  Experimental 
  Fired when the [`Navigation.currentEntry`](navigation/currententry) has changed.

  
[`navigate`](navigation/navigate_event)  Experimental 
  Fired when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated, allowing you to intercept as required.

  
[`navigateerror`](navigation/navigateerror_event)  Experimental 
  Fired when a navigation fails.

  
[`navigatesuccess`](navigation/navigatesuccess_event)  Experimental 
  Fired when a successful navigation has finished.

  
Examples
--------


### Moving forwards and backwards in the history



```
async function backHandler() {
  if (navigation.canGoBack) {
    await navigation.back().finished;
    // Handle any required clean-up after
    // navigation has finished
  } else {
    displayBanner("You are on the first page");
  }
}

async function forwardHandler() {
  if (navigation.canGoForward) {
    await navigation.forward().finished;
    // Handle any required clean-up after
    // navigation has finished
  } else {
    displayBanner("You are on the last page");
  }
}

```

### Traversing to a specific history entry



```
// On JS startup, get the key of the first loaded page
// so the user can always go back there.
const { key } = navigation.currentEntry;
backToHomeButton.onclick = () => navigation.traverseTo(key);

// Navigate away, but the button will always work.
await navigation.navigate("/another\_url").finished;

```

### Navigating and updating state




```
navigation.navigate(url, { state: newState });

```
 Or

 
```
navigation.reload({ state: newState });

```
 Or if the state is independent from a navigation or reload:

 
```
navigation.updateCurrentEntry({ state: newState });

```


Specifications
--------------




| Specification |
| --- |
| [Unknown specification # global](https://wicg.github.io/navigation-api/#global) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Navigation` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `back` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `canGoBack` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `canGoForward` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `currentEntry` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `currententrychange_event` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `entries` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `forward` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `navigate` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `navigate_event` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `navigateerror_event` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `navigatesuccess_event` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `reload` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `transition` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `traverseTo` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `updateCurrentEntry` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |


See also
--------


* [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/)
* [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md)
* Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Navigation>

NavigationDestination
=====================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `NavigationDestination` interface of the [Navigation API](navigation_api) represents the destination being navigated to in the current navigation.

 It is accessed via the [`NavigateEvent.destination`](navigateevent/destination) property.



Instance properties
-------------------


 
[`id`](navigationdestination/id) Read only   Experimental 
  Returns the [`id`](navigationhistoryentry/id) value of the destination [`NavigationHistoryEntry`](navigationhistoryentry) if the [`NavigateEvent.navigationType`](navigateevent/navigationtype) is `traverse`, or `null` otherwise.

  
[`index`](navigationdestination/index) Read only   Experimental 
  Returns the [`index`](navigationhistoryentry/index) value of the destination [`NavigationHistoryEntry`](navigationhistoryentry) if the [`NavigateEvent.navigationType`](navigateevent/navigationtype) is `traverse`, or `-1` otherwise.

  
[`key`](navigationdestination/key) Read only   Experimental 
  Returns the [`key`](navigationhistoryentry/key) value of the destination [`NavigationHistoryEntry`](navigationhistoryentry) if the [`NavigateEvent.navigationType`](navigateevent/navigationtype) is `traverse`, or `null` otherwise.

  
[`sameDocument`](navigationdestination/samedocument) Read only   Experimental 
  Returns `true` if the navigation is to the same `document` as the current [`Document`](document) value, or `false` otherwise.

  
[`url`](navigationdestination/url) Read only   Experimental 
  Returns the URL being navigated to.

  
Instance methods
----------------


 
[`getState()`](navigationdestination/getstate)  Experimental 
  Returns a clone of the available state associated with the destination [`NavigationHistoryEntry`](navigationhistoryentry), or navigation operation (e.g. [`navigate()`](navigation/navigate)) as appropriate.

  
Examples
--------



```
navigation.addEventListener("navigate", (event) => {
  // Exit early if this navigation shouldn't be intercepted,
  // e.g. if the navigation is cross-origin, or a download request
  if (shouldNotIntercept(event)) {
    return;
  }

  // Returns a URL() object constructed from the
  // NavigationDestination.url value
  const url = new URL(event.destination.url);

  if (url.pathname.startsWith("/articles/")) {
    event.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);
        renderArticlePage(articleContent);
      },
    });
  }
});

```

Specifications
--------------




| Specification |
| --- |
| [Unknown specification # navigationdestination](https://wicg.github.io/navigation-api/#navigationdestination) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `NavigationDestination` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `getState` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `id` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `index` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `key` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `sameDocument` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `url` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |


See also
--------


* [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/)
* [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md)
* Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/NavigationDestination>

MouseScrollEvent
================



**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.


**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The `MouseScrollEvent` interface represents events that occur due to the user moving a mouse wheel or similar input device.

  **Warning:** Do not use this interface for wheel events.

 Like `MouseWheelEvent`, this interface is non-standard and deprecated. It was used in Gecko-based browsers only. Instead use the standard *[`WheelEvent`](wheelevent).*

 

Method overview
---------------



```
void initMouseScrollEvent(
  in DOMString typeArg,
  in boolean canBubbleArg,
  in boolean cancelableArg,
  in nsIDOMAbstractView viewArg,
  in long detailArg,
  in long screenXArg,
  in long screenYArg,
  in long clientXArg,
  in long clientYArg,
  in boolean ctrlKeyArg,
  in boolean altKeyArg,
  in boolean shiftKeyArg,
  in boolean metaKeyArg,
  in unsigned short buttonArg,
  in nsIDOMEventTarget relatedTargetArg,
  in long axis);

```

Attributes
----------




| Attribute | Type | Description |
| --- | --- | --- |
| `axis` Read only  | `long` | Indicates scroll direction. |


Constants
---------


### Delta modes




| Constant | Value | Description |
| --- | --- | --- |
| `HORIZONTAL_AXIS` | `0x01` | The event is caused by horizontal wheel operation. |
| `VERTICAL_AXIS` | `0x02` | The event is caused by vertical wheel operation. |


Instance methods
----------------


 `initMouseScrollEvent()`  See `nsIDOMMouseScrollEvent::initMouseScrollEvent()`.

  
Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MouseScrollEvent` | No | No | 3.5 | No | No | No | No | No | 4 | No | No | No |


See also
--------


* `DOMMouseScroll`
* `MozMousePixelScroll`
* Standardized mouse wheel event object: [`WheelEvent`](wheelevent)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MouseScrollEvent>

MutationEvent
=============



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The `MutationEvent` interface provides event properties that are specific to modifications to the Document Object Model (DOM) hierarchy and nodes.

  **Note:** Using *mutation events* is problematic:

 * Their design is [flawed](https://lists.w3.org/Archives/Public/public-webapps/2011JulSep/0779.html).
* Adding DOM mutation listeners to a document [profoundly degrades the performance](https://groups.google.com/d/topic/mozilla.dev.platform/L0Lx11u5Bvs?pli=1) of further DOM modifications to that document (making them 1.5 - 7 times slower!). Moreover, removing the listeners does not reverse the damage.
* They have poor cross-browser compatibility: Safari doesn't support `DOMAttrModified` (see [WebKit bug 8191](https://webkit.org/b/8191)) and Firefox doesn't support *mutation name events* (like `DOMElementNameChanged` and `DOMAttributeNameChanged`).

 They have been deprecated in favor of [mutation observers](mutationobserver). **Consider using these instead.**

 
 Event MutationEvent

Instance properties
-------------------



*This interface also inherits properties from its parent [`UIEvent`](uievent), and indirectly from [`Event`](event).*

  
[`MutationEvent.attrChange`](mutationevent/attrchange) Read only   Deprecated 
  Indicates what kind of change triggered the `DOMAttrModified` event. It can be `MODIFICATION` (`1`), `ADDITION` (`2`) or `REMOVAL` (`3`). It has no meaning for other events and is then set to `0`.

  
[`MutationEvent.attrName`](mutationevent/attrname) Read only   Deprecated 
  Indicates the name of the node affected by the `DOMAttrModified` event. It has no meaning for other events and is then set to the empty string (`""`).

  
[`MutationEvent.newValue`](mutationevent/newvalue) Read only   Deprecated 
  In `DOMAttrModified` events, contains the new value of the modified [`Attr`](attr) node. In `DOMCharacterDataModified` events, contains the new value of the modified [`CharacterData`](characterdata) node. In all other cases, returns the empty string (`""`).

  
[`MutationEvent.prevValue`](mutationevent/prevvalue) Read only   Deprecated 
  In `DOMAttrModified` events, contains the previous value of the modified [`Attr`](attr) node. In `DOMCharacterDataModified` events, contains previous new value of the modified[`CharacterData`](characterdata) node. In all other cases, returns the empty string (`""`).

  
[`MutationEvent.relatedNode`](mutationevent/relatednode) Read only   Deprecated 
  Indicates the node related to the event, like the changed node inside the subtree for `DOMSubtreeModified`.

  

Instance methods
----------------


 
[`MutationEvent.initMutationEvent()`](mutationevent/initmutationevent)  Deprecated 
  Constructor method that returns a new `MutationEvent` configured with the parameters given.

  
Mutation events list
--------------------



The following is a list of all mutation events:

 * `DOMAttrModified` (Not supported by Safari)
* `DOMAttributeNameChanged` (Not supported by Firefox)
* `DOMCharacterDataModified`
* `DOMElementNameChanged` (Not supported by Firefox)
* `DOMNodeInserted`
* `DOMNodeInsertedIntoDocument`
* `DOMNodeRemoved`
* `DOMNodeRemovedFromDocument`
* `DOMSubtreeModified`



Examples
--------



You can register a listener for mutation events using [`EventTarget.addEventListener()`](eventtarget/addeventlistener) as follows:

 
```
element.addEventListener(
  "DOMNodeInserted",
  (event) => {
    // …
  },
  false
);

```


Specifications
--------------




| Specification |
| --- |
| [UI Events # interface-mutationevent](https://w3c.github.io/uievents/#interface-mutationevent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MutationEvent` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `attrChange` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `attrName` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `initMutationEvent` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `newValue` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `prevValue` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `relatedNode` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* [`MutationObserver`](mutationobserver)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MutationEvent>

MutationObserver
================


The [`MutationObserver`](mutationobserver) interface provides the ability to watch for changes being made to the [DOM](document_object_model) tree. It is designed as a replacement for the older [Mutation Events](mutationevent) feature, which was part of the DOM3 Events specification.


Constructor
-----------


 [`MutationObserver()`](mutationobserver/mutationobserver)  Creates and returns a new `MutationObserver` which will invoke a specified callback function when DOM changes occur.

  
Instance methods
----------------


 [`disconnect()`](mutationobserver/disconnect)  Stops the `MutationObserver` instance from receiving further notifications until and unless [`observe()`](mutationobserver/observe) is called again.

  [`observe()`](mutationobserver/observe)  Configures the `MutationObserver` to begin receiving notifications through its callback function when DOM changes matching the given options occur.

  [`takeRecords()`](mutationobserver/takerecords)  Removes all pending notifications from the `MutationObserver`'s notification queue and returns them in a new [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of [`MutationRecord`](mutationrecord) objects.

  
Mutation Observer & customize resize event listener & demo
----------------------------------------------------------


<https://codepen.io/milofultz/pen/LYjPXPw>


Example
-------



The following example was adapted from [this blog post](https://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/).

 
```
// Select the node that will be observed for mutations
const targetNode = document.getElementById("some-id");

// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
const callback = (mutationList, observer) => {
  for (const mutation of mutationList) {
    if (mutation.type === "childList") {
      console.log("A child node has been added or removed.");
    } else if (mutation.type === "attributes") {
      console.log(`The ${mutation.attributeName} attribute was modified.`);
    }
  }
};

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();

```


Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-mutationobserver](https://dom.spec.whatwg.org/#interface-mutationobserver) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MutationObserver` | 2618 | 12 | 14 | 11 | 15 | 76 | ≤374.4 | 2618 | 14 | 14 | 76 | 1.51.0 |
| `MutationObserver` | 2618 | 12 | 14 | 11 | 15 | 76 | ≤374.4 | 2618 | 14 | 14 | 76 | 1.51.0 |
| `disconnect` | 18 | 12 | 14 | 11 | 15 | 6 | 4.4 | 18 | 14 | 14 | 6 | 1.0 |
| `observe` | 18Before Chrome 33, `attributes: true` is required when using `attributeFilter` or `attributeOldValue`. If `attributes: true` is not present, then Chrome throws a syntax error. | 12Before Edge 79, `attributes: true` is required when using `attributeFilter` or `attributeOldValue`. If `attributes: true` is not present, then Edge throws a syntax error. | 14Before Firefox 36, `attributes: true` is required when using `attributeFilter` or `attributeOldValue`. If `attributes: true` is not present, then Firefox throws a syntax error. | 11Internet Explorer requires `attributes: true` when using `attributeFilter` or `attributeOldValue`. If `attributes: true` is not present, then Internet Explorer throws a syntax error. | 15Before Opera 20, `attributes: true` is required when using `attributeFilter` or `attributeOldValue`. If `attributes: true` is not present, then Opera throws a syntax error. | 6Before Safari 10.1, `attributes: true` is required when using `attributeFilter` or `attributeOldValue`. If `attributes: true` is not present, then Safari throws a syntax error. | 4.4Before WebView 4.4.3, `attributes: true` is required when using `attributeFilter` or `attributeOldValue`. If `attributes: true` is not present, then WebView throws a syntax error. | 18Before Chrome 33, `attributes: true` is required when using `attributeFilter` or `attributeOldValue`. If `attributes: true` is not present, then Chrome throws a syntax error. | 14Before Firefox 36, `attributes: true` is required when using `attributeFilter` or `attributeOldValue`. If `attributes: true` is not present, then Firefox throws a syntax error. | 14Before Opera 20, `attributes: true` is required when using `attributeFilter` or `attributeOldValue`. If `attributes: true` is not present, then Opera throws a syntax error. | 6Before Safari iOS 10.3, `attributes: true` is required when using `attributeFilter` or `attributeOldValue`. If `attributes: true` is not present, then Safari throws a syntax error. | 1.0Before Samsung Internet 2.0, `attributes: true` is required when using `attributeFilter` or `attributeOldValue`. If `attributes: true` is not present, then Samsung Internet throws a syntax error. |
| `takeRecords` | 20 | 12 | 14 | 11 | 15 | 6 | 4.4 | 25 | 14 | 14 | 6 | 1.5 |


See also
--------


* [`PerformanceObserver`](performanceobserver)
* [`ResizeObserver`](resizeobserver)
* [`IntersectionObserver`](intersectionobserver)
* [A brief overview](https://developer.chrome.com/blog/detect-dom-changes-with-mutation-observers/)
* [A more in-depth discussion](https://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/)
* [A screencast by Chromium developer Rafael Weinstein](https://www.youtube.com/watch?v=eRZ4pO0gVWw)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver>

MutationRecord
==============


The [`MutationRecord`](mutationrecord) is a read-only interface that represents an individual DOM mutation observed by a [`MutationObserver`](mutationobserver). It is the object inside the array passed to the callback of a [`MutationObserver`](mutationobserver).


Instance properties
-------------------


 
[`MutationRecord.addedNodes`](mutationrecord/addednodes) Read only 
  The nodes added by a mutation. Will be an empty [`NodeList`](nodelist) if no nodes were added.

  
[`MutationRecord.attributeName`](mutationrecord/attributename) Read only 
  The name of the changed attribute as a string, or `null`.

  
[`MutationRecord.attributeNamespace`](mutationrecord/attributenamespace) Read only 
  The namespace of the changed attribute as a string, or `null`.

  
[`MutationRecord.nextSibling`](mutationrecord/nextsibling) Read only 
  The next sibling of the added or removed nodes, or `null`.

  
[`MutationRecord.oldValue`](mutationrecord/oldvalue) Read only 
  The value depends on the [`MutationRecord.type`](mutationrecord/type):

 * For `attributes`, it is the value of the changed attribute before the change.
* For `characterData`, it is the data of the changed node before the change.
* For `childList`, it is `null`.

  
[`MutationRecord.previousSibling`](mutationrecord/previoussibling) Read only 
  The previous sibling of the added or removed nodes, or `null`.

  
[`MutationRecord.removedNodes`](mutationrecord/removednodes) Read only 
  The nodes removed by a mutation. Will be an empty [`NodeList`](nodelist) if no nodes were removed.

  
[`MutationRecord.target`](mutationrecord/target) Read only 
  The node the mutation affected, depending on the `MutationRecord.type`.

 * For `attributes`, it is the element whose attribute changed.
* For `characterData`, it is the `CharacterData` node.
* For `childList`, it is the node whose children changed.

  
[`MutationRecord.type`](mutationrecord/type) Read only 
  A string representing the type of mutation: `attributes` if the mutation was an attribute mutation, `characterData` if it was a mutation to a `CharacterData` node, and `childList` if it was a mutation to the tree of nodes.

  
Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-mutationrecord](https://dom.spec.whatwg.org/#interface-mutationrecord) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `MutationRecord` | 16 | 12 | 14 | 11 | 15 | 7 | 4.4 | 18 | 14 | 14 | 7 | 1.0 |
| `addedNodes` | 16 | 12 | 14 | 11 | 15 | 7 | 4.4 | 18 | 14 | 14 | 7 | 1.0 |
| `attributeName` | 16 | 12 | 14 | 11 | 15 | 7 | 4.4 | 18 | 14 | 14 | 7 | 1.0 |
| `attributeNamespace` | 16 | 12 | 14 | 11 | 15 | 7 | 4.4 | 18 | 14 | 14 | 7 | 1.0 |
| `nextSibling` | 16 | 12 | 14 | 11 | 15 | 7 | 4.4 | 18 | 14 | 14 | 7 | 1.0 |
| `oldValue` | 16 | 12 | 14 | 11 | 15 | 7 | 4.4 | 18 | 14 | 14 | 7 | 1.0 |
| `previousSibling` | 16 | 12 | 14 | 11 | 15 | 7 | 4.4 | 18 | 14 | 14 | 7 | 1.0 |
| `removedNodes` | 16 | 12 | 14 | 11 | 15 | 7 | 4.4 | 18 | 14 | 14 | 7 | 1.0 |
| `target` | 16 | 12 | 14 | 11 | 15 | 7 | 4.4 | 18 | 14 | 14 | 7 | 1.0 |
| `type` | 16 | 12 | 14 | 11 | 15 | 7 | 4.4 | 18 | 14 | 14 | 7 | 1.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/MutationRecord>

NamedNodeMap
============



The `NamedNodeMap` interface represents a collection of [`Attr`](attr) objects. Objects inside a `NamedNodeMap` are not in any particular order, unlike [`NodeList`](nodelist), although they may be accessed by an index as in an array.

 A `NamedNodeMap` object is *live* and will thus be auto-updated if changes are made to its contents internally or elsewhere.

  **Note:** Although called `NamedNodeMap`, this interface doesn't deal with [`Node`](node) objects but with [`Attr`](attr) objects, which are a specialized class of [`Node`](node) objects.

 

Instance properties
-------------------



*This interface doesn't inherit any property.*

  
[`NamedNodeMap.length`](namednodemap/length) Read only 
  Returns the amount of objects in the map.

  

Instance methods
----------------



*This interface doesn't inherit any method.*

  [`NamedNodeMap.getNamedItem()`](namednodemap/getnameditem)  Returns an [`Attr`](attr), corresponding to the given name.

  [`NamedNodeMap.setNamedItem()`](namednodemap/setnameditem)  Replaces, or adds, the [`Attr`](attr) identified in the map by the given name.

  [`NamedNodeMap.removeNamedItem()`](namednodemap/removenameditem)  Removes the [`Attr`](attr) identified by the given map.

  [`NamedNodeMap.item()`](namednodemap/item)  Returns the [`Attr`](attr) at the given index, or `null` if the index is higher or equal to the number of nodes.

  [`NamedNodeMap.getNamedItemNS()`](namednodemap/getnameditemns)  Returns an [`Attr`](attr) identified by a namespace and related local name.

  [`NamedNodeMap.setNamedItemNS()`](namednodemap/setnameditemns)  Replaces, or adds, the [`Attr`](attr) identified in the map by the given namespace and related local name.

  [`NamedNodeMap.removeNamedItemNS()`](namednodemap/removenameditemns)  Removes the [`Attr`](attr) identified by the given namespace and related local name.

  

Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-namednodemap](https://dom.spec.whatwg.org/#interface-namednodemap) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `NamedNodeMap` | 1 | 12 | 3422–341–22 | 5 | ≤12.1 | 1 | 4.4 | 18 | 3422–344–22 | ≤12.1 | 1 | 1.0 |
| `getNamedItem` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `getNamedItemNS` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `item` | 1 | 12 | 1 | 5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `length` | 1 | 12 | 1 | 5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `removeNamedItem` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `removeNamedItemNS` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `setNamedItem` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `setNamedItemNS` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* [`Element.attributes`](element/attributes)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/NamedNodeMap>

NavigationCurrentEntryChangeEvent
=================================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `NavigationCurrentEntryChangeEvent` interface of the [Navigation API](navigation_api) is the event object for the [`currententrychange`](navigation/currententrychange_event) event, which fires when the [`Navigation.currentEntry`](navigation/currententry) has changed.

 This event will fire for same-document navigations (e.g. [`back()`](navigation/back) or [`traverseTo()`](navigation/traverseto)), replacements (i.e. a [`navigate()`](navigation/navigate) call with `history` set to `replace`), or other calls that change the entry's state (e.g. [`updateCurrentEntry()`](navigation/updatecurrententry), or the [History API](history_api)'s [`History.replaceState()`](history/replacestate)).

 This event fires after the navigation is committed, meaning that the visible URL has changed and the [`NavigationHistoryEntry`](navigationhistoryentry) update has occurred. It is useful for migrating from usage of older API features like the [`hashchange`](window/hashchange_event) or [`popstate`](window/popstate_event) events.


 Event NavigationCurrentEntryChangeEvent

Constructor
-----------


 
[`NavigationCurrentEntryChangeEvent()`](navigationcurrententrychangeevent/navigationcurrententrychangeevent)  Experimental 
  Creates a new `NavigationCurrentEntryChangeEvent` object instance.

  
Instance properties
-------------------



*Inherits properties from its parent, [`Event`](event).*

  
[`from`](navigationcurrententrychangeevent/from) Read only   Experimental 
  Returns the [`NavigationHistoryEntry`](navigationhistoryentry) that was navigated from.

  
[`navigationType`](navigationcurrententrychangeevent/navigationtype) Read only   Experimental 
  Returns the type of the navigation that resulted in the change.

  

Examples
--------



Navigation data reporting:

 
```
navigation.addEventListener("currententrychange", () => {
  const data = navigation.currentEntry.getState();
  submitAnalyticsData(data.analytics);
});

```
 Setting up a per-entry event:

 
```
navigation.addEventListener("currententrychange", () => {
  navigation.currentEntry.addEventListener("dispose", genericDisposeHandler);
});

```


Specifications
--------------




| Specification |
| --- |
| [Unknown specification # navigationcurrententrychangeevent](https://wicg.github.io/navigation-api/#navigationcurrententrychangeevent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `NavigationCurrentEntryChangeEvent` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `NavigationCurrentEntryChangeEvent` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `from` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `navigationType` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |


See also
--------


* [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/)
* [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md)
* Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/NavigationCurrentEntryChangeEvent>

NavigationHistoryEntry
======================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `NavigationHistoryEntry` interface of the [Navigation API](navigation_api) represents a single navigation history entry.

 These objects are commonly accessed via the [`Navigation.currentEntry`](navigation/currententry) property and [`Navigation.entries()`](navigation/entries) method.

 The Navigation API only exposes history entries created in the current browsing context that have the same origin as the current page (e.g. not navigations inside embedded [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe)s, or cross-origin navigations), providing an accurate list of all previous history entries just for your app. This makes traversing the history a much less fragile proposition than with the older [History API](history_api).


 EventTarget NavigationHistoryEntry

Instance properties
-------------------



*Inherits properties from its parent, [`EventTarget`](eventtarget).*

  
[`id`](navigationhistoryentry/id) Read only   Experimental 
  Returns the `id` of the history entry. This is a unique, UA-generated value that always represents a specific history entry, useful to correlate it with an external resource such as a storage cache.

  
[`index`](navigationhistoryentry/index) Read only   Experimental 
  Returns the index of the history entry in the history entries list (that is, the list returned by [`Navigation.entries()`](navigation/entries)), or `-1` if the entry does not appear in the list.

  
[`key`](navigationhistoryentry/key) Read only   Experimental 
  Returns the `key` of the history entry. This is a unique, UA-generated value that represents the history entry's slot in the entries list rather than the entry itself. It is used to navigate that particular slot via [`Navigation.traverseTo()`](navigation/traverseto). The `key` will be reused by other entries that replace the entry in the list (that is, if the [`NavigateEvent.navigationType`](navigateevent/navigationtype) is `replace`).

  
[`sameDocument`](navigationhistoryentry/samedocument) Read only   Experimental 
  Returns `true` if this history entry is for the same `document` as the current [`Document`](document) value, or `false` otherwise.

  
[`url`](navigationhistoryentry/url) Read only   Experimental 
  Returns the absolute URL of this history entry.

  

Instance methods
----------------



*Inherits methods from its parent, [`EventTarget`](eventtarget).*

  
[`getState()`](navigationhistoryentry/getstate)  Experimental 
  Returns a clone of the available state associated with this history entry.

  

Events
------


 
[`dispose`](navigationhistoryentry/dispose_event)  Experimental 
  Fires when the entry is no longer part of the history entry list.

  
Examples
--------



```
function initHomeBtn() {
  // Get the key of the first loaded entry
  // so the user can always go back to this view.
  const { key } = navigation.currentEntry;
  backToHomeButton.onclick = () => {
    navigation.traverseTo(key);
  };
}
// Intercept navigate events, such as link clicks, and
// replace them with single-page navigations
navigation.addEventListener("navigate", (event) => {
  event.intercept({
    async handler() {
      // Navigate to a different view,
      // but the "home" button will always work.
    },
  });
});

```

Specifications
--------------




| Specification |
| --- |
| [Unknown specification # navigationhistoryentry](https://wicg.github.io/navigation-api/#navigationhistoryentry) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `NavigationHistoryEntry` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `dispose_event` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `getState` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `id` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `index` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `key` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `sameDocument` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `url` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |


See also
--------


* [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/)
* [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md)
* Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/NavigationHistoryEntry>

NavigationTransition
====================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `NavigationTransition` interface of the [Navigation API](navigation_api) represents an ongoing navigation, that is, a navigation that hasn't yet reached the [`navigatesuccess`](navigation/navigatesuccess_event) or [`navigateerror`](navigation/navigateerror_event) stage.

 It is accessed via the [`Navigation.transition`](navigation/transition) property.



Instance properties
-------------------


 
[`finished`](navigationtransition/finished) Read only   Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that fulfills at the same time the [`navigatesuccess`](navigation/navigatesuccess_event) event fires, or rejects at the same time the [`navigateerror`](navigation/navigateerror_event) event fires.

  
[`from`](navigationtransition/from) Read only   Experimental 
  Returns the [`NavigationHistoryEntry`](navigationhistoryentry) that the transition is coming from.

  
[`navigationType`](navigationtransition/navigationtype) Read only   Experimental 
  Returns the type of the ongoing navigation.

  
Examples
--------



```
async function cleanupNavigation() {
  await navigation.transition.finished;
  // Navigation has completed successfully
  // Cleanup any ongoing monitoring
}

```

Specifications
--------------




| Specification |
| --- |
| [Unknown specification # navigationtransition](https://wicg.github.io/navigation-api/#navigationtransition) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `NavigationTransition` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `finished` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `from` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |
| `navigationType` | 102 | 102 | No | No | 88 | No | 102 | 102 | No | 70 | No | 19.0 |


See also
--------


* [Modern client-side routing: the Navigation API](https://developer.chrome.com/docs/web-platform/navigation-api/)
* [Navigation API explainer](https://github.com/WICG/navigation-api/blob/main/README.md)
* Domenic Denicola's [Navigation API live demo](https://gigantic-honored-octagon.glitch.me/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/NavigationTransition>

Navigator
=========



The `Navigator` interface represents the state and the identity of the user agent. It allows scripts to query it and to register themselves to carry on some activities.

 A `Navigator` object can be retrieved using the read-only [`window.navigator`](window/navigator) property.



Instance properties
-------------------


*Doesn't inherit any properties.*


### Standard properties


 
[`Navigator.connection`](navigator/connection) Read only   Experimental 
  Provides a [`NetworkInformation`](networkinformation) object containing information about the network connection of a device.

  
[`Navigator.cookieEnabled`](navigator/cookieenabled) Read only 
  Returns false if setting a cookie will be ignored and true otherwise.

  
[`Navigator.credentials`](navigator/credentials) Read only 
  Returns the [`CredentialsContainer`](credentialscontainer) interface which exposes methods to request credentials and notify the user agent when interesting events occur such as successful sign in or sign out.

  
[`Navigator.deviceMemory`](navigator/devicememory) Read only   Experimental 
  Returns the amount of device memory in gigabytes. This value is an approximation given by rounding to the nearest power of 2 and dividing that number by 1024.

  
[`Navigator.geolocation`](navigator/geolocation) Read only 
  Returns a [`Geolocation`](geolocation) object allowing accessing the location of the device.

  
[`Navigator.gpu`](navigator/gpu) Read only   Experimental 
  Returns the [`GPU`](gpu) object for the current browsing context. The entry point for the [WebGPU API](webgpu_api).

  
[`Navigator.hid`](navigator/hid) Read only   Experimental 
   Returns an [`HID`](hid) object providing methods for connecting to HID devices, listing attached HID devices, and event handlers for connected HID devices. 

  
[`Navigator.hardwareConcurrency`](navigator/hardwareconcurrency) Read only 
  Returns the number of logical processor cores available.

  
[`Navigator.ink`](navigator/ink) Read only   Experimental 
  Returns an [`Ink`](ink) object for the current document, providing access to [Ink API](ink_api) functionality.

  
[`Navigator.keyboard`](navigator/keyboard) Read only   Experimental 
  Returns a [`Keyboard`](keyboard) object which provides access to functions that retrieve keyboard layout maps and toggle capturing of key presses from the physical keyboard.

  
[`Navigator.language`](navigator/language) Read only 
  Returns a string representing the preferred language of the user, usually the language of the browser UI. The `null` value is returned when this is unknown.

  
[`Navigator.languages`](navigator/languages) Read only 
  Returns an array of strings representing the languages known to the user, by order of preference.

  
[`Navigator.locks`](navigator/locks) Read only 
  Returns a [`LockManager`](lockmanager) object that provides methods for requesting a new [`Lock`](lock) object and querying for an existing [`Lock`](lock) object.

  
[`Navigator.maxTouchPoints`](navigator/maxtouchpoints) Read only 
  Returns the maximum number of simultaneous touch contact points are supported by the current device.

  
[`Navigator.mediaCapabilities`](navigator/mediacapabilities) Read only 
  Returns a [`MediaCapabilities`](mediacapabilities) object that can expose information about the decoding and encoding capabilities for a given format and output capabilities.

  
[`Navigator.mediaDevices`](navigator/mediadevices) Read only 
  Returns a reference to a [`MediaDevices`](mediadevices) object which can then be used to get information about available media devices ([`MediaDevices.enumerateDevices()`](mediadevices/enumeratedevices)), find out what constrainable properties are supported for media on the user's computer and user agent ([`MediaDevices.getSupportedConstraints()`](mediadevices/getsupportedconstraints)), and to request access to media using [`MediaDevices.getUserMedia()`](mediadevices/getusermedia).

  
[`Navigator.mediaSession`](navigator/mediasession) Read only 
  Returns [`MediaSession`](mediasession) object which can be used to provide metadata that can be used by the browser to present information about the currently-playing media to the user, such as in a global media controls UI.

  
[`Navigator.onLine`](navigator/online) Read only 
  Returns a boolean value indicating whether the browser is working online.

  
[`Navigator.pdfViewerEnabled`](navigator/pdfviewerenabled) Read only 
  Returns `true` if the browser can display PDF files inline when navigating to them, and `false` otherwise.

  
[`Navigator.permissions`](navigator/permissions) Read only 
  Returns a [`Permissions`](permissions) object that can be used to query and update permission status of APIs covered by the [Permissions API](permissions_api).

  
[`Navigator.presentation`](navigator/presentation) Read only 
  Returns a reference to the [`Presentation`](presentation) API.

  
[`Navigator.serial`](navigator/serial) Read only   Experimental 
  Returns a [`Serial`](serial) object, which represents the entry point into the [`Web Serial API`](web_serial_api) to enable the control of serial ports.

  
[`Navigator.serviceWorker`](navigator/serviceworker) Read only 
  Returns a [`ServiceWorkerContainer`](serviceworkercontainer) object, which provides access to registration, removal, upgrade, and communication with the [`ServiceWorker`](serviceworker) objects for the [associated document](https://html.spec.whatwg.org/multipage/browsers.html#concept-document-window).

  
[`Navigator.storage`](navigator/storage) Read only 
  Returns the singleton [`StorageManager`](storagemanager) object used for managing persistence permissions and estimating available storage on a site-by-site/app-by-app basis.

  
[`Navigator.userActivation`](navigator/useractivation) Read only 
  Returns a [`UserActivation`](useractivation) object containing information about the current window's user activation state.

  
[`Navigator.userAgent`](navigator/useragent) Read only 
  Returns the user agent string for the current browser.

  
[`Navigator.userAgentData`](navigator/useragentdata) Read only   Experimental 
  Returns a [`NavigatorUAData`](navigatoruadata) object, which gives access to information about the browser and operating system of the user.

  
[`Navigator.virtualKeyboard`](navigator/virtualkeyboard) Read only   Experimental 
  Returns a reference to the [`VirtualKeyboard`](virtualkeyboard) API, to take control of the on-screen virtual keyboard.

  
[`Navigator.webdriver`](navigator/webdriver) Read only 
  Indicates whether the user agent is controlled by automation.

  
[`Navigator.windowControlsOverlay`](navigator/windowcontrolsoverlay) Read only 
  Returns the [`WindowControlsOverlay`](windowcontrolsoverlay) interface which exposes information about the geometry of the title bar in desktop Progressive Web Apps, and an event to know whenever it changes.

  
[`Navigator.xr`](navigator/xr) Read only   Experimental 
  Returns [`XRSystem`](xrsystem) object, which represents the entry point into the [WebXR API](webxr_device_api).

  
### Non-standard properties


 
[`Navigator.buildID`](navigator/buildid)  Non-standard 
  Returns the build identifier of the browser. In modern browsers this property now returns a fixed timestamp as a privacy measure, e.g. `20181001000000` in Firefox 64 onwards.

  
[`Navigator.contacts`](navigator/contacts) Read only   Experimental 
  Returns a [`ContactsManager`](contactsmanager) interface which allows users to select entries from their contact list and share limited details of the selected entries with a website or application.

  
[`Navigator.globalPrivacyControl`](navigator/globalprivacycontrol)  Non-standard   Experimental 
  Returns a boolean indicating a user's consent to their information being shared or sold.

  
`Navigator.securitypolicy`  Non-standard 
  Returns an empty string. In Netscape 4.7x, returns "US & CA domestic policy" or "Export policy".

  
`Navigator.standalone`  Non-standard 
  Returns a boolean indicating whether the browser is running in standalone mode. Available on Apple's iOS Safari only.

  
[`Navigator.wakeLock`](navigator/wakelock) Read only 
  Returns a [`WakeLock`](wakelock) interface you can use to request screen wake locks and prevent screen from dimming, turning off, or showing a screen saver.

  
### Deprecated properties


 
[`Navigator.appCodeName`](navigator/appcodename) Read only   Deprecated 
  Always returns `'Mozilla'`, in any browser.

  
[`Navigator.appName`](navigator/appname) Read only   Deprecated 
  Always returns `'Netscape'`, in any browser.

  
[`Navigator.appVersion`](navigator/appversion) Read only   Deprecated 
  Returns the version of the browser as a string. Do not rely on this property to return the correct value.

  
[`Navigator.activeVRDisplays`](navigator/activevrdisplays) Read only   Deprecated   Non-standard 
  Returns an array containing every [`VRDisplay`](vrdisplay) object that is currently presenting ([`VRDisplay.ispresenting`](vrdisplay/ispresenting) is `true`).

  
[`Navigator.doNotTrack`](navigator/donottrack) Read only   Deprecated 
  Reports the value of the user's do-not-track preference. When this value is "1", your web site or application should not track the user.

  
[`Navigator.mimeTypes`](navigator/mimetypes) Read only   Deprecated 
  Returns an [`MimeTypeArray`](mimetypearray) listing the MIME types supported by the browser.

  
[`Navigator.oscpu`](navigator/oscpu) Read only   Deprecated 
  Returns a string that represents the current operating system.

  
[`Navigator.platform`](navigator/platform) Read only   Deprecated 
  Returns a string representing the platform of the browser. Do not rely on this function to return a significant value.

  
[`Navigator.plugins`](navigator/plugins) Read only   Deprecated 
  Returns a [`PluginArray`](pluginarray) listing the plugins installed in the browser.

  
[`Navigator.product`](navigator/product) Read only   Deprecated 
  Always returns `'Gecko'`, in any browser.

  
[`Navigator.productSub`](navigator/productsub) Read only   Deprecated 
  Returns either the string `'20030107'`, or `'"20100101'`.

  
[`Navigator.vendor`](navigator/vendor) Read only   Deprecated 
  Returns either the empty string, `'Apple Computer Inc.'`, or `'Google Inc.'`.

  
[`Navigator.vendorSub`](navigator/vendorsub) Read only   Deprecated 
  Always returns the empty string.

  
Instance methods
----------------



*Doesn't inherit any method.*

  [`Navigator.canShare()`](navigator/canshare)  Returns `true` if a call to `Navigator.share()` would succeed.

  [`Navigator.clearAppBadge()`](navigator/clearappbadge)  Clears a badge on the current app's icon and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined).

  
[`Navigator.getAutoplayPolicy()`](navigator/getautoplaypolicy)  Experimental 
  Returns a value indicating whether the specified media element, audio context, or media feature "type" is allowed to autoplay.

  [`Navigator.getBattery()`](navigator/getbattery)  Returns a promise that resolves with a [`BatteryManager`](batterymanager) object that returns information about the battery charging status.

  [`Navigator.registerProtocolHandler()`](navigator/registerprotocolhandler)  Allows web sites to register themselves as a possible handler for a given protocol.

  [`Navigator.unregisterProtocolHandler()`](navigator/unregisterprotocolhandler)  Unregister a website that is a handler for a given protocol.

  [`Navigator.requestMediaKeySystemAccess()`](navigator/requestmediakeysystemaccess)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) for a MediaKeySystemAccess object.

  [`Navigator.requestMIDIAccess()`](navigator/requestmidiaccess)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) representing a request for access to MIDI devices on the user's system.

  [`Navigator.sendBeacon()`](navigator/sendbeacon)  Used to asynchronously transfer a small amount of data using [HTTP](https://developer.mozilla.org/en-US/docs/Glossary/HTTP) from the User Agent to a web server.

  [`Navigator.setAppBadge()`](navigator/setappbadge)  Sets a badge on the icon associated with this app and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined).

  [`Navigator.share()`](navigator/share)  Invokes the native sharing mechanism of the current platform.

  [`Navigator.vibrate()`](navigator/vibrate)  Causes vibration on devices with support for it. Does nothing if vibration support isn't available.

  

### Deprecated methods


 
[`Navigator.getVRDisplays()`](navigator/getvrdisplays)  Deprecated   Non-standard 
  Returns a promise that resolves to an array of [`VRDisplay`](vrdisplay) objects representing any available VR devices connected to the computer.

  
[`Navigator.getUserMedia()`](navigator/getusermedia)  Deprecated 
  After having prompted the user for permission, returns the audio or video stream associated to a camera or microphone on the local computer.

  
[`Navigator.taintEnabled()`](navigator/taintenabled)  Deprecated 
  Returns `false`. JavaScript taint/untaint functions removed in JavaScript 1.2.

  
[`Navigator.javaEnabled()`](navigator/javaenabled)  Deprecated 
  Always returns false.

  
Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-navigator-object](https://html.spec.whatwg.org/multipage/system-state.html#the-navigator-object) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Navigator` | 1 | 12 | 1 | 4 | 3 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `activeVRDisplays` | No | 15–79WebVR content requires a Windows Mixed Reality headset or the Windows Mixed Reality Portal Simulator. | 9864–98macOS support was enabled in Firefox 64.55–98Windows support was enabled in Firefox 55. | No | No | No | No | 79–80Supported only by Google Daydream. | 55 | No | No | 12.0–13.0Supported only by Google Daydream. |
| `appCodeName` | 1 | 12 | 1 | 4 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `appName` | 1 | 12 | 1 | 4 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `appVersion` | 1 | 12 | 1 | 4 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `authentication` | 67 | 79 | No | No | 54 | No | No | 67 | No | No | No | No |
| `bluetooth` | 56Before Chrome 70, this feature was only supported in macOS. In Chrome 70, support was added for Windows 10. Linux support is not enabled by default.56In Linux and versions of Windows earlier than 10, this flag must be enabled. | 79Supported by default only on macOS and Windows 10. Linux support is not enabled by default.79In Linux and versions of Windows earlier than 10, this flag must be enabled. | No | No | 43Before Opera 57, this feature was only supported in macOS. In Opera 57, support was added for Windows 10. Linux support is not enabled by default.43In Linux and versions of Windows earlier than 10, this flag must be enabled. | No | NoSee [bug 1100993](https://crbug.com/1100993). | 56 | No | 43 | No | 6.0 |
| `buildID` | No | No | 2Since Firefox 64, this property returns a fixed timestamp as a privacy measure - `20181001000000`. | No | No | No | No | No | 4Since Firefox 64, this property returns a fixed timestamp as a privacy measure - `20181001000000`. | No | No | No |
| `canShare` | 89Only supported on Chrome OS and Windows, see [bug 770595](https://crbug.com/770595) and [bug 1144920](https://crbug.com/1144920). | 9389–93Only supported on Windows. | 96 | No | 75Only supported on Opera OS and Windows, see [bug 770595](https://crbug.com/770595) and [bug 1144920](https://crbug.com/1144920). | 14 | No | 75 | 96 | 54 | 14 | 11.0 |
| `clearAppBadge` | 81Windows and macOS only. | 81Windows and macOS only. | No | No | No | No | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `clipboard` | 66 | 79 | 63 | No | 53 | 13.1 | 66 | 66 | 63 | 47 | 13.4 | 9.0 |
| `connection` | 61 | 79 | 31–32 | No | 48 | NoSee [bug 185697](https://webkit.org/b/185697). | 50 | 38 | 14–99 | 37 | NoSee [bug 185697](https://webkit.org/b/185697). | 3.0 |
| `contacts` | No | No | No | No | No | No | 80 | 80 | No | 57 | 14.5 | 13.0 |
| `cookieEnabled` | 1 | 12 | 1Before Firefox 8, `navigator.cookieEnabled` would report the wrong result if a site exception was in place for the page on which the check was performed. This has been fixed. | 4`navigator.cookieEnabled` returns `true` even if the browser is set to block cookies (for example, if the page is in the *Restricted sites* security zone). | ≤12.1 | 1 | 4.4 | 18 | 4Before Firefox 8, `navigator.cookieEnabled` would report the wrong result if a site exception was in place for the page on which the check was performed. This has been fixed. | ≤12.1 | 1 | 1.0 |
| `credentials` | 51 | 18 | 60 | No | 38 | 13 | 51 | 51 | 60 | 41 | 13 | 5.0 |
| `deviceMemory` | 63 | 79 | No | No | 50 | No | 63 | 63 | No | 46 | No | 8.0 |
| `doNotTrack` | 23 | 17Before version 17, Edge implemented `window.doNotTrack`. | 9["In Firefox, `navigator.doNotTrack` returns `\"unspecified\"` instead of `null`.", "Before Firefox 32, `navigator.doNotTrack` would report values of `\"yes\"` and `\"no\"` rather than `\"1\"` and `\"0\"`."] | 9–11For IE11 and subsequent versions, use `window.doNotTrack` | 12 | 5.1–7 | 4.4 | 25 | 9["In Firefox, `navigator.doNotTrack` returns `\"unspecified\"` instead of `null`.", "Before Firefox 32, `navigator.doNotTrack` would report values of `\"yes\"` and `\"no\"` rather than `\"1\"` and `\"0\"`."] | 12 | 5–7 | 1.5 |
| `geolocation` | 5 | 12 | 3.5 | 9 | 10.6 | 5 | ≤37 | 18 | 4 | 11 | ≤3 | 1.0 |
| `getAutoplayPolicy` | No | No | 112 | No | No | No | No | No | 112 | No | No | No |
| `getBattery` | 38 | 79 | 43–52 | No | 25 | No | 38 | 38 | 43–52 | 25 | No | 3.0 |
| `getGamepads` | 3521 | 12 | 29 | No | 2215 | 10.1 | 37≤37 | 3525 | 32 | 2214 | 10.3 | 3.01.5 |
| `getInstalledRelatedApps` | 85Only supported on Windows. Resolves with an empty array on other platforms.80–85Always resolves with an empty array. | 85Only supported on Windows. Resolves with an empty array on other platforms.80–85Always resolves with an empty array. | No | No | 71Only supported on Windows. Resolves with an empty array on other platforms.67–71Always resolves with an empty array. | No | No | 80 | No | No | No | 13.0 |
| `getUserMedia` | 5321 | 7912 | 17 | No | 401512–15 | 11–12 | 5340 | 5325 | 24 | 411412–14 | 11–12 | 6.01.5 |
| `getVRDisplays` | NoAvailable on all platforms behind a flag, but currently only works on desktop in an [experimental version of Chrome](https://webvr.info/get-chrome/) (other builds won't return any devices when `Navigator.getVRDisplays()` is invoked). | 15–79 | 9864–98macOS support was enabled in Firefox 64.55–98Windows support was enabled in Firefox 55. | No | No | No | No | 79–80Currently supported only by Google Daydream. | 55 | No | No | 12.0–13.0Currently supported only by Google Daydream. |
| `globalPrivacyControl` | No | No | 95 | No | No | No | No | No | No | No | No | No |
| `gpu` | 113Currently supported on ChromeOS, macOS, and Windows only. | 113Currently supported on EdgeOS, macOS, and Windows only. | previewCurrently supported on Linux and Windows only. | No | NoCurrently supported on OperaOS, macOS, and Windows only. | No | No | No | No | No | No | No |
| `hardwareConcurrency` | 37 | 15 | 48 | No | 24 | 10.1–11 | 37 | 37 | 48 | 24 | 10.3–11 | 3.0 |
| `hid` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `ink` | 94 | 93 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `javaEnabled` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `keyboard` | 68 | 79 | No | No | 55 | No | 68 | 68 | No | 48 | No | 10.0 |
| `language` | 1 | 12 | 1Before Firefox 4, this property's value was also part of the user agent string, as reported by `navigator.userAgent`. Starting in Firefox 5, this property's value is based on the value of the `Accept-Language` [HTTP header](https://developer.mozilla.org/docs/Web/HTTP/Headers). | 11Closest available (non-standard) properties are `userLanguage` and `browserLanguage`. | 4 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `languages` | 37Before Chrome 65, `navigator.languages[0]` is not guaranteed to equal `navigator.language`. | 16 | 32In Firefox, the `navigator.languages` property's value is taken from the `intl.accept_languages` preference. | NoClosest available (non-standard) properties are `userLanguage` and `browserLanguage`. | 24 | 10.1 | 37Before version 65, `navigator.languages[0]` is not guaranteed to equal `navigator.language`. | 37Before Chrome 65, `navigator.languages[0]` is not guaranteed to equal `navigator.language`. | 32In Firefox, the `navigator.languages` property's value is taken from the `intl.accept_languages` preference. | 24 | 10.3 | 3.0 |
| `locks` | 69 | 79 | 96 | No | 56 | 15.4 | 69 | 69 | 96 | 48 | 15.4 | 10.0 |
| `maxTouchPoints` | 35 | 12 | 59 | 1110 | 22 | 13 | 37 | 35 | 79 | 22 | 13 | 3.0 |
| `mediaCapabilities` | 66 | 79 | 63 | No | 55 | 13 | 66 | 66 | 63 | 48 | 13 | 9.0 |
| `mediaDevices` | 47 | 12 | 36 | No | 34 | 11 | 47 | 47 | 36 | 34 | 11 | 5.0 |
| `mediaSession` | 73 | 79 | 82 | No | 60 | 15 | No | 57 | 82 | 43 | 15 | 7.0 |
| `mimeTypes` | 1 | 12 | 1 | 4 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `onLine` | 2Earlier versions of Chrome incorrectly return true when a tab is first opened, but it starts reporting the correct connectivity status after the first network event. Windows: 11, macOS: 14, Chrome OS: 13, Linux: Always returns `true`. For history, see [crbug.com/7469](https://crbug.com/7469). | 12 | 1.5Since Firefox 4 the browser returns `true` when 'Work Offline' mode is disabled and `false` when it is enabled, regardless of actual connectivity. Since Firefox 41, on OS X and Windows, the returned values follow the actual network connectivity, unless 'Work offline' mode is selected (where it will always return `false`). | 4in Internet Explorer 8 'online' and 'offline' events are raised on the `document.body`; under IE 9 they are raised on both `document.body` and `window`. | 3From Opera 11.1 until Opera 12.1, the browser returns `true` when 'Work Offline' mode is disabled and `false` when it is enabled, regardless of actual connectivity. | 4 | ≤37Can incorrectly return true, see [bug 811122](https://crbug.com/811122). | 18 | 4 | 10.1From Opera 11.1 until Opera 12.1, the browser returns `true` when 'Work Offline' mode is disabled and `false` when it is enabled, regardless of actual connectivity. | 3.2 | 1.0 |
| `oscpu` | No | No | 1The preference `"general.oscpu.override"` can be used to set a value to be returned instead of the true CPU description. The preference setting is ignored for calls made by privileged code, which continue to get the actual CPU description. | No | No | No | No | No | 4The preference `"general.oscpu.override"` can be used to set a value to be returned instead of the true CPU description. The preference setting is ignored for calls made by privileged code, which continue to get the actual CPU description. | No | No | No |
| `pdfViewerEnabled` | 94 | 94 | 99 | No | 80 | 16.4 | 94 | 94 | 99 | 66 | 16.4 | 17.0 |
| `permissions` | 43 | 79 | 46 | No | 30 | 16 | NoSee [bug 490120](https://crbug.com/490120). | 43 | 46 | 30 | 16 | 4.0 |
| `platform` | 1 | 12 | 1["Before Firefox 69, `platform` would report running on a 32-bit CPU if running the 32-bit version of Firefox on a 64-bit system.", "You can override the value returned by `platform` by setting the preference `general.platform.override` to the string you wish to be returned instead."] | 4 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `plugins` | 1 | 12 | 1 | 4 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `presentation` | 47 | 79 | No | No | 34 | No | NoSee [bug 521319](https://crbug.com/521319). | 47 | No | 34 | No | 5.0 |
| `product` | 1 | 12 | 1 | 11 | 15 | 1 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `productSub` | 1Always returns `20030107`. | 12Always returns `20030107`. | 1 | No | 15Always returns `20030107`. | 1Always returns `20030107`. | 4.4Always returns `20030107`. | 18Always returns `20030107`. | 4 | 14Always returns `20030107`. | 1Always returns `20030107`. | 1.0Always returns `20030107`. |
| `registerProtocolHandler` | 13From Chrome 77, the URL parameter only accepts `http` or `https` URLs. | 79 | 2 | No | 11.6 | No | No | No | 4 | No | No | No |
| `requestMIDIAccess` | 43 | 79 | 108API access is gated by installation of a [site permission add-on](https://support.mozilla.org/en-US/kb/site-permission-addons) (user prompt), secure context, and [Permission Policy: `midi`](https://developer.mozilla.org/docs/Web/HTTP/Headers/Feature-Policy/midi).97–108["Version 107 and later, API use is gated by a site permission add-on that is automatically generated by Firefox.", "Version 105 and later, the `dom.webmidi.gated` preference may be set `false` to allow WebMIDI to be used without a site permission addon.", "Version 100 to 104 (inclusive) WebMIDI is not available (API use is gated by a site permission add-on that is no longer available)."] | No | 30 | No | 43 | 43 | No | 30 | No | 4.0 |
| `requestMediaKeySystemAccess` | 42["The spec requires that the passed `supportedConfigurations` option contain at least one of `audioCapabilities` or `videoCapabilities`, and that said parameters include a codec string.", "The function does not exist in insecure contexts. This was not enforced until Chrome 58."] | 13 | 38["Starting in Firefox 55, if neither `audioCapabilities` nor `videoCapabilities` is specified in `supportedConfigurations`, a warning is output to the web console.", "In addition, starting in Firefox 55, if in `supportedConfigurations`, either `audioCapabilities`'s or `videoCapabilities`'s `contentType` value doesn't specify a `\"codecs\"` substring to define allowed codecs within the media wrapper, a warning is output to the web console. See note below table for example and correction.", "In the future, if neither `audioCapabilities` nor `videoCapabilities` is specified in the `supportedConfigurations`, a `NotSupported` exception will be thrown."] | No | 29["The spec requires that the passed `supportedConfigurations` option contain at least one of `audioCapabilities` or `videoCapabilities`, and that said parameters include a codec string.", "The function does not exist in insecure contexts. This was not enforced until Opera 45."] | 12.1 | 43["The spec requires that the passed `supportedConfigurations` option contain at least one of `audioCapabilities` or `videoCapabilities`, and that said parameters include a codec string.", "The function does not exist in insecure contexts. This was not enforced until version 58."] | 42["The spec requires that the passed `supportedConfigurations` option contain at least one of `audioCapabilities` or `videoCapabilities`, and that said parameters include a codec string.", "The function does not exist in insecure contexts. This was not enforced until Chrome 58."] | 38["Starting in Firefox 55, if neither `audioCapabilities` nor `videoCapabilities` is specified in `supportedConfigurations`, a warning is output to the web console.", "In addition, starting in Firefox 55, if in `supportedConfigurations`, either `audioCapabilities`'s or `videoCapabilities`'s `contentType` value doesn't specify a `\"codecs\"` substring to define allowed codecs within the media wrapper, a warning is output to the web console. See note below table for example and correction.", "In the future, if neither `audioCapabilities` nor `videoCapabilities` is specified in the `supportedConfigurations`, a `NotSupported` exception will be thrown."] | 29["The spec requires that the passed `supportedConfigurations` option contain at least one of `audioCapabilities` or `videoCapabilities`, and that said parameters include a codec string.", "The function does not exist in insecure contexts. This was not enforced until Opera 45."] | 12.2 | 4.0["The spec requires that the passed `supportedConfigurations` option contain at least one of `audioCapabilities` or `videoCapabilities`, and that said parameters include a codec string.", "The function does not exist in insecure contexts. This was not enforced until Samsung Internet 7.0."] |
| `scheduling` | 87 | 87 | No | No | 74 | No | 87 | 87 | No | 62 | No | 14.0 |
| `sendBeacon` | 39Starting in Chrome 59, this method cannot send a `Blob` whose type is not CORS safelisted. This is a temporary change until a mitigation can be found for the security issues that this creates. For more information see [Chrome bug 720283](https://crbug.com/720283). | 14 | 31 | No | 26Starting in Opera 46, this method cannot send a `Blob` whose type is not CORS safelisted. This is a temporary change until a mitigation can be found for the security issues that this creates. For more information see [Chrome bug 720283](https://crbug.com/720283). | 11.1 | 40Starting in Chrome 59, this method cannot send a `Blob` whose type is not CORS safelisted. This is a temporary change until a mitigation can be found for the security issues that this creates. For more information see [Chrome bug 720283](https://crbug.com/720283). | 42Starting in Chrome 59, this method cannot send a `Blob` whose type is not CORS safelisted. This is a temporary change until a mitigation can be found for the security issues that this creates. For more information see [Chrome bug 720283](https://crbug.com/720283). | 31 | 26Starting in Opera 46, this method cannot send a `Blob` whose type is not CORS safelisted. This is a temporary change until a mitigation can be found for the security issues that this creates. For more information see [Chrome bug 720283](https://crbug.com/720283). | 11.3 | 4.0Starting in Samsung Internet 7.0, this method cannot send a `Blob` whose type is not CORS safelisted. This is a temporary change until a mitigation can be found for the security issues that this creates. For more information see [Chrome bug 720283](https://crbug.com/720283). |
| `serial` | 89 | 89 | No | No | 75 | No | No | No | No | No | No | No |
| `serviceWorker` | 40 | 17 | 44In Firefox private windows, the `serviceWorker` object is `undefined`. See [bug 1320796](https://bugzil.la/1320796). | No | 27 | 11.1 | 40 | 40 | 44In Firefox private windows, the `serviceWorker` object is `undefined`. See [bug 1320796](https://bugzil.la/1320796). | 27 | 11.3 | 4.0 |
| `setAppBadge` | 81Windows and macOS only. | 81Windows and macOS only. | No | No | No | No | 81 | 81 | No | 58 | 16.4 | 13.0 |
| `share` | 89Only supported on Chrome OS and Windows, see [bug 770595](https://crbug.com/770595) and [bug 1144920](https://crbug.com/1144920). | 9389–93Only supported on Windows. | 71 | No | 75Only supported on Opera OS and Windows, see [bug 770595](https://crbug.com/770595) and [bug 1144920](https://crbug.com/1144920). | 12.1 | No | 61 | 79 | 48 | 12.2 | 8.0 |
| `storage` | 55 | 79 | 57 | No | 42 | 15.2 | 55 | 55 | 57 | 42 | 15.2 | 6.0 |
| `taintEnabled` | No | No | 1 | 6 | ≤12.1–15 | No | No | No | 4 | ≤12.1–14 | No | No |
| `unregisterProtocolHandler` | 38 | 79 | No | No | 25≤12.1–15 | No | No | No | No | No | No | No |
| `usb` | 61 | 79 | No | No | 48 | No | NoWebView exposes `navigator.usb`, but does not support WebUSB. See [Chromium bug 933055](https://crbug.com/933055). | 61 | No | 45 | No | 8.0 |
| `userActivation` | 72 | 79 | No | No | 60 | 16.4 | 72 | 72 | No | 51 | 16.4 | 11.0 |
| `userAgent` | 1 | 12 | 1 | 4 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `userAgentData` | 90 | 90 | No | No | 76 | No | NoSee [bug 921655](https://crbug.com/921655). | 90 | No | 64 | No | 15.0 |
| `vendor` | 1 | 12 | 1 | 11 | 15 | 1 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `vendorSub` | 1 | 12 | 1 | No | 15 | 3 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `vibrate` | 32 | 79 | 16["Until Firefox 26 included, when the vibration pattern was too long or any of its elements too large, Firefox threw an exception instead of returning `false` ([bug 884935](https://bugzil.la/884935)).", "From Firefox 32 onwards, when the vibration pattern is too long or any of its elements too large, it returns `true` but truncates the pattern ([bug 1014581](https://bugzil.la/1014581)).", "Beginning in Firefox 72, this is not supported in cross-origin iframes."]11–16 | No | 19 | No | 4.4.3["Beginning in version 55, this is not supported in cross-origin iframes.", "Beginning in version 60, this method requires a user gesture. Otherwise it returns `false`."] | 32["Beginning in Chrome 55, this is not supported in cross-origin iframes.", "Beginning in Chrome 60, this method requires a user gesture. Otherwise it returns `false`."] | 79Vibration is disabled. If the window is visible, then `navigator.vibrate()` returns `true`, but no vibration takes place (regardless of hardware support). Originally, the intent was to disable it for cross-origin frames only ([bug 1591113](https://bugzil.la/1591113)), but the feature was not re-enabled due to abuse concerns ([bug 1653318](https://bugzil.la/1653318)).16–79["Until Firefox 26 included, when the vibration pattern was too long or any of its elements too large, Firefox threw an exception instead of returning `false` ([bug 884935](https://bugzil.la/884935)).", "From Firefox 32 onwards, when the vibration pattern is too long or any of its elements too large, it returns `true` but truncates the pattern ([bug 1014581](https://bugzil.la/1014581))."]14–16 | 19["Beginning in Opera 42, this is not supported in cross-origin iframes.", "Beginning in Opera 47, this method requires a user gesture. Otherwise it returns `false`."] | No | 2.0["Beginning in Samsung Internet 6.0, this is not supported in cross-origin iframes.", "Beginning in Samsung Internet 8.0, this method requires a user gesture. Otherwise it returns `false`."] |
| `virtualKeyboard` | 94 | 94 | No | No | 80 | No | 94 | 94 | No | 66 | No | 17.0 |
| `wakeLock` | 84 | 84 | No | No | 70 | 16.4 | 84 | 84 | No | 60 | 16.4 | 14.0 |
| `webdriver` | 63 | 12 | 60 | 11 | 50 | 10.1 | 63 | 63 | 60 | 46 | 10.3 | 8.0 |
| `windowControlsOverlay` | 105 | 105 | No | No | 91 | No | No | No | No | No | No | No |
| `xr` | 79 | 79 | No | No | 66 | No | No | 79 | No | 57 | No | 11.2 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Navigator>

NavigatorUAData
===============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `NavigatorUAData` interface of the [`User-Agent Client Hints API`](user-agent_client_hints_api) returns information about the browser and operating system of a user.

 An instance of this object is returned by calling [`Navigator.userAgentData`](navigator/useragentdata). Therefore, this interface has no constructor.

  **Note:** The terms *high entropy* and *low entropy* refer to the amount of information these values reveal about the browser. The values returned as properties are deemed low entropy, and unlikely to identify a user. The values returned by [`NavigatorUAData.getHighEntropyValues()`](navigatoruadata/gethighentropyvalues) could potentially reveal more information. These values are therefore retrieved via a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), allowing time for the browser to request user permission, or make other checks.

 

Instance properties
-------------------


 
[`NavigatorUAData.brands`](navigatoruadata/brands) Read only   Experimental 
  Returns an array of brand information containing the browser name and version.

  
[`NavigatorUAData.mobile`](navigatoruadata/mobile) Read only   Experimental 
  Returns `true` if the user-agent is running on a mobile device.

  
[`NavigatorUAData.platform`](navigatoruadata/platform) Read only   Experimental 
  Returns the platform brand the user-agent is running on.

  
Instance methods
----------------


 
[`NavigatorUAData.getHighEntropyValues()`](navigatoruadata/gethighentropyvalues)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with a dictionary object containing the *high entropy* values the user-agent returns.

  
[`NavigatorUAData.toJSON()`](navigatoruadata/tojson)  Experimental 
  A *serializer* that returns a JSON representation of the *low entropy* properties of the `NavigatorUAData` object.

  
Examples
--------


### Getting the brands



The following example prints the value of [`NavigatorUAData.brands`](navigatoruadata/brands) to the console.

 
```
console.log(navigator.userAgentData.brands);

```


### Returning high entropy values



In the following value a number of hints are requested using the [`NavigatorUAData.getHighEntropyValues()`](navigatoruadata/gethighentropyvalues) method. When the promise resolves, this information is printed to the console.

 
```
navigator.userAgentData
  .getHighEntropyValues([
    "architecture",
    "model",
    "platform",
    "platformVersion",
    "fullVersionList",
  ])
  .then((ua) => {
    console.log(ua);
  });

```


Specifications
--------------




| Specification |
| --- |
| [User-Agent Client Hints # navigatoruadata](https://wicg.github.io/ua-client-hints/#navigatoruadata) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `NavigatorUAData` | 90 | 90 | No | No | 76 | No | NoSee [bug 921655](https://crbug.com/921655). | 90 | No | 64 | No | No |
| `brands` | 90 | 90 | No | No | 76 | No | No | 90 | No | 64 | No | No |
| `getHighEntropyValues` | 90 | 90 | No | No | 76 | No | No | 90 | No | 64 | No | No |
| `mobile` | 90 | 90 | No | No | 76 | No | No | 90 | No | 64 | No | No |
| `platform` | 93 | 93 | No | No | 79 | No | No | 93 | No | 66 | No | No |
| `toJSON` | 93 | 93 | No | No | 79 | No | No | 93 | No | 66 | No | No |


See also
--------


* [Improving user privacy and developer experience with User-Agent Client Hints](https://web.dev/user-agent-client-hints/)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData>

NavigationPreloadManager
========================



The `NavigationPreloadManager` interface of the [Service Worker API](service_worker_api) provides methods for managing the preloading of resources in parallel with service worker bootup.

  If supported, an object of this type is returned by [`ServiceWorkerRegistration.navigationPreload`](serviceworkerregistration/navigationpreload). The result of a preload fetch request is waited on using the promise returned by [`FetchEvent.preloadResponse`](fetchevent/preloadresponse). 



Instance methods
----------------


 [`NavigationPreloadManager.enable()`](navigationpreloadmanager/enable)  Enables navigation preloading, returning a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined).

  [`NavigationPreloadManager.disable()`](navigationpreloadmanager/disable)  Disables navigation preloading, returning a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined).

  [`NavigationPreloadManager.setHeaderValue()`](navigationpreloadmanager/setheadervalue)  Sets the value of the [`Service-Worker-Navigation-Preload`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Service-Worker-Navigation-Preload) HTTP header sent in preloading requests and returns an empty [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).

  [`NavigationPreloadManager.getState()`](navigationpreloadmanager/getstate)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to an object with properties that indicate whether preloading is enabled, and what value will be sent in the [`Service-Worker-Navigation-Preload`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Service-Worker-Navigation-Preload) HTTP header in preloading requests.

  
Description
-----------



 Service workers handle [`fetch()`](fetch) events on behalf of a site, for pages within a given scope. When a user navigates to a page that uses a service worker, the browser boots up the worker (if it isn't already running), then sends it a fetch event and waits for the result. On receiving an event, the worker returns the resource from a cache if it is present, or otherwise fetches the resource from the remote server (storing a copy for returning in future requests). 

  A service worker cannot process events from the browser until it has booted. This is unavoidable, but usually doesn't have much impact. Service workers are often already started (they remain active for some time after processing other requests). Even if a service worker does have to boot, much of the time it may be returning values from a cache, which is very fast. However, in those cases where a worker has to boot before it can start fetching a remote resource, then the delay can be significant. 

  The [`NavigationPreloadManager`](navigationpreloadmanager) provides a mechanism to allow fetching of the resources to run in parallel with service worker boot, so that by the time the worker is able to handle the fetch request from the browser, the resource may already have been fully or partially downloaded. This makes the case where the worker has to start up "no worse" than when the worker is already started, and in some cases better. 

  The preload manager sends the [`Service-Worker-Navigation-Preload`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Service-Worker-Navigation-Preload) HTTP header with preload requests, allowing responses to be customized for preload requests. This might be used, for example, to reduce the data sent to just part of the original page, or to customize the response based on the user's log-in state. 



Examples
--------


The examples here are from [Speed up Service Worker with Navigation Preloads](https://developer.chrome.com/blog/navigation-preload/) (developer.chrome.com).


### Feature detection and enabling navigation preloading



Below we enable navigation preloading in the service worker's `activate` event handler, after first using [`ServiceWorkerRegistration.navigationPreload`](serviceworkerregistration/navigationpreload) to determine if the feature is supported (this returns either the `NavigationPreloadManager` for the service worker or `undefined` if the feature is not supported).

 
```
addEventListener("activate", (event) => {
  event.waitUntil(
    (async () => {
      if (self.registration.navigationPreload) {
        // Enable navigation preloads!
        await self.registration.navigationPreload.enable();
      }
    })()
  );
});

```


### Using a preloaded response



The following code shows a service worker fetch event handler that uses a preloaded response ([`FetchEvent.preloadResponse`](fetchevent/preloadresponse)).

  The `fetch` event handler calls [`FetchEvent.respondWith()`](fetchevent/respondwith) to pass a promise back to the controlled page. This promise will resolve with the requested resource, which may be from the cache, a preloaded fetch request, or a new network request. 

  If there is a matching URL request in the [`Cache`](cache) object, then the code returns a resolved promise for fetching the response from the cache. If no match is found in the cache, the code returns the resolved preloaded response ([`FetchEvent.preloadResponse`](fetchevent/preloadresponse)). If there is no matching cache entry or preloaded response, the code starts a new fetch operation from the network and returns the (unresolved) promise for that fetch operation. 

 
```
addEventListener("fetch", (event) => {
  event.respondWith(
    (async () => {
      // Respond from the cache if we can
      const cachedResponse = await caches.match(event.request);
      if (cachedResponse) return cachedResponse;

      // Else, use the preloaded response, if it's there
      const response = await event.preloadResponse;
      if (response) return response;

      // Else try the network.
      return fetch(event.request);
    })()
  );
});

```


### Custom responses



 The browser sends the HTTP header [`Service-Worker-Navigation-Preload`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Service-Worker-Navigation-Preload) with preload requests, with a default directive value of `true`. This allows servers to differentiate between normal and preload fetch requests, and to send different responses in each case if required. 

  **Note:** If the response from preload and normal fetch operations can be different, then the server must set `Vary: Service-Worker-Navigation-Preload` to ensure that the different responses are cached.

   The header value can be changed to any other string value using [`NavigationPreloadManager.setHeaderValue()`](navigationpreloadmanager/setheadervalue) in order to provide additional context for the prefetch operation. For example, you might set the value to the ID of your most recently cached resource, so that the server won't return any resources unless they are actually needed. Similarly, you could configure the returned information based on authentication status instead of using cookies. 

 The code below shows how to set the value of the header directive to some variable `newValue`.

 
```
navigator.serviceWorker.ready
  .then((registration) =>
    registration.navigationPreload.setHeaderValue(newValue)
  )
  .then(() => {
    console.log("Done!");
  });

```
 [Speed up Service Worker with Navigation Preloads > Custom responses for preloads](https://developer.chrome.com/blog/navigation-preload/) provides a more complete example of a site where the response for an article web page is constructed from a cached header and footer, so that only the article content is returned for a prefetch.



### Getting the state



 You can use [`NavigationPreloadManager.getState()`](navigationpreloadmanager/getstate) to check whether navigation preloading is enabled and to determine what directive value is sent with the [`Service-Worker-Navigation-Preload`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Service-Worker-Navigation-Preload) HTTP header for preload requests. 

 The code below shows how to get the promise that resolves to a `state` object and log the result.

 
```
navigator.serviceWorker.ready
  .then((registration) => registration.navigationPreload.getState())
  .then((state) => {
    console.log(state.enabled); // boolean
    console.log(state.headerValue); // string
  });

```


Specifications
--------------




| Specification |
| --- |
| [Service Workers # navigation-preload-manager](https://w3c.github.io/ServiceWorker/#navigation-preload-manager) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `NavigationPreloadManager` | 59 | 18 | 99 | No | 46 | 15.4 | 59 | 59 | 99 | 43 | 15.4 | 7.0 |
| `disable` | 59 | 18 | 99 | No | 46 | 15.4 | 59 | 59 | 99 | 43 | 15.4 | 7.0 |
| `enable` | 59 | 18 | 99 | No | 46 | 15.4 | 59 | 59 | 99 | 43 | 15.4 | 7.0 |
| `getState` | 59 | 18 | 99 | No | 46 | 15.4 | 59 | 59 | 99 | 43 | 15.4 | 7.0 |
| `setHeaderValue` | 59 | 18 | 99 | No | 46 | 15.4 | 59 | 59 | 99 | 43 | 15.4 | 7.0 |


See also
--------


* [Speed up Service Worker with Navigation Preloads](https://developer.chrome.com/blog/navigation-preload/) (developer.chrome.com)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/NavigationPreloadManager>

NDEFMessage
===========



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `NDEFMessage` interface of the [Web NFC API](web_nfc_api) represents the content of an NDEF message that has been read from or could be written to an NFC tag. An instance is acquired by calling the `NDEFMessage()` constructor or from the [`NDEFReadingEvent.message`](ndefreadingevent/message) property, which is passed to the [`reading`](ndefreader/reading_event) event.



Constructor
-----------


 
[`NDEFMessage()`](ndefmessage/ndefmessage)  Experimental 
  Creates a new `NDEFMessage` object, initialized with the given NDEF records.

  
Attributes
----------


 
[`NDEFMessage.records`](ndefmessage/records) Read only   Experimental 
  Returns the list of NDEF records contained in the message.

  
Specifications
--------------




| Specification |
| --- |
| [Web NFC API # dom-ndefmessage](https://w3c.github.io/web-nfc/#dom-ndefmessage) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `NDEFMessage` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `NDEFMessage` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `records` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `secure_context_required` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/NDEFMessage>

NDEFReader
==========



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `NDEFReader` interface of the [Web NFC API](web_nfc_api) is used to read from and write data to compatible NFC devices, e.g. NFC tags supporting NDEF, when these devices are within the reader's magnetic induction field.


 EventTarget NDEFReader

Constructor
-----------


 
[`NDEFReader()`](ndefreader/ndefreader)  Experimental 
  Returns a new `NDEFReader` object.

  
Instance methods
----------------



*The `NDEFReader` interface inherits the methods of [`EventTarget`](eventtarget), its parent interface.*

  
[`NDEFReader.scan()`](ndefreader/scan)  Experimental 
  Activates a reading device and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that either resolves when an NFC tag is read or rejects if a hardware or permission error is encountered. This method triggers a permission prompt if the "nfc" permission has not been previously granted.

  
[`NDEFReader.write()`](ndefreader/write)  Experimental 
  Attempts to write an NDEF message to a tag and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that either resolves when a message has been written to the tag or rejects if a hardware or permission error is encountered. This method triggers a permission prompt if the "nfc" permission has not been previously granted.

  

Events
------



*Inherits properties from its parent, [`EventTarget`](eventtarget).*

  
[`reading`](ndefreader/reading_event)  Experimental 
  Fires when a new reading is available from compatible NFC devices.

  
[`readingerror`](ndefreader/readingerror_event)  Experimental 
  Fires when a tag is in proximity of a reading device, but cannot be read.

  

Examples
--------


### Handling initial reads while writing



The example below shows how to coordinate between a common reading handler and one used specifically for a single write. In order to write, a tag needs to be found and read. This gives you the ability to check whether it is actually a tag that you want to write to. That's why it's recommended that you call `write()` from a reading event.

 
```
const ndef = new NDEFReader();
let ignoreRead = false;

ndef.onreading = (event) => {
  if (ignoreRead) {
    return; // write pending, ignore read.
  }

  console.log("We read a tag, but not during pending write!");
};

function write(data) {
  ignoreRead = true;
  return new Promise((resolve, reject) => {
    ndef.addEventListener(
      "reading",
      (event) => {
        // Check if we want to write to this tag, or reject.
        ndef
          .write(data)
          .then(resolve, reject)
          .finally(() => (ignoreRead = false));
      },
      { once: true }
    );
  });
}

await ndef.scan();
try {
  await write("Hello World");
  console.log("We wrote to a tag!");
} catch (err) {
  console.error("Something went wrong", err);
}

```


Specifications
--------------




| Specification |
| --- |
| [Web NFC API # the-ndefreader-object](https://w3c.github.io/web-nfc/#the-ndefreader-object) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `NDEFReader` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `NDEFReader` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `makeReadOnly` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `reading_event` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `readingerror_event` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `scan` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `secure_context_required` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `write` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/NDEFReader>

NDEFReadingEvent
================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `NDEFReadingEvent` interface of the [Web NFC API](web_nfc_api) represents events dispatched on new NFC readings obtained by [`NDEFReader`](ndefreader).


 Event NDEFReadingEvent

Constructor
-----------


 
[`NDEFReadingEvent.NDEFReadingEvent()`](ndefreadingevent/ndefreadingevent)  Experimental 
  Creates a new `NDEFReadingEvent`.

  
Instance properties
-------------------



*Inherits properties from its parent, [`Event`](event)*.

  
[`NDEFReadingEvent.message`](ndefreadingevent/message) Read only   Experimental 
  Returns an [`NDEFMessage`](ndefmessage) object containing the received message.

  
[`NDEFReadingEvent.serialNumber`](ndefreadingevent/serialnumber) Read only   Experimental 
  Returns the serial number of the device, which is used for anti-collision and identification, or an empty string if no serial number is available.

  

Instance methods
----------------


*Inherits methods from its parent, [`Event`](event)*.


Specifications
--------------




| Specification |
| --- |
| [Web NFC API # dom-ndefreadingevent](https://w3c.github.io/web-nfc/#dom-ndefreadingevent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `NDEFReadingEvent` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `NDEFReadingEvent` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `message` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `secure_context_required` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `serialNumber` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/NDEFReadingEvent>

NDEFRecord
==========



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `NDEFRecord` interface of the [Web NFC API](web_nfc_api) provides data that can be read from, or written to, compatible NFC devices, e.g. NFC tags supporting NDEF.



Constructor
-----------


 
[`NDEFRecord()`](ndefrecord/ndefrecord)  Experimental 
  Returns a new `NDEFRecord`.

  
Instance properties
-------------------


 
[`NDEFRecord.recordType`](ndefrecord/recordtype)  Experimental  Read only 
  Returns the record type of the record. Records must have either a standardized well-known type name such as `"empty"`, `"text"`, `"url"`, `"smart-poster"`, `"absolute-url"`, `"mime"`, or `"unknown"` or else an external type name, which consists of a domain name and custom type name separated by a colon (":").

  
[`NDEFRecord.mediaType`](ndefrecord/mediatype)  Experimental  Read only 
  Returns the [MIME type](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type) of the record. This value will be `null` if `recordType` is not equal to `"mime"`.

  
[`NDEFRecord.id`](ndefrecord/id)  Experimental  Read only 
  Returns the record identifier, which is an absolute or relative URL used to identify the record.

  **Note:** The uniqueness of the identifier is enforced only by the generator of the record.

   
[`NDEFRecord.data`](ndefrecord/data)  Experimental  Read only 
  Returns a [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) containing the raw bytes of the record's payload.

  
[`NDEFRecord.encoding`](ndefrecord/encoding)  Experimental  Read only 
  Returns the encoding of a textual payload, or `null` otherwise.

  
[`NDEFRecord.lang`](ndefrecord/lang)  Experimental  Read only 
  Returns the language of a textual payload, or `null` if one was not supplied.

  
Instance methods
----------------


 
[`NDEFRecord.toRecords()`](ndefrecord/torecords)  Experimental 
  Converts [`NDEFRecord.data`](ndefrecord/data) to a sequence of records. This allows parsing the payloads of record types which may contain nested records, such as smart poster and external type records.

  
Specifications
--------------




| Specification |
| --- |
| [Web NFC API # dom-ndefrecord](https://w3c.github.io/web-nfc/#dom-ndefrecord) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `NDEFRecord` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `NDEFRecord` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `data` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `encoding` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `id` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `lang` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `mediaType` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `recordType` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `secure_context_required` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |
| `toRecords` | No | No | No | No | No | No | 89 | 89 | No | 63 | No | 15.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/NDEFRecord>

NetworkInformation
==================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

  The `NetworkInformation` interface of the [Network Information API](network_information_api) provides information about the connection a device is using to communicate with the network and provides a means for scripts to be notified if the connection type changes. The `NetworkInformation` interface cannot be instantiated. It is instead accessed through the `connection` property of the [`Navigator`](navigator) interface. 


 **Note:** This feature is available in [Web Workers](web_workers_api)

   EventTarget NetworkInformation

Instance properties
-------------------



*This interface also inherits properties of its parent, [`EventTarget`](eventtarget).*

  
[`NetworkInformation.downlink`](networkinformation/downlink) Read only   Experimental 
  Returns the effective bandwidth estimate in megabits per second, rounded to the nearest multiple of 25 kilobits per seconds.

  
[`NetworkInformation.downlinkMax`](networkinformation/downlinkmax) Read only   Experimental 
  Returns the maximum downlink speed, in megabits per second (Mbps), for the underlying connection technology.

  
[`NetworkInformation.effectiveType`](networkinformation/effectivetype) Read only   Experimental 
  Returns the effective type of the connection meaning one of 'slow-2g', '2g', '3g', or '4g'. This value is determined using a combination of recently observed round-trip time and downlink values.

  
[`NetworkInformation.rtt`](networkinformation/rtt) Read only   Experimental 
  Returns the estimated effective round-trip time of the current connection, rounded to the nearest multiple of 25 milliseconds.

  
[`NetworkInformation.saveData`](networkinformation/savedata) Read only   Experimental 
  Returns `true` if the user has set a reduced data usage option on the user agent.

  
[`NetworkInformation.type`](networkinformation/type) Read only   Experimental 
  Returns the type of connection a device is using to communicate with the network. It will be one of the following values:

 * `bluetooth`
* `cellular`
* `ethernet`
* `none`
* `wifi`
* `wimax`
* `other`
* `unknown`

  

Instance methods
----------------


*This interface also inherits methods of its parent, [`EventTarget`](eventtarget).*


Events
------


 
[`change`](networkinformation/change_event)  Experimental 
  The event that's fired when connection information changes.

  
Specifications
--------------




| Specification |
| --- |
| [Network Information API # networkinformation-interface](https://wicg.github.io/netinfo/#networkinformation-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `NetworkInformation` | 61 | 79 | 31–32 | No | 48 | NoSee [bug 185697](https://webkit.org/b/185697). | 50 | 38 | 31–99 | 25 | NoSee [bug 185697](https://webkit.org/b/185697). | 3.0 |
| `change_event` | 61 | 79 | No | No | 48 | No | 50 | 38 | NoOn Firefox, the event handler property corresponding to the `change` event is `ontypechange`. | 45 | No | 3.0 |
| `downlink` | 61The value is never greater than 10 Mbps, as a non-standard anti-fingerprinting measure. | 79The value is never greater than 10 Mbps, as a non-standard anti-fingerprinting measure. | No | No | 48The value is never greater than 10 Mbps, as a non-standard anti-fingerprinting measure. | No | 50The value is never greater than 10 Mbps, as a non-standard anti-fingerprinting measure. | 38The value is never greater than 10 Mbps, as a non-standard anti-fingerprinting measure. | No | 25The value is never greater than 10 Mbps, as a non-standard anti-fingerprinting measure. | No | 3.0The value is never greater than 10 Mbps, as a non-standard anti-fingerprinting measure. |
| `downlinkMax` | 61Only supported in Chrome OS | No | No | No | No | No | 50 | 38 | No | 45 | No | 3.0 |
| `effectiveType` | 61 | 79 | No | No | 48 | No | 50 | 38 | No | 45 | No | 3.0 |
| `rtt` | 61The value is never greater than 3000 ms, as a non-standard anti-fingerprinting measure. | 79The value is never greater than 3000 ms, as a non-standard anti-fingerprinting measure. | No | No | 48The value is never greater than 3000 ms, as a non-standard anti-fingerprinting measure. | No | 50The value is never greater than 3000 ms, as a non-standard anti-fingerprinting measure. | 38The value is never greater than 3000 ms, as a non-standard anti-fingerprinting measure. | No | 25The value is never greater than 3000 ms, as a non-standard anti-fingerprinting measure. | No | 3.0The value is never greater than 3000 ms, as a non-standard anti-fingerprinting measure. |
| `saveData` | 65 | 79 | No | No | 52 | No | 65 | 65 | No | 47 | No | 9.0 |
| `type` | 61Only supported in Chrome OS | No | 31–32 | No | No | No | 50 | 38 | 31–99 | 45 | No | 3.0 |
| `typechange_event` | No | No | 31–32 | No | No | No | 50 | 38Removal proposed in [bug 699892](https://crbug.com/699892). | 31–99 | 25Removal proposed in [bug 699892](https://crbug.com/699892). | No | 3.0Removal proposed in [bug 699892](https://crbug.com/699892). |
| `worker_support` | 61 | 79 | 31–32 | No | 48 | No | 50 | 38 | 53–99 | 45 | No | 3.0 |


See also
--------


* [Online and offline events](navigator/online)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation>

Node
====



 The [DOM](https://developer.mozilla.org/en-US/docs/Glossary/DOM) `Node` interface is an abstract base class upon which many other DOM API objects are based, thus letting those object types to be used similarly and often interchangeably. As an abstract class, there is no such thing as a plain `Node` object. All objects that implement `Node` functionality are based on one of its subclasses. Most notable are [`Document`](document), [`Element`](element), and [`DocumentFragment`](documentfragment). 

  In addition, every kind of DOM node is represented by an interface based on `Node`. These include [`Attr`](attr), [`CharacterData`](characterdata) (which [`Text`](text), [`Comment`](comment), [`CDATASection`](cdatasection) and [`ProcessingInstruction`](processinginstruction) are all based on), and [`DocumentType`](documenttype). 

  In some cases, a particular feature of the base `Node` interface may not apply to one of its child interfaces; in that case, the inheriting node may return `null` or throw an exception, depending on circumstances. For example, attempting to add children to a node type that cannot have children will throw an exception. 


 EventTarget Node

Instance properties
-------------------



*In addition to the properties below, `Node` inherits properties from its parent, [`EventTarget`](eventtarget)*.

  
[`Node.baseURI`](node/baseuri) Read only 
   Returns a string representing the base URL of the document containing the `Node`. 

  
[`Node.childNodes`](node/childnodes) Read only 
   Returns a live [`NodeList`](nodelist) containing all the children of this node (including elements, text and comments). [`NodeList`](nodelist) being live means that if the children of the `Node` change, the [`NodeList`](nodelist) object is automatically updated. 

  
[`Node.firstChild`](node/firstchild) Read only 
   Returns a `Node` representing the first direct child node of the node, or `null` if the node has no child. 

  
[`Node.isConnected`](node/isconnected) Read only 
   A boolean indicating whether or not the Node is connected (directly or indirectly) to the context object, e.g. the [`Document`](document) object in the case of the normal DOM, or the [`ShadowRoot`](shadowroot) in the case of a shadow DOM. 

  
[`Node.lastChild`](node/lastchild) Read only 
   Returns a `Node` representing the last direct child node of the node, or `null` if the node has no child. 

  
[`Node.nextSibling`](node/nextsibling) Read only 
   Returns a `Node` representing the next node in the tree, or `null` if there isn't such node. 

  
[`Node.nodeName`](node/nodename) Read only 
   Returns a string containing the name of the `Node`. The structure of the name will differ with the node type. E.g. An [`HTMLElement`](htmlelement) will contain the name of the corresponding tag, like `'audio'` for an [`HTMLAudioElement`](htmlaudioelement), a [`Text`](text) node will have the `'#text'` string, or a [`Document`](document) node will have the `'#document'` string. 

  
[`Node.nodeType`](node/nodetype) Read only 
   Returns an `unsigned short` representing the type of the node. Possible values are: 

 

| Name | Value |
| --- | --- |
| `ELEMENT_NODE` | `1` |
| `ATTRIBUTE_NODE` | `2` |
| `TEXT_NODE` | `3` |
| `CDATA_SECTION_NODE` | `4` |
| `PROCESSING_INSTRUCTION_NODE` | `7` |
| `COMMENT_NODE` | `8` |
| `DOCUMENT_NODE` | `9` |
| `DOCUMENT_TYPE_NODE` | `10` |
| `DOCUMENT_FRAGMENT_NODE` | `11` |

  [`Node.nodeValue`](node/nodevalue)  Returns / Sets the value of the current node.

  
[`Node.ownerDocument`](node/ownerdocument) Read only 
   Returns the [`Document`](document) that this node belongs to. If the node is itself a document, returns `null`. 

  
[`Node.parentNode`](node/parentnode) Read only 
   Returns a `Node` that is the parent of this node. If there is no such node, like if this node is the top of the tree or if doesn't participate in a tree, this property returns `null`. 

  
[`Node.parentElement`](node/parentelement) Read only 
   Returns an [`Element`](element) that is the parent of this node. If the node has no parent, or if that parent is not an [`Element`](element), this property returns `null`. 

  
[`Node.previousSibling`](node/previoussibling) Read only 
   Returns a `Node` representing the previous node in the tree, or `null` if there isn't such node. 

  [`Node.textContent`](node/textcontent)  Returns / Sets the textual content of an element and all its descendants.

  

Instance methods
----------------



*In addition to the methods below, `Node` inherits methods from its parent, [`EventTarget`](eventtarget).*

  [`Node.appendChild()`](node/appendchild)   Adds the specified `childNode` argument as the last child to the current node. If the argument referenced an existing node on the DOM tree, the node will be detached from its current position and attached at the new position. 

  [`Node.cloneNode()`](node/clonenode)   Clone a `Node`, and optionally, all of its contents. By default, it clones the content of the node. 

  [`Node.compareDocumentPosition()`](node/comparedocumentposition)  Compares the position of the current node against another node in any other document.

  [`Node.contains()`](node/contains)   Returns `true` or `false` value indicating whether or not a node is a descendant of the calling node. 

  [`Node.getRootNode()`](node/getrootnode)  Returns the context object's root which optionally includes the shadow root if it is available.

  [`Node.hasChildNodes()`](node/haschildnodes)  Returns a boolean value indicating whether or not the element has any child nodes.

  [`Node.insertBefore()`](node/insertbefore)   Inserts a `Node` before the reference node as a child of a specified parent node. 

  [`Node.isDefaultNamespace()`](node/isdefaultnamespace)   Accepts a namespace URI as an argument and returns a boolean value with a value of `true` if the namespace is the default namespace on the given node or `false` if not. 

  [`Node.isEqualNode()`](node/isequalnode)   Returns a boolean value which indicates whether or not two nodes are of the same type and all their defining data points match. 

  [`Node.isSameNode()`](node/issamenode)   Returns a boolean value indicating whether or not the two nodes are the same (that is, they reference the same object). 

  [`Node.lookupPrefix()`](node/lookupprefix)   Returns a string containing the prefix for a given namespace URI, if present, and `null` if not. When multiple prefixes are possible, the result is implementation-dependent. 

  [`Node.lookupNamespaceURI()`](node/lookupnamespaceuri)   Accepts a prefix and returns the namespace URI associated with it on the given node if found (and `null` if not). Supplying `null` for the prefix will return the default namespace. 

  [`Node.normalize()`](node/normalize)  Clean up all the text nodes under this element (merge adjacent, remove empty).

  [`Node.removeChild()`](node/removechild)   Removes a child node from the current element, which must be a child of the current node. 

  [`Node.replaceChild()`](node/replacechild)   Replaces one child `Node` of the current one with the second one given in parameter. 

  

Examples
--------


### Remove all children nested within a node



This function remove each first child of an element, until there are none left.

 
```
function removeAllChildren(element) {
  while (element.firstChild) {
    element.removeChild(element.firstChild);
  }
}

```
 Using this function is a single call. Here we empty the body of the document:

 
```
removeAllChildren(document.body);

```
 An alternative could be to set the textContent to the empty string: `document.body.textContent = ""`.



### Recurse through child nodes



 The following function recursively calls a callback function for each node contained by a root node (including the root itself): 

 
```
function eachNode(rootNode, callback) {
  if (!callback) {
    const nodes = [];
    eachNode(rootNode, (node) => {
      nodes.push(node);
    });
    return nodes;
  }

  if (callback(rootNode) === false) {
    return false;
  }

  if (rootNode.hasChildNodes()) {
    for (const node of rootNode.childNodes) {
      if (eachNode(node, callback) === false) {
        return;
      }
    }
  }
}

```
  The function recursively calls a function for each descendant node of `rootNode` (including the root itself). 

  If `callback` is omitted, the function returns an [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) instead, which contains `rootNode` and all nodes contained within. 

  If `callback` is provided, and it returns `false` when called, the current recursion level is aborted, and the function resumes execution at the last parent's level. This can be used to abort loops once a node has been found (such as searching for a text node which contains a certain string). 

 The function has two parameters:

  `rootNode`  The `Node` object whose descendants will be recursed through.

  
`callback` Optional
   An optional callback [function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) that receives a `Node` as its only argument. If omitted, `eachNode` returns an [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of every node contained within `rootNode` (including the root itself). 

    The following demonstrates a real-world use of the `eachNode()` function: searching for text on a web-page. 

 We use a wrapper function named `grep` to do the searching:

 
```
function grep(parentNode, pattern) {
  let matches = [];
  let endScan = false;

  eachNode(parentNode, (node) => {
    if (endScan) {
      return false;
    }

    // Ignore anything which isn't a text node
    if (node.nodeType !== Node.TEXT\_NODE) {
      return;
    }

    if (typeof pattern === "string" && node.textContent.includes(pattern)) {
      matches.push(node);
    } else if (pattern.test(node.textContent)) {
      if (!pattern.global) {
        endScan = true;
        matches = node;
      } else {
        matches.push(node);
      }
    }
  });

  return matches;
}

```


Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-node](https://dom.spec.whatwg.org/#interface-node) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Node` | 1WebKit and old versions of Blink incorrectly do not make `Node` inherit from `EventTarget`. | 12 | 1 | 5 | 7WebKit and old versions of Blink incorrectly do not make `Node` inherit from `EventTarget`. | 1WebKit and old versions of Blink incorrectly do not make `Node` inherit from `EventTarget`. | ≤37 | 18WebKit and old versions of Blink incorrectly do not make `Node` inherit from `EventTarget`. | 4 | 10.1WebKit and old versions of Blink incorrectly do not make `Node` inherit from `EventTarget`. | 1WebKit and old versions of Blink incorrectly do not make `Node` inherit from `EventTarget`. | 1.0WebKit and old versions of Blink incorrectly do not make `Node` inherit from `EventTarget`. |
| `appendChild` | 1 | 12 | 1 | 5 | 7 | 1.1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `baseURI` | 1 | 12 | 1 | No | ≤12.1 | ≤4 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `childNodes` | 1 | 12 | 1 | 5 | 7 | 1.2 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `cloneNode` | 1 | 12 | 1 | 6 | 7 | 1.1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `compareDocumentPosition` | 2 | 12 | 1 | 9Only supports `contains` for elements | ≤12.1 | 4 | ≤37 | 18 | 4 | ≤12.1 | 3.2 | 1.0 |
| `contains` | 16 | 12 | 9 | 9Only supported for [`HTMLElement`](https://developer.mozilla.org/docs/Web/API/HTMLElement), not all `Node` objects. | 7 | 1.1 | 4.4 | 18 | 9 | 10.1 | 1 | 1.0 |
| `firstChild` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `getRootNode` | 54 | 79 | 53 | No | 41 | 10.1 | 54 | 54 | 53 | 41 | 10.3 | 6.0 |
| `hasChildNodes` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `insertBefore` | 1 | 12 | 1 | 6 | 7 | 1.1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `isConnected` | 51 | 79 | 49 | No | 38 | 10 | 51 | 51 | 49 | 41 | 10 | 6.0 |
| `isDefaultNamespace` | 1 | 12 | 1 | 9 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `isEqualNode` | 1 | 12 | 1 | 9 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `isSameNode` | 1 | 12 | 481–10 | 9 | ≤12.1 | 3 | 4.4 | 18 | 484–10 | ≤12.1 | 1 | 1.0 |
| `lastChild` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 45 | ≤12.1 | 1 | 1.0 |
| `lookupNamespaceURI` | 1 | 12 | 1 | 9 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `lookupPrefix` | 1 | 12 | 1 | 9 | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `nextSibling` | 1 | 12 | 1 | 5.5 | 7 | 1.1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `nodeName` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `nodeType` | 1 | 12 | 1 | 6 | 7 | 1.1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `nodeValue` | 1 | 12 | 1 | 6 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `normalize` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `ownerDocument` | 1 | 12 | 91–9The `ownerDocument` of doctype nodes (that is, nodes for which `Node.nodeType` is `Node.DOCUMENT_TYPE_NODE` or 10) is `null`. | 6 | ≤12.1 | 1 | 4.4 | 18 | 94–9The `ownerDocument` of doctype nodes (that is, nodes for which `Node.nodeType` is `Node.DOCUMENT_TYPE_NODE` or 10) is `null`. | ≤12.1 | 1 | 1.0 |
| `parentElement` | 1 | 12 | 9 | 8Only supported on `Element`. | 7Before Opera 15, this feature was only supported on `Element`. | 1.1 | 4.4 | 18 | 9 | 10.1Before Opera Android 14, this feature was only supported on `Element`. | 1 | 1.0 |
| `parentNode` | 1 | 12 | 1 | 5.5 | 7 | 1.1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `previousSibling` | 1 | 12 | 1 | 5.5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `removeChild` | 1 | 12 | 1 | 5 | 7 | 1.1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `replaceChild` | 1 | 12 | 1 | 6 | 7 | 1.1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `selectstart_event` | 1 | 12 | 52 | 5 | 15 | 1.3 | 4.4 | 18 | 52 | 14 | No | 1.0 |
| `textContent` | 1 | 12 | 1 | 9 | 9 | 3 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Node>

NodeIterator
============


 The `NodeIterator` interface represents an iterator over the members of a list of the nodes in a subtree of the DOM. The nodes will be returned in document order. 


Syntax
------



 A `NodeIterator` can be created using the [`Document.createNodeIterator()`](document/createnodeiterator) method, as follows: 

 
```
const nodeIterator = document.createNodeIterator(root, whatToShow, filter);

```


Instance properties
-------------------



*This interface doesn't inherit any property.*

  
[`NodeIterator.root`](nodeiterator/root) Read only 
   Returns a [`Node`](node) representing the root node as specified when the `NodeIterator` was created. 

  
[`NodeIterator.whatToShow`](nodeiterator/whattoshow) Read only 
   Returns an `unsigned long` being a bitmask made of constants describing the types of [`Node`](node) that must to be presented. Non-matching nodes are skipped, but their children may be included, if relevant. 

 The possible values are:

 

| Constant | Numerical value | Description |
| --- | --- | --- |
| `NodeFilter.SHOW_ALL` | `4294967295` (that is the max value of `unsigned long`) | Shows all nodes. |
| `NodeFilter.SHOW_ATTRIBUTE`  Deprecated  | `2` | Shows attribute [`Attr`](attr) nodes. This is meaningful only when creating a [`NodeIterator`](nodeiterator) with an [`Attr`](attr) node as its root; in this case, it means that the attribute node will appear in the first position of the iteration or traversal. Since attributes are never children of other nodes, they do not appear when traversing over the document tree. |
| `NodeFilter.SHOW_CDATA_SECTION`  Deprecated  | `8` | Shows [`CDATASection`](cdatasection) nodes. |
| `NodeFilter.SHOW_COMMENT` | `128` | Shows [`Comment`](comment) nodes. |
| `NodeFilter.SHOW_DOCUMENT` | `256` | Shows [`Document`](document) nodes. |
| `NodeFilter.SHOW_DOCUMENT_FRAGMENT` | `1024` | Shows [`DocumentFragment`](documentfragment) nodes. |
| `NodeFilter.SHOW_DOCUMENT_TYPE` | `512` | Shows [`DocumentType`](documenttype) nodes. |
| `NodeFilter.SHOW_ELEMENT` | `1` | Shows [`Element`](element) nodes. |
| `NodeFilter.SHOW_ENTITY`  Deprecated  | `32` | Legacy, no more used. |
| `NodeFilter.SHOW_ENTITY_REFERENCE`  Deprecated  | `16` | Legacy, no more used. |
| `NodeFilter.SHOW_NOTATION`  Deprecated  | `2048` | Legacy, no more used. |
| `NodeFilter.SHOW_PROCESSING_INSTRUCTION` | `64` | Shows [`ProcessingInstruction`](processinginstruction) nodes. |
| `NodeFilter.SHOW_TEXT` | `4` | Shows [`Text`](text) nodes. |

  
[`NodeIterator.filter`](nodeiterator/filter) Read only 
  Returns a [`NodeFilter`](document/createnodeiterator) used to select the relevant nodes.

   [`NodeIterator.referenceNode`](nodeiterator/referencenode) Read only   Experimental    Returns the [`Node`](node) to which the iterator is anchored.

  
[`NodeIterator.pointerBeforeReferenceNode`](nodeiterator/pointerbeforereferencenode) Read only   Experimental 
   Returns a boolean flag that indicates whether the [`NodeIterator`](nodeiterator) is anchored before, the flag being `true`, or after, the flag being `false`, the anchor node. 

  

Instance methods
----------------



*This interface doesn't inherit any method.*

  
[`NodeIterator.detach()`](nodeiterator/detach)  Deprecated 
   This operation is a no-op. It doesn't do anything. Previously it was telling the engine that the `NodeIterator` was no more used, but this is now useless. 

  [`NodeIterator.previousNode()`](nodeiterator/previousnode)   Returns the previous [`Node`](node) in the document, or `null` if there are none. 

  [`NodeIterator.nextNode()`](nodeiterator/nextnode)   Returns the next [`Node`](node) in the document, or `null` if there are none. 

  

Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-nodeiterator](https://dom.spec.whatwg.org/#interface-nodeiterator) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `NodeIterator` | 1 | 12 | 3.5 | 9 | 9 | 3 | 4.4 | 18 | 4 | 10.1 | 3 | 1.0 |
| `detach` | 1 | 12 | 3.5–22 | 9 | 9 | 3 | 4.4 | 18 | 4–22 | 10.1 | 3 | 1.0 |
| `filter` | 1 | 12 | 3.5 | 9 | 9 | 3 | 4.4 | 18 | 4 | 10.1 | 3 | 1.0 |
| `nextNode` | 1 | 12 | 3.5 | 9 | 9 | 3 | 4.4 | 18 | 4 | 10.1 | 3 | 1.0 |
| `pointerBeforeReferenceNode` | 1 | 17 | 3.5 | No | ≤15 | 3 | 4.4 | 18 | 4 | ≤14 | 3 | 1.0 |
| `previousNode` | 1 | 12 | 3.5 | 9 | 9 | 3 | 4.4 | 18 | 4 | 10.1 | 3 | 1.0 |
| `referenceNode` | 1 | 17 | 3.5 | No | ≤15 | 3 | 4.4 | 18 | 4 | ≤14 | 3 | 1.0 |
| `root` | 1 | 12 | 3.5 | 9 | 9 | 3 | 4.4 | 18 | 4 | 10.1 | 3 | 1.0 |
| `whatToShow` | 1 | 12 | 3.5 | 9 | 9 | 3 | 4.4 | 18 | 4 | 10.1 | 3 | 1.0 |


See also
--------


* The creator method: [`Document.createNodeIterator()`](document/createnodeiterator).
* Related interfaces:
	+ [`NodeFilter`](document/createnodeiterator)
	+ [`TreeWalker`](treewalker)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/NodeIterator>

NodeList
========



`NodeList` objects are collections of [nodes](node), usually returned by properties such as [`Node.childNodes`](node/childnodes) and methods such as [`document.querySelectorAll()`](document/queryselectorall).

  **Note:** Although `NodeList` is not an `Array`, it is possible to iterate over it with `forEach()`. It can also be converted to a real `Array` using [`Array.from()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from).

 

Live vs. Static NodeLists
-------------------------


Although they are both considered `NodeList` objects, there are 2 varieties of NodeList: *live* and *static*.


### Live NodeLists



In some cases, the `NodeList` is *live*, which means that changes in the DOM automatically update the collection.

 For example, [`Node.childNodes`](node/childnodes) is live:

 
```
const parent = document.getElementById("parent");
let childNodes = parent.childNodes;
console.log(childNodes.length); // let's assume "2"
parent.appendChild(document.createElement("div"));
console.log(childNodes.length); // outputs "3"

```


### Static NodeLists



In other cases, the `NodeList` is *static,* where any changes in the DOM do not affect the content of the collection. The ubiquitous [`document.querySelectorAll()`](document/queryselectorall) method returns a *static* `NodeList`.

 It's good to keep this distinction in mind when you choose how to iterate over the items in the `NodeList`, and whether you should cache the list's `length`.



Instance properties
-------------------


 [`NodeList.length`](nodelist/length)  The number of nodes in the `NodeList`.

  
Instance methods
----------------


 [`NodeList.item()`](nodelist/item)  Returns an item in the list by its index, or `null` if the index is out-of-bounds.

 An alternative to accessing `nodeList[i]` (which instead returns `undefined` when `i` is out-of-bounds). This is mostly useful for non-JavaScript DOM implementations.

  [`NodeList.entries()`](nodelist/entries)  Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols), allowing code to go through all key/value pairs contained in the collection. (In this case, the keys are integers starting from `0` and the values are nodes.)

  [`NodeList.forEach()`](nodelist/foreach)  Executes a provided function once per `NodeList` element, passing the element as an argument to the function.

  [`NodeList.keys()`](nodelist/keys)  Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols), allowing code to go through all the keys of the key/value pairs contained in the collection. (In this case, the keys are integers starting from `0`.)

  [`NodeList.values()`](nodelist/values)  Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing code to go through all values (nodes) of the key/value pairs contained in the collection.

  
Example
-------



It's possible to loop over the items in a `NodeList` using a [for](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) loop:

 
```
for (let i = 0; i < myNodeList.length; i++) {
  let item = myNodeList[i];
}

```
 **Don't use [`for...in`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) to enumerate the items in `NodeList`s**, since they will *also* enumerate its `length` and `item` properties and cause errors if your script assumes it only has to deal with [`element`](element) objects. Also, `for...in` is not guaranteed to visit the properties in any particular order.

 [`for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) loops loop over `NodeList` objects correctly:

 
```
const list = document.querySelectorAll("input[type=checkbox]");
for (const checkbox of list) {
  checkbox.checked = true;
}

```
 Browsers also support the iterator method ([`forEach()`](nodelist/foreach)) as well as [`entries()`](nodelist/entries), [`values()`](nodelist/values), and [`keys()`](nodelist/keys).



Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-nodelist](https://dom.spec.whatwg.org/#interface-nodelist) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@iterator` | 51 | 79 | 36 | No | 38 | 10 | 51 | 51 | 36 | 41 | 10 | 5.0 |
| `NodeList` | 1 | 12 | 1 | 5 | 8 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `entries` | 51 | 16 | 50 | No | 38 | 10 | 51 | 51 | 50 | 41 | 10 | 5.0 |
| `forEach` | 51 | 16 | 50 | No | 38 | 10 | 51 | 51 | 50 | 41 | 10 | 5.0 |
| `item` | 1 | 12 | 1 | 5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `keys` | 51 | 16 | 50 | No | 38 | 10 | 51 | 51 | 50 | 41 | 10 | 5.0 |
| `length` | 1 | 12 | 1 | 5 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `values` | 51 | 16 | 50 | No | 38 | 10 | 51 | 51 | 50 | 41 | 10 | 5.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/NodeList>

Notification
============



 **Note:** This feature is available in [Web Workers](web_workers_api)

 
**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `Notification` interface of the [Notifications API](notifications_api) is used to configure and display desktop notifications to the user.

 These notifications' appearance and specific functionality vary across platforms but generally they provide a way to asynchronously provide information to the user.


 EventTarget Notification

Constructor
-----------


 [`Notification()`](notification/notification)  Creates a new instance of the `Notification` object.

  
Static properties
-----------------



These properties are available only on the `Notification` object itself.

  
[`Notification.permission`](notification/permission) Read only 
  A string representing the current permission to display notifications. Possible values are:

 * `denied` — The user refuses to have notifications displayed.
* `granted` — The user accepts having notifications displayed.
* `default` — The user choice is unknown and therefore the browser will act as if the value were denied.

  
[`Notification.maxActions`](notification/maxactions) Read only   Experimental 
  The maximum number of actions supported by the device and the User Agent.

  

Instance properties
-------------------



These properties are available only on instances of the `Notification` object.

  
[`Notification.actions`](notification/actions) Read only   Experimental 
  The actions array of the notification as specified in the constructor's `options` parameter.

  
[`Notification.badge`](notification/badge) Read only   Experimental 
  The URL of the image used to represent the notification when there is not enough space to display the notification itself.

  
[`Notification.body`](notification/body) Read only 
  The body string of the notification as specified in the constructor's `options` parameter.

  
[`Notification.data`](notification/data) Read only 
  Returns a structured clone of the notification's data.

  
[`Notification.dir`](notification/dir) Read only 
  The text direction of the notification as specified in the constructor's `options` parameter.

  
[`Notification.lang`](notification/lang) Read only 
  The language code of the notification as specified in the constructor's `options` parameter.

  
[`Notification.tag`](notification/tag) Read only 
  The ID of the notification (if any) as specified in the constructor's `options` parameter.

  
[`Notification.icon`](notification/icon) Read only 
  The URL of the image used as an icon of the notification as specified in the constructor's `options` parameter.

  
[`Notification.image`](notification/image) Read only   Experimental 
  The URL of an image to be displayed as part of the notification, as specified in the constructor's `options` parameter.

  
[`Notification.renotify`](notification/renotify) Read only   Experimental 
  Specifies whether the user should be notified after a new notification replaces an old one.

  
[`Notification.requireInteraction`](notification/requireinteraction) Read only   Experimental 
  A boolean value indicating that a notification should remain active until the user clicks or dismisses it, rather than closing automatically.

  
[`Notification.silent`](notification/silent) Read only   Experimental 
  Specifies whether the notification should be silent — i.e., no sounds or vibrations should be issued, regardless of the device settings.

  
[`Notification.timestamp`](notification/timestamp) Read only   Experimental 
  Specifies the time at which a notification is created or applicable (past, present, or future).

  
[`Notification.title`](notification/title) Read only 
  The title of the notification as specified in the first parameter of the constructor.

  
[`Notification.vibrate`](notification/vibrate) Read only   Experimental 
  Specifies a vibration pattern for devices with vibration hardware to emit.

  

Static methods
--------------



These methods are available only on the `Notification` object itself.

  [`Notification.requestPermission()`](notification/requestpermission)  Requests permission from the user to display notifications.

  

Instance methods
----------------



These properties are available only on an instance of the `Notification` object or through its [`prototype`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain). The `Notification` object also inherits from the [`EventTarget`](eventtarget) interface.

  [`Notification.close()`](notification/close)  Programmatically closes a notification instance.

  

Events
------


 [`click`](notification/click_event)  Fires when the user clicks the notification.

  [`close`](notification/close_event)  Fires when the user closes the notification.

  [`error`](notification/error_event)  Fires when the notification encounters an error.

  [`show`](notification/show_event)  Fires when the notification is displayed.

  
Examples
--------



Assume this basic HTML:

 
```
<button onclick="notifyMe()">Notify me!</button>

```
 It's possible to send a notification as follows — here we present a fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification.

 
```
function notifyMe() {
  if (!("Notification" in window)) {
    // Check if the browser supports notifications
    alert("This browser does not support desktop notification");
  } else if (Notification.permission === "granted") {
    // Check whether notification permissions have already been granted;
    // if so, create a notification
    const notification = new Notification("Hi there!");
    // …
  } else if (Notification.permission !== "denied") {
    // We need to ask the user for permission
    Notification.requestPermission().then((permission) => {
      // If the user accepts, let's create a notification
      if (permission === "granted") {
        const notification = new Notification("Hi there!");
        // …
      }
    });
  }

  // At last, if the user has denied notifications, and you
  // want to be respectful there is no need to bother them anymore.
}

```
 We no longer show a live sample on this page, as Chrome and Firefox no longer allow notification permissions to be requested from cross-origin [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe)s, with other browsers to follow. To see an example in action, check out our [To-do list example](https://github.com/mdn/dom-examples/tree/main/to-do-notifications) (also see [the app running live](https://mdn.github.io/dom-examples/to-do-notifications/)).

  **Note:** In the above example we spawn notifications in response to a user gesture (clicking a button). This is not only best practice — you should not be spamming users with notifications they didn't agree to — but going forward browsers will explicitly disallow notifications not triggered in response to a user gesture. Firefox is already doing this from version 72, for example.

 

Specifications
--------------




| Specification |
| --- |
| [Notifications API Standard # api](https://notifications.spec.whatwg.org/#api) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Notification` | 20 | 14 | 224 | No | 23 | 7 | No | No | 224 | No | 16.4 | No |
| `Notification` | 20["Starting in Chrome 49, notifications do not work in incognito mode.", "Before Chrome 42, service worker additions were not supported."] | 14 | 224 | No | 23["Starting in Opera 36, notifications do not work in incognito mode.", "Before Opera 29, service worker additions were not supported."] | 7 | NoSee [bug 551446](https://crbug.com/551446). | 42["Notifications in Chrome for Android are only available through service workers. To show notifications on Android, see [`ServiceWorkerRegistration.showNotification()`](https://developer.mozilla.org/docs/Web/API/ServiceWorkerRegistration/showNotification).", "Starting in Chrome 49, notifications do not work in incognito mode."] | 224 | 29["Notifications in Opera for Android are only available through service workers. To show notifications on Android, see [`ServiceWorkerRegistration.showNotification()`](https://developer.mozilla.org/docs/Web/API/ServiceWorkerRegistration/showNotification).", "Starting in Opera for Android 36, notifications do not work in incognito mode."] | 16.4 | 4.0["Notifications in Samsung Internet are only available through service workers. To show notifications on Android, see [`ServiceWorkerRegistration.showNotification()`](https://developer.mozilla.org/docs/Web/API/ServiceWorkerRegistration/showNotification).", "Starting in Samsung Internet 5.0, notifications do not work in incognito mode."] |
| `actions` | 53 | 18 | No | No | 39 | No | No | 53 | No | 41 | No | 6.0 |
| `badge` | 53 | 18 | No | No | 39 | No | No | 53 | No | 41 | No | 6.0 |
| `body` | 33 | 14 | 26 | No | 23 | 11 | No | 42 | 26 | 29 | 16.4 | 4.0 |
| `click_event` | 20 | 14 | 22 | No | 23 | 7 | No | 42 | 22 | 29 | No | 4.0 |
| `close` | 20 | 14 | 22 | No | 23 | 7 | No | 42 | 22 | 29 | 16.4 | 4.0 |
| `close_event` | 20 | 14 | 22 | No | 23 | 7 | No | 42 | 22 | 29 | No | 4.0 |
| `data` | 44 | 16 | 34 | No | 31 | 16 | No | 44 | 34 | 32 | 16.4 | 4.0 |
| `dir` | 20 | 14 | 26 | No | 23 | 7 | No | 42 | 26 | 29 | 16.4 | 4.0 |
| `error_event` | 20 | 14 | 22 | No | 23 | 7 | No | 42 | 22 | 29 | No | 4.0 |
| `icon` | 33 | 14 | 26 | No | 23 | 11 | No | 42 | 26 | 29 | 16.4 | 4.0 |
| `image` | 56 | 18 | No | No | 43 | No | No | 56 | No | 43 | No | 6.0 |
| `lang` | 33 | 14 | 26 | No | 23 | 11 | No | 42 | 26 | 29 | 16.4 | 4.0 |
| `maxActions` | 48 | 18 | No | No | 35 | No | No | 48 | No | 35 | No | 5.0 |
| `permission` | 32 | 14 | 22 | No | 23 | 7 | No | 42 | 22 | 29 | 16.4 | 4.0 |
| `renotify` | 50 | 79 | No | No | 37 | No | No | 50 | No | 37 | No | 5.0 |
| `requestPermission` | 20 | 14 | 22["From Firefox 70 onwards, cannot be called from a cross-origin `iframe`.", "From Firefox 72 onwards, can only be called in response to a user gesture such as a `click` event."] | No | 23 | 157–15Only supported the deprecated callback syntax. | No | 42 | 22["From Firefox Android 79 onwards, cannot be called from a cross-origin `iframe`.", "From Firefox Android 79 onwards, can only be called in response to a user gesture such as a `click` event."] | 29 | 16.4 | 4.0 |
| `requireInteraction` | 47 | 17 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |
| `secure_context_required` | 62 | 79 | 67 | No | 49 | No | No | 62 | 67 | 46 | No | 8.0 |
| `show_event` | 20 | 14 | 22 | No | 23 | 7 | No | 42 | 22 | 29 | No | 4.0 |
| `silent` | 43 | 17 | No | No | 30 | No | No | 43 | No | 30 | No | 4.0 |
| `tag` | 20 | 14 | 26 | No | 23 | 7 | No | 42 | 26 | 29 | 16.4 | 4.0 |
| `timestamp` | 50 | 17 | No | No | 37 | No | No | 50 | No | 37 | No | 5.0 |
| `title` | 33 | 14 | 26 | No | 23 | 11 | No | 42 | 26 | 29 | 16.4 | 4.0 |
| `vibrate` | 53 | 79 | No | No | 40 | No | No | 53[Does not work](https://crbug.com/971422) on Android O or later regardless of Chrome version. | No | 41[Does not work](https://crbug.com/971422) on Android O or later regardless of Chrome version. | No | 6.0[Does not work](https://crbug.com/971422) on Android O or later regardless of Chrome version. |
| `worker_support` | 42 | 15 | 41 | No | 29 | No | No | 42 | 41 | 29 | No | 4.0 |


See also
--------


* [Using the Notifications API](notifications_api/using_the_notifications_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Notification>

NotifyAudioAvailableEvent
=========================



**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.


**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The non-standard, obsolete, `NotifyAudioAvailableEvent` interface defines the event sent to audio elements when the audio buffer is full.



Instance properties
-------------------


 
`frameBuffer` Read only 
  A [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) containing the raw 32-bit floating-point audio data obtained from decoding the audio (e.g., the raw data being sent to the audio hardware vs. encoded audio). The data is a series of audio samples, each sample containing one 32-bit value per audio channel. All audio frames are normalized to contain 1024 samples by default, but could be any length between 512 and 16384 samples if the user has set a different length using the `mozFrameBufferLength` attribute.

  `time`  A floating-point value indicating the time in seconds at which the first sample in the `frameBuffer` occurs, relative to the start of the audio track.

  

 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/NotifyAudioAvailableEvent>

OffscreenCanvasRenderingContext2D
=================================



 The `OffscreenCanvasRenderingContext2D` interface is a [`CanvasRenderingContext2D`](canvasrenderingcontext2d) 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 (`drawFocusIfNeeded`, and `scrollPathIntoView`)
* its `canvas` attribute refers to an `OffscreenCanvas` object rather than a [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element
* it has a `commit()` method for pushing rendered images to the context's `OffscreenCanvas` object's placeholder [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element



Example
-------



 The following code snippet creates a [`Worker`](worker) object using the [`Worker()`](worker/worker) constructor. The `transferControlToOffscreen()` method is used to transfer the `OffscreenCanvas` object to the worker: 

 
```
const canvas = document.getElementById("canvas");
const offscreen = canvas.transferControlToOffscreen();
const worker = new Worker("worker.js");
worker.postMessage({ canvas: offscreen }, [offscreen]);

```
 In the worker thread, we can use the `OffscreenCanvasRenderingContext2D` to draw to the bitmap of the `OffscreenCanvas` object:

 
```
onmessage = (event) => {
  const canvas = event.data.canvas;
  const offCtx = canvas.getContext("2d");
  // draw to the offscreen canvas context
  offCtx.fillStyle = "red";
  offCtx.fillRect(0, 0, 100, 100);
};

```
 For a full example, see our [OffscreenCanvas worker example](https://github.com/mdn/dom-examples/tree/main/web-workers/offscreen-canvas-worker) ([run OffscreenCanvas worker](https://mdn.github.io/dom-examples/web-workers/offscreen-canvas-worker/)).



Additional methods
------------------



The following method is new to the `OffscreenCanvasRenderingContext2D` interface and does not exist in the `CanvasRenderingContext2D` interface:

  [`commit()`](offscreencanvasrenderingcontext2d/commit)  Pushes the rendered image to the context's `OffscreenCanvas` object's placeholder [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element.

  

Unsupported features
--------------------



The following user interface methods are **not supported** by the `OffscreenCanvasRenderingContext2D` interface:

  [`CanvasRenderingContext2D.drawFocusIfNeeded()`](canvasrenderingcontext2d/drawfocusifneeded)  If a given element is focused, this method draws a focus ring around the current path.

  
[`CanvasRenderingContext2D.scrollPathIntoView()`](canvasrenderingcontext2d/scrollpathintoview)  Experimental 
  Scrolls the current path or a given path into the view.

  

Inherited properties and methods
--------------------------------


*The following properties and methods are inherited from [`CanvasRenderingContext2D`](canvasrenderingcontext2d). They have the same usage as in `CanvasRenderingContext2D`*


### Context


 
[`CanvasRenderingContext2D.isContextLost()`](canvasrenderingcontext2d/iscontextlost)  Experimental 
  Returns `true` if the rendering context was lost.

  
### Drawing rectangles


 [`CanvasRenderingContext2D.clearRect()`](canvasrenderingcontext2d/clearrect)  Sets all pixels in the rectangle defined by starting point *(x, y)* and size *(width, height)* to transparent black, erasing any previously drawn content.

  [`CanvasRenderingContext2D.fillRect()`](canvasrenderingcontext2d/fillrect)  Draws a filled rectangle at *(x, y)* position whose size is determined by *width* and *height*.

  [`CanvasRenderingContext2D.strokeRect()`](canvasrenderingcontext2d/strokerect)  Paints a rectangle which has a starting point at *(x, y)* and has a *w* width and an *h* height onto the canvas, using the current stroke style.

  
### Drawing text



The following methods and properties control drawing text. See also the [`TextMetrics`](textmetrics) object for text properties.

  [`CanvasRenderingContext2D.fillText()`](canvasrenderingcontext2d/filltext)  Draws (fills) a given text at the given (x, y) position.

  [`CanvasRenderingContext2D.strokeText()`](canvasrenderingcontext2d/stroketext)  Draws (strokes) a given text at the given (x, y) position.

  [`CanvasRenderingContext2D.measureText()`](canvasrenderingcontext2d/measuretext)  Returns a [`TextMetrics`](textmetrics) object.

  
[`CanvasRenderingContext2D.textRendering`](canvasrenderingcontext2d/textrendering)  Experimental 
  Text rendering. Possible values: `auto` (default), `optimizeSpeed`, `optimizeLegibility`,

  

### Line styles



The following methods and properties control how lines are drawn.

  [`CanvasRenderingContext2D.lineWidth`](canvasrenderingcontext2d/linewidth)  Width of lines. Default `1.0`.

  [`CanvasRenderingContext2D.lineCap`](canvasrenderingcontext2d/linecap)  Type of endings on the end of lines. Possible values: `butt` (default), `round`, `square`.

  [`CanvasRenderingContext2D.lineJoin`](canvasrenderingcontext2d/linejoin)  Defines the type of corners where two lines meet. Possible values: `round`, `bevel`, `miter` (default).

  [`CanvasRenderingContext2D.miterLimit`](canvasrenderingcontext2d/miterlimit)  Miter limit ratio. Default `10`.

  [`CanvasRenderingContext2D.getLineDash()`](canvasrenderingcontext2d/getlinedash)  Returns the current line dash pattern array containing an even number of non-negative numbers.

  [`CanvasRenderingContext2D.setLineDash()`](canvasrenderingcontext2d/setlinedash)  Sets the current line dash pattern.

  [`CanvasRenderingContext2D.lineDashOffset`](canvasrenderingcontext2d/linedashoffset)  Specifies where to start a dash array on a line.

  

### Text styles



The following properties control how text is laid out.

  [`CanvasRenderingContext2D.font`](canvasrenderingcontext2d/font)  Font setting. Default value `10px sans-serif`.

  [`CanvasRenderingContext2D.textAlign`](canvasrenderingcontext2d/textalign)  Text alignment setting. Possible values: `start` (default), `end`, `left`, `right`, `center`.

  [`CanvasRenderingContext2D.textBaseline`](canvasrenderingcontext2d/textbaseline)  Baseline alignment setting. Possible values: `top`, `hanging`, `middle`, `alphabetic` (default), `ideographic`, `bottom`.

  [`CanvasRenderingContext2D.direction`](canvasrenderingcontext2d/direction)  Directionality. Possible values: `ltr`, `rtl`, `inherit` (default).

  
[`CanvasRenderingContext2D.letterSpacing`](canvasrenderingcontext2d/letterspacing)  Experimental 
  Letter spacing. Default: `0px`.

  [`CanvasRenderingContext2D.fontKerning`](canvasrenderingcontext2d/fontkerning)  Font kerning. Possible values: `auto` (default), `normal`, `none`.

  
[`CanvasRenderingContext2D.fontStretch`](canvasrenderingcontext2d/fontstretch)  Experimental 
  Font stretch. Possible values: `ultra-condensed`, `extra-condensed`, `condensed`, `semi-condensed`, `normal` (default), `semi-expanded`, `expanded`, `extra-expanded`, `ultra-expanded`.

  
[`CanvasRenderingContext2D.fontVariantCaps`](canvasrenderingcontext2d/fontvariantcaps)  Experimental 
  Font variant caps. Possible values: `normal` (default), `small-caps`, `all-small-caps`, `petite-caps`, `all-petite-caps`, `unicase`, `titling-caps`.

  
[`CanvasRenderingContext2D.textRendering`](canvasrenderingcontext2d/textrendering)  Experimental 
  Text rendering. Possible values: `auto` (default), `optimizeSpeed`, `optimizeLegibility`, `geometricPrecision`.

  
[`CanvasRenderingContext2D.wordSpacing`](canvasrenderingcontext2d/wordspacing)  Experimental 
  Word spacing. Default value: `0px`

  

### Fill and stroke styles



Fill styling is used for colors and styles inside shapes and stroke styling is used for the lines around shapes.

  [`CanvasRenderingContext2D.fillStyle`](canvasrenderingcontext2d/fillstyle)  Color or style to use inside shapes. Default `#000` (black).

  [`CanvasRenderingContext2D.strokeStyle`](canvasrenderingcontext2d/strokestyle)  Color or style to use for the lines around shapes. Default `#000` (black).

  

### Gradients and patterns


 [`CanvasRenderingContext2D.createConicGradient()`](canvasrenderingcontext2d/createconicgradient)  Creates a conic gradient around a point given by coordinates represented by the parameters.

  [`CanvasRenderingContext2D.createLinearGradient()`](canvasrenderingcontext2d/createlineargradient)  Creates a linear gradient along the line given by the coordinates represented by the parameters.

  [`CanvasRenderingContext2D.createRadialGradient()`](canvasrenderingcontext2d/createradialgradient)  Creates a radial gradient given by the coordinates of the two circles represented by the parameters.

  [`CanvasRenderingContext2D.createPattern()`](canvasrenderingcontext2d/createpattern)  Creates a pattern using the specified image. It repeats the source in the directions specified by the repetition argument. This method returns a [`CanvasPattern`](canvaspattern).

  
### Shadows


 [`CanvasRenderingContext2D.shadowBlur`](canvasrenderingcontext2d/shadowblur)  Specifies the blurring effect. Default: `0`.

  [`CanvasRenderingContext2D.shadowColor`](canvasrenderingcontext2d/shadowcolor)  Color of the shadow. Default: fully-transparent black.

  [`CanvasRenderingContext2D.shadowOffsetX`](canvasrenderingcontext2d/shadowoffsetx)  Horizontal distance the shadow will be offset. Default: `0`.

  [`CanvasRenderingContext2D.shadowOffsetY`](canvasrenderingcontext2d/shadowoffsety)  Vertical distance the shadow will be offset. Default: `0`.

  
### Paths



The following methods can be used to manipulate paths of objects.

  [`CanvasRenderingContext2D.beginPath()`](canvasrenderingcontext2d/beginpath)  Starts a new path by emptying the list of sub-paths. Call this method when you want to create a new path.

  [`CanvasRenderingContext2D.closePath()`](canvasrenderingcontext2d/closepath)  Causes the point of the pen to move back to the start of the current sub-path. It tries to draw a straight line from the current point to the start. If the shape has already been closed or has only one point, this function does nothing.

  [`CanvasRenderingContext2D.moveTo()`](canvasrenderingcontext2d/moveto)  Moves the starting point of a new sub-path to the (x, y) coordinates.

  [`CanvasRenderingContext2D.lineTo()`](canvasrenderingcontext2d/lineto)  Connects the last point in the current sub-path to the specified (x, y) coordinates with a straight line.

  [`CanvasRenderingContext2D.bezierCurveTo()`](canvasrenderingcontext2d/beziercurveto)  Adds a cubic Bézier curve to the current path.

  [`CanvasRenderingContext2D.quadraticCurveTo()`](canvasrenderingcontext2d/quadraticcurveto)  Adds a quadratic Bézier curve to the current path.

  [`CanvasRenderingContext2D.arc()`](canvasrenderingcontext2d/arc)  Adds a circular arc to the current path.

  [`CanvasRenderingContext2D.arcTo()`](canvasrenderingcontext2d/arcto)  Adds an arc to the current path with the given control points and radius, connected to the previous point by a straight line.

  [`CanvasRenderingContext2D.ellipse()`](canvasrenderingcontext2d/ellipse)  Adds an elliptical arc to the current path.

  [`CanvasRenderingContext2D.rect()`](canvasrenderingcontext2d/rect)  Creates a path for a rectangle at position (x, y) with a size that is determined by *width* and *height*.

  

### Drawing paths


 [`CanvasRenderingContext2D.fill()`](canvasrenderingcontext2d/fill)  Fills the current sub-paths with the current fill style.

  [`CanvasRenderingContext2D.stroke()`](canvasrenderingcontext2d/stroke)  Strokes the current sub-paths with the current stroke style.

  [`CanvasRenderingContext2D.clip()`](canvasrenderingcontext2d/clip)  Creates a clipping path from the current sub-paths. Everything drawn after `clip()` is called appears inside the clipping path only. For an example, see [Clipping paths](canvas_api/tutorial/compositing) in the Canvas tutorial.

  [`CanvasRenderingContext2D.isPointInPath()`](canvasrenderingcontext2d/ispointinpath)  Reports whether or not the specified point is contained in the current path.

  [`CanvasRenderingContext2D.isPointInStroke()`](canvasrenderingcontext2d/ispointinstroke)  Reports whether or not the specified point is inside the area contained by the stroking of a path.

  [`CanvasRenderingContext2D.roundRect()`](canvasrenderingcontext2d/roundrect)  Addition to CanvasPath that allows users to render rectangles with rounded corners.

  
### Transformations



Objects in the `CanvasRenderingContext2D` rendering context have a current transformation matrix and methods to manipulate it. The transformation matrix is applied when creating the current default path, painting text, shapes and [`Path2D`](path2d) objects. The methods listed below remain for historical and compatibility reasons as [`DOMMatrix`](dommatrix) objects are used in most parts of the API nowadays and will be used in the future instead.

  [`CanvasRenderingContext2D.getTransform()`](canvasrenderingcontext2d/gettransform)  Retrieves the current transformation matrix being applied to the context.

  [`CanvasRenderingContext2D.rotate()`](canvasrenderingcontext2d/rotate)  Adds a rotation to the transformation matrix. The angle argument represents a clockwise rotation angle and is expressed in radians.

  [`CanvasRenderingContext2D.scale()`](canvasrenderingcontext2d/scale)  Adds a scaling transformation to the canvas units by x horizontally and by y vertically.

  [`CanvasRenderingContext2D.translate()`](canvasrenderingcontext2d/translate)  Adds a translation transformation by moving the canvas and its origin x horizontally and y vertically on the grid.

  [`CanvasRenderingContext2D.transform()`](canvasrenderingcontext2d/transform)  Multiplies the current transformation matrix with the matrix described by its arguments.

  [`CanvasRenderingContext2D.setTransform()`](canvasrenderingcontext2d/settransform)  Resets the current transform to the identity matrix, and then invokes the `transform()` method with the same arguments.

  [`CanvasRenderingContext2D.resetTransform()`](canvasrenderingcontext2d/resettransform)  Resets the current transform by the identity matrix.

  

### Compositing


 [`CanvasRenderingContext2D.globalAlpha`](canvasrenderingcontext2d/globalalpha)  Alpha value that is applied to shapes and images before they are composited onto the canvas. Default `1.0` (opaque).

  [`CanvasRenderingContext2D.globalCompositeOperation`](canvasrenderingcontext2d/globalcompositeoperation)  With `globalAlpha` applied this sets how shapes and images are drawn onto the existing bitmap.

  
### Drawing images


 [`CanvasRenderingContext2D.drawImage()`](canvasrenderingcontext2d/drawimage)  Draws the specified image. This method is available in multiple formats, providing a great deal of flexibility in its use.

  
### Pixel manipulation



See also the [`ImageData`](imagedata) object.

  [`CanvasRenderingContext2D.createImageData()`](canvasrenderingcontext2d/createimagedata)  Creates a new, blank [`ImageData`](imagedata) object with the specified dimensions. All of the pixels in the new object are transparent black.

  [`CanvasRenderingContext2D.getImageData()`](canvasrenderingcontext2d/getimagedata)  Returns an [`ImageData`](imagedata) object representing the underlying pixel data for the area of the canvas denoted by the rectangle which starts at *(sx, sy)* and has an *sw* width and *sh* height.

  [`CanvasRenderingContext2D.putImageData()`](canvasrenderingcontext2d/putimagedata)  Paints data from the given [`ImageData`](imagedata) object onto the bitmap. If a dirty rectangle is provided, only the pixels from that rectangle are painted.

  

### Image smoothing


 [`CanvasRenderingContext2D.imageSmoothingEnabled`](canvasrenderingcontext2d/imagesmoothingenabled)  Image smoothing mode; if disabled, images will not be smoothed if scaled.

  [`CanvasRenderingContext2D.imageSmoothingQuality`](canvasrenderingcontext2d/imagesmoothingquality)  Allows you to set the quality of image smoothing.

  
### The canvas state



The `CanvasRenderingContext2D` rendering context contains a variety of drawing style states (attributes for line styles, fill styles, shadow styles, text styles). The following methods help you to work with that state:

  [`CanvasRenderingContext2D.save()`](canvasrenderingcontext2d/save)  Saves the current drawing style state using a stack so you can revert any change you make to it using `restore()`.

  [`CanvasRenderingContext2D.restore()`](canvasrenderingcontext2d/restore)  Restores the drawing style state to the last element on the 'state stack' saved by `save()`.

  [`CanvasRenderingContext2D.canvas`](canvasrenderingcontext2d/canvas)  A read-only reference to an `OffscreenCanvas` object.

  [`CanvasRenderingContext2D.getContextAttributes()`](canvasrenderingcontext2d/getcontextattributes)  Returns an object containing the actual context attributes. Context attributes can be requested with [`HTMLCanvasElement.getContext()`](htmlcanvaselement/getcontext).

  [`CanvasRenderingContext2D.reset()`](canvasrenderingcontext2d/reset)  Resets the current drawing style state to the default values.

  

### Filters


 [`CanvasRenderingContext2D.filter`](canvasrenderingcontext2d/filter)  Applies a CSS or SVG filter to the canvas; e.g., to change its brightness or blurriness.

  
Unsupported properties and methods
----------------------------------



The following methods are **not supported** in the `OffscreenCanvasRenderingContext2D` interface:

  [`CanvasRenderingContext2D.drawFocusIfNeeded()`](canvasrenderingcontext2d/drawfocusifneeded)  If a given element is focused, this method draws a focus ring around the current path.

  
[`CanvasRenderingContext2D.scrollPathIntoView()`](canvasrenderingcontext2d/scrollpathintoview)  Experimental 
  Scrolls the current path or a given path into the view.

  

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-offscreen-2d-rendering-context](https://html.spec.whatwg.org/multipage/canvas.html#the-offscreen-2d-rendering-context) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `OffscreenCanvasRenderingContext2D` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `arc` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `arcTo` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `beginPath` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `bezierCurveTo` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `canvas` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `clearRect` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `clip` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `closePath` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `commit` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `createConicGradient` | 99 | 99 | 105 | No | 85 | 16.4 | 99 | 99 | 105 | 68 | 16.4 | 18.0 |
| `createImageData` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `createLinearGradient` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `createPattern` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `createRadialGradient` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `direction` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `drawImage` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `ellipse` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `fill` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `fillRect` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `fillStyle` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `fillText` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `filter` | 69 | 79 | 105 | No | 56 | No | 69 | 69 | 105 | 48 | No | 10.0 |
| `font` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `fontKerning` | 99 | 99 | 105 | No | 85 | No | 99 | 99 | 105 | 68 | No | 18.0 |
| `fontStretch` | 99 | 99 | No | No | 85 | No | 99 | 99 | No | 68 | No | 18.0 |
| `fontVariantCaps` | 99 | 99 | No | No | 85 | No | 99 | 99 | No | 68 | No | 18.0 |
| `getImageData` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `getLineDash` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `getTransform` | 80 | 80 | 105 | No | 67 | 16.4 | 80 | 80 | 105 | 57 | 16.4 | 13.0 |
| `globalAlpha` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `globalCompositeOperation` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `imageSmoothingEnabled` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `imageSmoothingQuality` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `isContextLost` | 99 | 99 | No | No | 85 | No | 99 | 99 | No | 68 | No | 18.0 |
| `isPointInPath` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `isPointInStroke` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `letterSpacing` | 99 | 99 | No | No | 85 | No | 99 | 99 | No | 68 | No | 18.0 |
| `lineCap` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `lineDashOffset` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `lineJoin` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `lineTo` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `lineWidth` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `measureText` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `miterLimit` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `moveTo` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `putImageData` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `quadraticCurveTo` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `rect` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `reset` | 99 | 99 | 113 | No | 85 | No | 99 | 99 | 113 | 68 | No | 18.0 |
| `resetTransform` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `restore` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `rotate` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `roundRect` | 99 | 99 | 112 | No | 85 | 16.4 | 99 | 99 | 112 | 68 | 16.4 | 18.0 |
| `save` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `scale` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `setLineDash` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `setTransform` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `shadowBlur` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `shadowColor` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `shadowOffsetX` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `shadowOffsetY` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `stroke` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `strokeRect` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `strokeStyle` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `strokeText` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `textAlign` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `textBaseline` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `textRendering` | 99 | 99 | No | No | 85 | No | 99 | 99 | No | 68 | No | 18.0 |
| `transform` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `translate` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `wordSpacing` | 99 | 99 | No | No | 85 | No | 99 | 99 | No | 68 | No | 18.0 |


See also
--------


* [`HTMLCanvasElement`](htmlcanvaselement)
* [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvasRenderingContext2D>

OTPCredential
=============



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `OTPCredential` interface of the [WebOTP API](webotp_api) contains the attributes that are returned when a new one-time password is retrieved.


 Credential OTPCredential

Instance properties
-------------------



*This interface also inherits properties from [`Credential`](credential).*

  
[`OTPCredential.code`](otpcredential/code)  Experimental 
  The one-time password.

  

### Event handlers


None.


Instance methods
----------------


None.


Examples
--------



The below code triggers the browser's permission flow when an SMS message arrives. If permission is granted then the promise resolves with an `OTPCredential` object. [See this code as part of a simple demo](https://glitch.com/edit/#!/web-otp?path=views%2Findex.html%3A55%3A8).

 
```
navigator.credentials
  .get({
    otp: { transport: ["sms"] },
    signal: ac.signal,
  })
  .then((otp) => {
    input.value = otp.code;
    if (form) form.submit();
  })
  .catch((err) => {
    console.error(err);
  });

```


Specifications
--------------




| Specification |
| --- |
| [WebOTP API # OTPCredential](https://wicg.github.io/web-otp/#OTPCredential) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `OTPCredential` | 93 | 93 | No | No | 79 | No | No | 84 | No | 60 | No | 14.0 |
| `code` | 93 | 93 | No | No | 79 | No | No | 84 | No | 60 | No | 14.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/OTPCredential>

NotificationEvent
=================



The parameter passed into the [`onnotificationclick`](serviceworkerglobalscope/notificationclick_event) handler, the `NotificationEvent` interface represents a notification click event that is dispatched on the [`ServiceWorkerGlobalScope`](serviceworkerglobalscope) of a [`ServiceWorker`](serviceworker).

 This interface inherits from the [`ExtendableEvent`](extendableevent) interface.


 Event ExtendableEvent NotificationEvent

Constructor
-----------


 [`NotificationEvent()`](notificationevent/notificationevent)  Creates a new `NotificationEvent` object.

  
Instance properties
-------------------



*Inherits properties from its ancestor, [`Event`](event)*.

  
[`NotificationEvent.notification`](notificationevent/notification) Read only 
  Returns a [`Notification`](notification) object representing the notification that was clicked to fire the event.

  
[`NotificationEvent.action`](notificationevent/action) Read only 
  Returns the string ID of the notification button the user clicked. This value returns an empty string if the user clicked the notification somewhere other than an action button, or the notification does not have a button.

  

Instance methods
----------------



*Inherits methods from its parent, [`ExtendableEvent`](extendableevent)*.

  [`ExtendableEvent.waitUntil()`](extendableevent/waituntil)  Extends the lifetime of the event. Tells the browser that work is ongoing.

  

Example
-------



```
self.addEventListener("notificationclick", (event) => {
  console.log(`On notification click: ${event.notification.tag}`);
  event.notification.close();

  // This looks to see if the current is already open and
  // focuses if it is
  event.waitUntil(
    clients
      .matchAll({
        type: "window",
      })
      .then((clientList) => {
        for (const client of clientList) {
          if (client.url === "/" && "focus" in client) return client.focus();
        }
        if (clients.openWindow) return clients.openWindow("/");
      })
  );
});

```

Specifications
--------------




| Specification |
| --- |
| [Notifications API Standard # notificationevent](https://notifications.spec.whatwg.org/#notificationevent) |


 **Note:** This interface is specified in the [Notifications API](notifications_api), but accessed through [`ServiceWorkerGlobalScope`](serviceworkerglobalscope).

 
Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `NotificationEvent` | 42 | 17 | 44 | No | 37 | 16Supported on macOS 13 and later | No | 42 | 44 | 37 | 16.4 | 4.0 |
| `NotificationEvent` | 42 | 17 | 44 | No | 37 | 16Supported on macOS 13 and later | NoSee [bug 551446](https://crbug.com/551446). | 42 | 44 | 37 | 16.4 | 4.0 |
| `action` | 48 | 17 | 44 | No | No | No | No | 48 | 44 | No | No | 5.0 |
| `notification` | 42 | 17 | 44 | No | 37 | No | No | 42 | 44 | 37 | No | 4.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/NotificationEvent>

OES\_draw\_buffers\_indexed
===========================



The `OES_draw_buffers_indexed` extension is part of the [WebGL API](webgl_api) and enables the use of different blend options when writing to multiple color buffers simultaneously.

 WebGL extensions are available using the [`WebGLRenderingContext.getExtension()`](webglrenderingcontext/getextension) method. For more information, see also [Using Extensions](webgl_api/using_extensions) in the [WebGL tutorial](webgl_api/tutorial).

  **Note:** This extension is only available to [WebGL2](webgl2renderingcontext) contexts.

 

Instance methods
----------------


 [`OES_draw_buffers_indexed.blendEquationiOES()`](oes_draw_buffers_indexed/blendequationioes)  Sets both the RGB and alpha blend equations for a particular draw buffer.

  [`OES_draw_buffers_indexed.blendEquationSeparateiOES()`](oes_draw_buffers_indexed/blendequationseparateioes)  Sets the RGB and alpha blend equations separately for a particular draw buffer.

  [`OES_draw_buffers_indexed.blendFunciOES()`](oes_draw_buffers_indexed/blendfuncioes)  Defines which function is used when blending pixels for a particular draw buffer.

  [`OES_draw_buffers_indexed.blendFuncSeparateiOES()`](oes_draw_buffers_indexed/blendfuncseparateioes)  Defines which function is used when blending pixels for RGB and alpha components separately for a particular draw buffer.

  [`OES_draw_buffers_indexed.colorMaskiOES()`](oes_draw_buffers_indexed/colormaskioes)  Sets which color components to enable or to disable when drawing or rendering for a particular draw buffer.

  [`OES_draw_buffers_indexed.disableiOES()`](oes_draw_buffers_indexed/disableioes)  Disables blending for a particular draw buffer.

  [`OES_draw_buffers_indexed.enableiOES()`](oes_draw_buffers_indexed/enableioes)  Enables blending for a particular draw buffer.

  
Examples
--------


### Using the `OES_draw_buffers_indexed` extension



Enable the extension with a call to [`WebGLRenderingContext.getExtension()`](webglrenderingcontext/getextension).

 
```
const ext = gl.getExtension("OES\_draw\_buffers\_indexed");

```
 You can now enable blending, set blending equation, blending function, and color mask for a particular draw buffer.

 
```
// For gl.DRAW\_BUFFER0
ext.enableiOES(gl.BLEND, 0);
ext.blendEquationiOES(0, gl.FUNC\_ADD);
ext.blendFunciOES(0, gl.ONE, gl.ONE);
ext.colorMaskiOES(0, 1, 0, 0, 0);

// For gl.DRAW\_BUFFER1
ext.enableiOES(gl.BLEND, 1);
ext.blendEquationSeparateiOES(1, gl.FUNC\_ADD, gl.FUNC\_SUBTRACT);
ext.blendFuncSeparateiOES(1, gl.SRC\_ALPHA, gl.ONE\_MINUS\_SRC\_ALPHA, gl.ZERO, gl.ZERO);
ext.colorMaskiOES(1, 0, 1, 0, 0);

```
 To retrieve settings for a particular draw buffer, use [`WebGL2RenderingContext.getIndexedParameter()`](webgl2renderingcontext/getindexedparameter).

 
```
// For gl.DRAW\_BUFFER0
gl.getIndexedParameter(gl.BLEND\_EQUATION\_RGB, 0);
gl.getIndexedParameter(gl.BLEND\_EQUATION\_ALPHA, 0);
gl.getIndexedParameter(gl.BLEND\_SRC\_RGB, 0);
gl.getIndexedParameter(gl.BLEND\_SRC\_ALPHA, 0);
gl.getIndexedParameter(gl.BLEND\_DST\_RGB, 0);
gl.getIndexedParameter(gl.BLEND\_DST\_ALPHA, 0);
gl.getIndexedParameter(gl.COLOR\_WRITEMASK, 0);

// For gl.DRAW\_BUFFER1
gl.getIndexedParameter(gl.BLEND\_EQUATION\_RGB, 1);
gl.getIndexedParameter(gl.BLEND\_EQUATION\_ALPHA, 1);
gl.getIndexedParameter(gl.BLEND\_SRC\_RGB, 1);
gl.getIndexedParameter(gl.BLEND\_SRC\_ALPHA, 1);
gl.getIndexedParameter(gl.BLEND\_DST\_RGB, 1);
gl.getIndexedParameter(gl.BLEND\_DST\_ALPHA, 1);
gl.getIndexedParameter(gl.COLOR\_WRITEMASK, 1);

```
 You can use [`WebGLRenderingContext.getParameter()`](webglrenderingcontext/getparameter) to see how many draw buffers are available.

 
```
const maxDrawBuffers = gl.getParameter(gl.MAX\_DRAW\_BUFFERS);

```


Specifications
--------------




| Specification |
| --- |
| [WebGL OES\_draw\_buffers\_indexed Extension Specification](https://registry.khronos.org/webgl/extensions/OES_draw_buffers_indexed/)  |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `OES_draw_buffers_indexed` | 100 | 100 | 108 | No | 86 | 16 | 100 | 100 | 108 | 69 | 16 | 19.0 |
| `blendEquationSeparateiOES` | 100 | 100 | 108 | No | 86 | 16 | 100 | 100 | 108 | 69 | 16 | 19.0 |
| `blendEquationiOES` | 100 | 100 | 108 | No | 86 | 16 | 100 | 100 | 108 | 69 | 16 | 19.0 |
| `blendFuncSeparateiOES` | 100 | 100 | 108 | No | 86 | 16 | 100 | 100 | 108 | 69 | 16 | 19.0 |
| `blendFunciOES` | 100 | 100 | 108 | No | 86 | 16 | 100 | 100 | 108 | 69 | 16 | 19.0 |
| `colorMaskiOES` | 100 | 100 | 108 | No | 86 | 16 | 100 | 100 | 108 | 69 | 16 | 19.0 |
| `disableiOES` | 100 | 100 | 108 | No | 86 | 16 | 100 | 100 | 108 | 69 | 16 | 19.0 |
| `enableiOES` | 100 | 100 | 108 | No | 86 | 16 | 100 | 100 | 108 | 69 | 16 | 19.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/OES_draw_buffers_indexed>

OfflineAudioCompletionEvent
===========================



The [Web Audio API](web_audio_api) `OfflineAudioCompletionEvent` interface represents events that occur when the processing of an [`OfflineAudioContext`](offlineaudiocontext) is terminated. The [`complete`](offlineaudiocontext/complete_event) event uses this interface.

  **Note:** This interface is marked as deprecated; it is still supported for legacy reasons, but it will soon be superseded when the promise version of [`OfflineAudioContext.startRendering`](offlineaudiocontext/startrendering) is supported in browsers, which will no longer need it.

 
 Event OfflineAudioCompletionEvent

Constructor
-----------


 [`OfflineAudioCompletionEvent()`](offlineaudiocompletionevent/offlineaudiocompletionevent)  Creates a new `OfflineAudioCompletionEvent` object instance.

  
Instance properties
-------------------



*Also inherits properties from its parent, [`Event`](event)*.

  
[`OfflineAudioCompletionEvent.renderedBuffer`](offlineaudiocompletionevent/renderedbuffer) Read only 
  An [`AudioBuffer`](audiobuffer) containing the result of processing an [`OfflineAudioContext`](offlineaudiocontext).

  

Instance methods
----------------


*Inherits methods from its parent, [`Event`](event)*.


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # OfflineAudioCompletionEvent](https://webaudio.github.io/web-audio-api/#OfflineAudioCompletionEvent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `OfflineAudioCompletionEvent` | 57 | 79 | 53 | No | 44 | 14 | 57 | 57 | 53 | 43 | 14 | 7.0 |
| `OfflineAudioCompletionEvent` | 14 | 12 | 25 | No | 15 | 6 | ≤37 | 18 | 25 | 14 | 6 | 1.0 |
| `renderedBuffer` | 14 | 12 | 25 | No | 15 | 6 | ≤37 | 18 | 25 | 14 | 6 | 1.0 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/OfflineAudioCompletionEvent>

OfflineAudioContext
===================



The `OfflineAudioContext` interface is an [`AudioContext`](audiocontext) interface representing an audio-processing graph built from linked together [`AudioNode`](audionode)s. In contrast with a standard [`AudioContext`](audiocontext), an `OfflineAudioContext` doesn't render the audio to the device hardware; instead, it generates it, as fast as it can, and outputs the result to an [`AudioBuffer`](audiobuffer).


 EventTarget BaseAudioContext OfflineAudioContext

Constructor
-----------


 [`OfflineAudioContext()`](offlineaudiocontext/offlineaudiocontext)  Creates a new `OfflineAudioContext` instance.

  
Instance properties
-------------------



*Also inherits properties from its parent interface, [`BaseAudioContext`](baseaudiocontext).*

  
[`OfflineAudioContext.length`](offlineaudiocontext/length) Read only 
  An integer representing the size of the buffer in sample-frames.

  

Instance methods
----------------



*Also inherits methods from its parent interface, [`BaseAudioContext`](baseaudiocontext).*

  [`OfflineAudioContext.suspend()`](offlineaudiocontext/suspend)  Schedules a suspension of the time progression in the audio context at the specified time and returns a promise.

  [`OfflineAudioContext.startRendering()`](offlineaudiocontext/startrendering)  Starts rendering the audio, taking into account the current connections and the current scheduled changes. This page covers both the event-based version and the promise-based version.

  

### Deprecated methods



 [`OfflineAudioContext.resume()`](offlineaudiocontext/resume)  Resumes the progression of time in an audio context that has previously been suspended.

    **Note:** The `resume()` method is still available — it is now defined on the [`BaseAudioContext`](baseaudiocontext) interface (see [`AudioContext.resume`](audiocontext/resume)) and thus can be accessed by both the [`AudioContext`](audiocontext) and [`OfflineAudioContext`](offlineaudiocontext) interfaces.

 

Events
------



Listen to these events using [`addEventListener()`](eventtarget/addeventlistener) or by assigning an event listener to the `oneventname` property of this interface:

  [`complete`](offlineaudiocontext/complete_event)  Fired when the rendering of an offline audio context is complete.

  

Examples
--------



In this simple example, we declare both an [`AudioContext`](audiocontext) and an `OfflineAudioContext` object. We use the `AudioContext` to load an audio track via XHR ([`BaseAudioContext.decodeAudioData`](baseaudiocontext/decodeaudiodata)), then the `OfflineAudioContext` to render the audio into an [`AudioBufferSourceNode`](audiobuffersourcenode) and play the track through. After the offline audio graph is set up, you need to render it to an [`AudioBuffer`](audiobuffer) using [`OfflineAudioContext.startRendering`](offlineaudiocontext/startrendering).

 When the `startRendering()` promise resolves, rendering has completed and the output `AudioBuffer` is returned out of the promise.

 At this point we create another audio context, create an [`AudioBufferSourceNode`](audiobuffersourcenode) inside it, and set its buffer to be equal to the promise `AudioBuffer`. This is then played as part of a simple standard audio graph.

  **Note:** For a working example, see our [offline-audio-context-promise](https://mdn.github.io/webaudio-examples/offline-audio-context-promise/) GitHub repo (see the [source code](https://github.com/mdn/webaudio-examples/tree/master/offline-audio-context-promise) too.)

  
```
// define online and offline audio context

const audioCtx = new AudioContext();
const offlineCtx = new OfflineAudioContext(2, 44100 \* 40, 44100);

source = offlineCtx.createBufferSource();

// use XHR to load an audio track, and
// decodeAudioData to decode it and OfflineAudioContext to render it

function getData() {
  request = new XMLHttpRequest();

  request.open("GET", "viper.ogg", true);

  request.responseType = "arraybuffer";

  request.onload = () => {
    const audioData = request.response;

    audioCtx.decodeAudioData(audioData, (buffer) => {
      myBuffer = buffer;
      source.buffer = myBuffer;
      source.connect(offlineCtx.destination);
      source.start();
      //source.loop = true;
      offlineCtx
        .startRendering()
        .then((renderedBuffer) => {
          console.log("Rendering completed successfully");
          const song = audioCtx.createBufferSource();
          song.buffer = renderedBuffer;

          song.connect(audioCtx.destination);

          play.onclick = () => {
            song.start();
          };
        })
        .catch((err) => {
          console.error(`Rendering failed: ${err}`);
          // Note: The promise should reject when startRendering is called a second time on an OfflineAudioContext
        });
    });
  };

  request.send();
}

// Run getData to start the process off

getData();

```


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # OfflineAudioContext](https://webaudio.github.io/web-audio-api/#OfflineAudioContext) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `OfflineAudioContext` | 3525–57 | 12 | 25 | No | 2215–44 | 14.17–14.1 | 374.4–57 | 3525–57 | 25 | 2214–43 | 14.57–14.5 | 3.01.5–7.0 |
| `OfflineAudioContext` | 3525–57 | 12 | 25 | No | 2215–44 | 14.17–14.1 | 374.4–57 | 3525–57 | 25 | 2214–43 | 14.57–14.5 | 3.01.5–7.0 |
| `complete_event` | 25 | 12 | 25 | No | 15 | 7 | 4.4 | 25 | 25 | 14 | 7 | 1.5 |
| `length` | 51 | 14 | 49 | No | 38 | 14.1 | 51 | 51 | 49 | 41 | 14.5 | 5.0 |
| `resume` | 41 | 14 | 40 | No | 28 | 9 | 41 | 41 | 40 | 28 | 9 | 4.0 |
| `startRendering` | 25 | 12 | 25 | No | 15 | 7 | 4.4 | 25 | 25 | 14 | 7 | 1.5 |
| `suspend` | 41 | 14 | NoSee [bug 1265406](https://bugzil.la/1265406). | No | 28 | 9 | 41 | 41 | NoSee [bug 1265406](https://bugzil.la/1265406). | 28 | 9 | 4.0 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/OfflineAudioContext>

OffscreenCanvas
===============



 When using the [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element or the [Canvas API](canvas_api), rendering, animation, and user interaction usually happen on the main execution thread of a web application. The computation relating to canvas animations and rendering can have a significant impact on application performance. 

  The `OffscreenCanvas` interface provides a canvas that can be rendered off screen, decoupling the DOM and the Canvas API so that the [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element is no longer entirely dependent on the DOM. Rendering operations can also be run inside a [worker](web_workers_api) context, allowing you to run some tasks in a separate thread and avoid heavy work on the main thread. 

 `OffscreenCanvas` is a [transferable object](web_workers_api/transferable_objects).


 **Note:** This feature is available in [Web Workers](web_workers_api)

   EventTarget OffscreenCanvas

Constructors
------------


 [`OffscreenCanvas()`](offscreencanvas/offscreencanvas)  `OffscreenCanvas` constructor. Creates a new `OffscreenCanvas` object.

  
Instance properties
-------------------


 [`OffscreenCanvas.height`](offscreencanvas/height)  The height of the offscreen canvas.

  [`OffscreenCanvas.width`](offscreencanvas/width)  The width of the offscreen canvas.

  
Instance methods
----------------


 [`OffscreenCanvas.getContext()`](offscreencanvas/getcontext)  Returns a rendering context for the offscreen canvas.

  [`OffscreenCanvas.convertToBlob()`](offscreencanvas/converttoblob)  Creates a [`Blob`](blob) object representing the image contained in the canvas.

  [`OffscreenCanvas.transferToImageBitmap()`](offscreencanvas/transfertoimagebitmap)  Creates an [`ImageBitmap`](imagebitmap) object from the most recently rendered image of the `OffscreenCanvas`.

  
Examples
--------


### Synchronous display of frames produced by an `OffscreenCanvas`



One way to use the `OffscreenCanvas` API is to use a rendering context that has been obtained from an `OffscreenCanvas` object to generate new frames. Once a new frame has finished rendering in this context, the [`transferToImageBitmap()`](offscreencanvas/transfertoimagebitmap) method can be called to save the most recent rendered image. This method returns an [`ImageBitmap`](imagebitmap) object, which can be used in a variety of Web APIs and also in a second canvas without creating a transfer copy.

 To display the `ImageBitmap`, you can use an [`ImageBitmapRenderingContext`](imagebitmaprenderingcontext) context, which can be created by calling `canvas.getContext("bitmaprenderer")` on a (visible) canvas element. This context only provides functionality to replace the canvas's contents with the given `ImageBitmap`. A call to [`ImageBitmapRenderingContext.transferFromImageBitmap()`](imagebitmaprenderingcontext/transferfromimagebitmap) with the previously rendered and saved `ImageBitmap` from the OffscreenCanvas, will display the `ImageBitmap` on the canvas and transfer its ownership to the canvas. A single `OffscreenCanvas` may transfer frames into an arbitrary number of other `ImageBitmapRenderingContext` objects.

 Given these two [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) elements

 
```
<canvas id="one"></canvas> <canvas id="two"></canvas>

```
 the following code will provide the rendering using `OffscreenCanvas` as described above.

 
```
const one = document.getElementById("one").getContext("bitmaprenderer");
const two = document.getElementById("two").getContext("bitmaprenderer");

const offscreen = new OffscreenCanvas(256, 256);
const gl = offscreen.getContext("webgl");

// Perform some drawing for the first canvas using the gl context
const bitmapOne = offscreen.transferToImageBitmap();
one.transferFromImageBitmap(bitmapOne);

// Perform some more drawing for the second canvas
const bitmapTwo = offscreen.transferToImageBitmap();
two.transferFromImageBitmap(bitmapTwo);

```


### Asynchronous display of frames produced by an `OffscreenCanvas`



Another way to use the `OffscreenCanvas` API, is to call [`transferControlToOffscreen()`](htmlcanvaselement/transfercontroltooffscreen) on a [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) element, either on a [worker](web_workers_api) or the main thread, which will return an `OffscreenCanvas` object from an [`HTMLCanvasElement`](htmlcanvaselement) object from the main thread. Calling [`getContext()`](offscreencanvas/getcontext) will then obtain a rendering context from that `OffscreenCanvas`.

 main.js (main thread code):

 
```
const htmlCanvas = document.getElementById("canvas");
const offscreen = htmlCanvas.transferControlToOffscreen();

const worker = new Worker("offscreencanvas.js");
worker.postMessage({ canvas: offscreen }, [offscreen]);

```
 offscreencanvas.js (worker code):

 
```
onmessage = (evt) => {
  const canvas = evt.data.canvas;
  const gl = canvas.getContext("webgl");

  // Perform some drawing using the gl context
};

```
 You can also use requestAnimationFrame in workers

 
```
onmessage = (evt) => {
  const canvas = evt.data.canvas;
  const gl = canvas.getContext("webgl");

  function render(time) {
    // Perform some drawing using the gl context
    requestAnimationFrame(render);
  }
  requestAnimationFrame(render);
};

```
 For a full example, see our [OffscreenCanvas worker example](https://github.com/mdn/dom-examples/tree/main/web-workers/offscreen-canvas-worker) ([run OffscreenCanvas worker](https://mdn.github.io/dom-examples/web-workers/offscreen-canvas-worker/)).



Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-offscreencanvas-interface](https://html.spec.whatwg.org/multipage/canvas.html#the-offscreencanvas-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `OffscreenCanvas` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `OffscreenCanvas` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `contextlost_event` | 99 | 99 | 105 | No | 85 | No | 99 | 99 | 105 | 68 | No | 18.0 |
| `contextrestored_event` | 99 | 99 | 105 | No | 85 | No | 99 | 99 | 105 | 68 | No | 18.0 |
| `convertToBlob` | 69 | 79 | 105105 | No | 56 | 16.4 | 69 | 69 | 105105 | 48 | 16.4 | 10.0 |
| `getContext` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `height` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `transferToImageBitmap` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |
| `width` | 69 | 79 | 105 | No | 56 | 16.4 | 69 | 69 | 105 | 48 | 16.4 | 10.0 |


See also
--------


* [WebGL Off the Main Thread – Mozilla Hacks](https://hacks.mozilla.org/2016/01/webgl-off-the-main-thread/)
* [`CanvasRenderingContext2D`](canvasrenderingcontext2d)
* [`OffscreenCanvasRenderingContext2D`](offscreencanvasrenderingcontext2d)
* [`ImageBitmap`](imagebitmap)
* [`ImageBitmapRenderingContext`](imagebitmaprenderingcontext)
* [`HTMLCanvasElement.transferControlToOffscreen()`](htmlcanvaselement/transfercontroltooffscreen)
* `WebGLRenderingContext.commit()`


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas>

OrientationSensor
=================



The `OrientationSensor` interface of the [Sensor APIs](sensor_apis) is the base class for orientation sensors. This interface cannot be used directly. Instead it provides properties and methods accessed by interfaces that inherit from it.

 This feature may be blocked by a [Permissions Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy) set on your server.


 EventTarget Sensor OrientationSensor

Interfaces based on OrientationSensor
-------------------------------------



Below is a list of interfaces based on the OrientationSensor interface.

 * [`AbsoluteOrientationSensor`](absoluteorientationsensor)
* [`RelativeOrientationSensor`](relativeorientationsensor)



Instance properties
-------------------


 [`OrientationSensor.quaternion`](orientationsensor/quaternion)  Returns a four element [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) whose elements contain the components of the unit quaternion representing the device's orientation.

  
Instance methods
----------------


 [`OrientationSensor.populateMatrix()`](orientationsensor/populatematrix)  Populates the given object with the rotation matrix based on the latest sensor reading. The rotation matrix is shown below.

  
Examples
--------


### Basic Example



The following example, which is loosely based on [Intel's Orientation Phone demo](https://intel.github.io/generic-sensor-demos/orientation-phone/), instantiates an `AbsoluteOrientationSensor` with a frequency of 60 times a second. On each reading it uses [`OrientationSensor.quaternion`](orientationsensor/quaternion) to rotate a visual model of a phone.

 
```
const options = { frequency: 60, referenceFrame: "device" };
const sensor = new AbsoluteOrientationSensor(options);

sensor.addEventListener("reading", () => {
  // model is a Three.js object instantiated elsewhere.
  model.quaternion.fromArray(sensor.quaternion).inverse();
});
sensor.addEventListener("error", (error) => {
  if (event.error.name === "NotReadableError") {
    console.log("Sensor is not available.");
  }
});
sensor.start();

```


### Permissions Example



Using orientation sensors requires requesting permissions for multiple device sensors. Because the [`Permissions`](permissions) interface uses promises, a good way to request permissions is to use [`Promise.all`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all).

 
```
const sensor = new AbsoluteOrientationSensor();
Promise.all([
  navigator.permissions.query({ name: "accelerometer" }),
  navigator.permissions.query({ name: "magnetometer" }),
  navigator.permissions.query({ name: "gyroscope" }),
]).then((results) => {
  if (results.every((result) => result.state === "granted")) {
    sensor.start();
    // …
  } else {
    console.log("No permissions to use AbsoluteOrientationSensor.");
  }
});

```


Specifications
--------------




| Specification |
| --- |
| [Orientation Sensor # orientationsensor-interface](https://w3c.github.io/orientation-sensor/#orientationsensor-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `OrientationSensor` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |
| `populateMatrix` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |
| `quaternion` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/OrientationSensor>

OscillatorNode
==============



The `OscillatorNode` interface represents a periodic waveform, such as a sine wave. It is an [`AudioScheduledSourceNode`](audioscheduledsourcenode) audio-processing module that causes a specified frequency of a given wave to be created—in effect, a constant tone.


 EventTarget AudioNode AudioScheduledSourceNode OscillatorNode 

|  |  |
| --- | --- |
| Number of inputs | `0` |
| Number of outputs | `1` |
| Channel count mode | `max` |
| Channel count | `2` (not used in the default count mode) |
| Channel interpretation | `speakers` |



Constructor
-----------


 [`OscillatorNode()`](oscillatornode/oscillatornode)  Creates a new instance of an `OscillatorNode` object, optionally providing an object specifying default values for the node's [properties](#instance_properties). As an alternative, you can use the [`BaseAudioContext.createOscillator()`](baseaudiocontext/createoscillator) factory method; see [Creating an AudioNode](audionode#creating_an_audionode).

  
Instance properties
-------------------



*Inherits properties from its parent, [`AudioScheduledSourceNode`](audioscheduledsourcenode), and adds the following properties:*

  [`OscillatorNode.frequency`](oscillatornode/frequency)  An [a-rate](audioparam#a-rate) [`AudioParam`](audioparam) representing the frequency of oscillation in hertz (though the `AudioParam` returned is read-only, the value it represents is not). The default value is 440 Hz (a standard middle-A note).

  [`OscillatorNode.detune`](oscillatornode/detune)  An [a-rate](audioparam#a-rate) [`AudioParam`](audioparam) representing detuning of oscillation in cents (though the `AudioParam` returned is read-only, the value it represents is not). The default value is 0.

  [`OscillatorNode.type`](oscillatornode/type)  A string which specifies the shape of waveform to play; this can be one of a number of standard values, or `custom` to use a [`PeriodicWave`](periodicwave) to describe a custom waveform. Different waves will produce different tones. Standard values are `"sine"`, `"square"`, `"sawtooth"`, `"triangle"` and `"custom"`. The default is `"sine"`.

  

### Event handlers


 [`OscillatorNode.onended`](audioscheduledsourcenode/ended_event)  Sets the event handler for the [`ended`](audioscheduledsourcenode/ended_event) event, which fires when the tone has stopped playing.

  
Instance methods
----------------



*Inherits methods from its parent, [`AudioScheduledSourceNode`](audioscheduledsourcenode), and adds the following:*

  [`OscillatorNode.setPeriodicWave()`](oscillatornode/setperiodicwave)  Sets a [`PeriodicWave`](periodicwave) which describes a periodic waveform to be used instead of one of the standard waveforms; calling this sets the `type` to `custom`.

  [`OscillatorNode.start()`](audioscheduledsourcenode/start)  Specifies the exact time to start playing the tone.

  [`OscillatorNode.stop()`](audioscheduledsourcenode/stop)  Specifies the time to stop playing the tone.

  

Examples
--------



The following example shows basic usage of an [`AudioContext`](audiocontext) to create an oscillator node and to start playing a tone on it. For an applied example, check out our [Violent Theremin demo](https://mdn.github.io/webaudio-examples/violent-theremin/) ([see app.js](https://github.com/mdn/webaudio-examples/blob/master/violent-theremin/scripts/app.js) for relevant code).

 
```
// create web audio api context
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();

// create Oscillator node
const oscillator = audioCtx.createOscillator();

oscillator.type = "square";
oscillator.frequency.setValueAtTime(440, audioCtx.currentTime); // value in hertz
oscillator.connect(audioCtx.destination);
oscillator.start();

```


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # OscillatorNode](https://webaudio.github.io/web-audio-api/#OscillatorNode) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `OscillatorNode` | 55 | 79 | 53 | No | 42 | 14.1 | 55 | 55 | 53 | 42 | 14.5 | 6.0 |
| `OscillatorNode` | 20 | 12 | 25 | No | 15 | 6 | 4.4 | 25 | 25 | 14 | 6 | 1.5 |
| `detune` | 20 | 12 | 25 | No | 15 | 6 | 4.4 | 25 | 25 | 14 | 6 | 1.5 |
| `frequency` | 20 | 12 | 25 | No | 15 | 6 | 4.4 | 25 | 25 | 14 | 6 | 1.5 |
| `setPeriodicWave` | 30 | 12 | 25 | No | 17 | 8 | ≤37 | 30 | 25 | 18 | 8 | 2.0 |
| `type` | 20 | 12 | 25 | No | 15 | 6 | 4.4 | 25 | 25 | 14 | 6 | 1.5 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/OscillatorNode>

PaintWorkletGlobalScope
=======================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `PaintWorkletGlobalScope` interface of the [CSS Painting API](css_painting_api) represents the global object available inside a paint [`Worklet`](worklet).



Privacy concerns
----------------



To avoid leaking visited links, this feature is currently disabled in Chrome-based browsers for [`<a>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a) elements with an [`href`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#href) attribute, and for children of such elements. For details, see the following:

 * The CSS Painting API [Privacy Considerations section](https://drafts.css-houdini.org/css-paint-api/#privacy-considerations)
* The CSS Painting API spec issue ["CSS Paint API leaks browsing history"](https://github.com/w3c/css-houdini-drafts/issues/791)



Instance properties
-------------------



*This interface inherits methods from [`WorkletGlobalScope`](workletglobalscope).*

  
[`PaintWorkletGlobalScope.devicePixelRatio`](paintworkletglobalscope/devicepixelratio)  Experimental 
  Returns the current device's ratio of physical pixels to logical pixels.

  

Instance methods
----------------



*This interface inherits methods from [`WorkletGlobalScope`](workletglobalscope).*

  
[`PaintWorkletGlobalScope.registerPaint()`](paintworkletglobalscope/registerpaint)  Experimental 
  Registers a class to programmatically generate an image where a CSS property expects a file.

  

### Event


None.


Examples
--------


The following three examples go together to show creating, loading, and using a paint `Worklet`.


### Create a paint worklet



The following shows an example worklet module. This should be in a separate js file. Note that `registerPaint()` is called without a reference to a paint `Worklet`.

 
```
class CheckerboardPainter {
  paint(ctx, geom, properties) {
    // The global object here is a PaintWorkletGlobalScope
    // Methods and properties can be accessed directly
    // as global features or prefixed using self
    const dpr = self.devicePixelRatio;

    // Use `ctx` as if it was a normal canvas
    const colors = ["red", "green", "blue"];
    const size = 32;
    for (let y = 0; y < geom.height / size; y++) {
      for (let x = 0; x < geom.width / size; x++) {
        const color = colors[(x + y) % colors.length];
        ctx.beginPath();
        ctx.fillStyle = color;
        ctx.rect(x \* size, y \* size, size, size);
        ctx.fill();
      }
    }
  }
}

// Register our class under a specific name
registerPaint("checkerboard", CheckerboardPainter);

```


### Load a paint worklet



The following example demonstrates loading the above worklet from its js file and does so by feature detection.

 
```
if ("paintWorklet" in CSS) {
  CSS.paintWorklet.addModule("checkerboard.js");
}

```


### Use a paint worklet



This example shows how to use a paint `Worklet` in a stylesheet, including the simplest way to provide a fallback if `CSS.paintWorklet` isn't supported.

 
```
<style>
 textarea {
 background-image: url(checkerboard);
 background-image: paint(checkerboard);
 }
</style>
<textarea></textarea>

```
 You can also use the [`@supports`](https://developer.mozilla.org/en-US/docs/Web/CSS/@supports) at-rule.

 
```
@supports (background: paint(id)) {
  background-image: paint(checkerboard);
}

```


Specifications
--------------




| Specification |
| --- |
| [CSS Painting API Level 1 # paintworkletglobalscope](https://drafts.css-houdini.org/css-paint-api/#paintworkletglobalscope) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PaintWorkletGlobalScope` | 65 | 79 | No | No | 52 | No | 65 | 65 | No | 47 | No | 9.0 |
| `devicePixelRatio` | 65 | 79 | No | No | 52 | No | 65 | 65 | No | 47 | No | 9.0 |
| `registerPaint` | 65 | 79 | No | No | 52 | No | 65 | 65 | No | 47 | No | 9.0 |


See also
--------


* [CSS Painting API](css_painting_api)
* [Houdini APIs](https://developer.mozilla.org/en-US/docs/Web/Guide/Houdini)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PaintWorkletGlobalScope>

PannerNode
==========



The `PannerNode` interface defines an audio-processing object that represents the location, direction, and behavior of an audio source signal in a simulated physical space. This [`AudioNode`](audionode) uses right-hand Cartesian coordinates to describe the source's *position* as a vector and its *orientation* as a 3D directional cone.

 A `PannerNode` always has exactly one input and one output: the input can be *mono* or *stereo* but the output is always *stereo* (2 channels); you can't have panning effects without at least two audio channels!

  ![The PannerNode defines a spatial position and direction for a given signal.] 


 EventTarget AudioNode PannerNode 

|  |  |
| --- | --- |
| Number of inputs | `1` |
| Number of outputs | `1` |
| Channel count mode | `"clamped-max"` |
| Channel count | `2` |
| Channel interpretation | `"speakers"` |



Constructor
-----------


 [`PannerNode()`](pannernode/pannernode)  Creates a new `PannerNode` object instance.

  
Instance properties
-------------------



*Inherits properties from its parent, [`AudioNode`](audionode)*.

  **Note:** The orientation and position value are set and retrieved using different syntaxes, since they're stored as [`AudioParam`](audioparam) values. Retrieval is done by accessing, for example, `PannerNode.positionX`. While setting the same property is done with `PannerNode.positionX.value`. This is why these values are not marked read only, which is how they appear in the WebIDL.

   [`PannerNode.coneInnerAngle`](pannernode/coneinnerangle)  A double value describing the angle, in degrees, of a cone inside of which there will be no volume reduction.

  [`PannerNode.coneOuterAngle`](pannernode/coneouterangle)  A double value describing the angle, in degrees, of a cone outside of which the volume will be reduced by a constant value, defined by the `coneOuterGain` property.

  [`PannerNode.coneOuterGain`](pannernode/coneoutergain)  A double value describing the amount of volume reduction outside the cone defined by the `coneOuterAngle` attribute. Its default value is `0`, meaning that no sound can be heard.

  [`PannerNode.distanceModel`](pannernode/distancemodel)  An enumerated value determining which algorithm to use to reduce the volume of the audio source as it moves away from the listener. Possible values are `"linear"`, `"inverse"` and `"exponential"`. The default value is `"inverse"`.

  [`PannerNode.maxDistance`](pannernode/maxdistance)  A double value representing the maximum distance between the audio source and the listener, after which the volume is not reduced any further.

  [`PannerNode.orientationX`](pannernode/orientationx)  Represents the horizontal position of the audio source's vector in a right-hand Cartesian coordinate system. While this [`AudioParam`](audioparam) cannot be directly changed, its value can be altered using its [`value`](audioparam/value) property. The default is value is 1.

  [`PannerNode.orientationY`](pannernode/orientationy)  Represents the vertical position of the audio source's vector in a right-hand Cartesian coordinate system. The default is 0. While this [`AudioParam`](audioparam) cannot be directly changed, its value can be altered using its [`value`](audioparam/value) property. The default is value is 0.

  [`PannerNode.orientationZ`](pannernode/orientationz)  Represents the longitudinal (back and forth) position of the audio source's vector in a right-hand Cartesian coordinate system. The default is 0. While this [`AudioParam`](audioparam) cannot be directly changed, its value can be altered using its [`value`](audioparam/value) property. The default is value is 0.

  [`PannerNode.panningModel`](pannernode/panningmodel)  An enumerated value determining which spatialization algorithm to use to position the audio in 3D space.

  [`PannerNode.positionX`](pannernode/positionx)  Represents the horizontal position of the audio in a right-hand Cartesian coordinate system. The default is 0. While this [`AudioParam`](audioparam) cannot be directly changed, its value can be altered using its [`value`](audioparam/value) property. The default is value is 0.

  [`PannerNode.positionY`](pannernode/positiony)  Represents the vertical position of the audio in a right-hand Cartesian coordinate system. The default is 0. While this [`AudioParam`](audioparam) cannot be directly changed, its value can be altered using its [`value`](audioparam/value) property. The default is value is 0.

  [`PannerNode.positionZ`](pannernode/positionz)  Represents the longitudinal (back and forth) position of the audio in a right-hand Cartesian coordinate system. The default is 0. While this [`AudioParam`](audioparam) cannot be directly changed, its value can be altered using its [`value`](audioparam/value) property. The default is value is 0.

  [`PannerNode.refDistance`](pannernode/refdistance)  A double value representing the reference distance for reducing volume as the audio source moves further from the listener. For distances greater than this the volume will be reduced based on `rolloffFactor` and `distanceModel`.

  [`PannerNode.rolloffFactor`](pannernode/rollofffactor)  A double value describing how quickly the volume is reduced as the source moves away from the listener. This value is used by all distance models.

  

Instance methods
----------------



*Inherits methods from its parent, [`AudioNode`](audionode)*.

  
[`PannerNode.setPosition()`](pannernode/setposition)  Deprecated 
  Defines the position of the audio source relative to the listener (represented by an [`AudioListener`](audiolistener) object stored in the [`BaseAudioContext.listener`](baseaudiocontext/listener) attribute.)

  
[`PannerNode.setOrientation()`](pannernode/setorientation)  Deprecated 
  Defines the direction the audio source is playing in.

  
[`PannerNode.setVelocity()`](pannernode/setvelocity)  Deprecated 
  Defines the velocity vector of the audio source — how fast it is moving and in what direction. In a previous version of the specification, the [`PannerNode`](pannernode) had a velocity vector that could pitch up or down [`AudioBufferSourceNode`](audiobuffersourcenode) objects connected downstream. This feature was not clearly specified and had a number of issues, so it was removed from the specification.

  

Examples
--------


See [`BaseAudioContext.createPanner()`](baseaudiocontext/createpanner#examples) for example code.


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # PannerNode](https://webaudio.github.io/web-audio-api/#PannerNode) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PannerNode` | 55 | 79 | 53 | No | 42 | 14.1 | 55 | 55 | 53 | 42 | 14.5 | 6.0 |
| `PannerNode` | 14 | 12 | 25 | No | 15 | 14.16–14.1 | 4.4.3 | 18 | 25 | 14 | 14.56–14.5 | 1.0 |
| `coneInnerAngle` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `coneOuterAngle` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `coneOuterGain` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `distanceModel` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `maxDistance` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `orientationX` | 52 | 79 | 50 | No | 39 | 14.1 | 52 | 52 | 50 | 41 | 14.5 | 6.0 |
| `orientationY` | 52 | 79 | 50 | No | 39 | 14.1 | 52 | 52 | 50 | 41 | 14.5 | 6.0 |
| `orientationZ` | 52 | 79 | 50 | No | 39 | 14.1 | 52 | 52 | 50 | 41 | 14.5 | 6.0 |
| `panningModel` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `positionX` | 52 | 79 | 50 | No | 39 | 14.1 | 52 | 52 | 50 | 41 | 14.5 | 6.0 |
| `positionY` | 52 | 79 | 50 | No | 39 | 14.1 | 52 | 52 | 50 | 41 | 14.5 | 6.0 |
| `positionZ` | 52 | 79 | 50 | No | 39 | 14.1 | 52 | 52 | 50 | 41 | 14.5 | 6.0 |
| `refDistance` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `rolloffFactor` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `setOrientation` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `setPosition` | 14 | 12 | 25 | No | 15 | 6 | 4.4.3 | 18 | 25 | 14 | 6 | 1.0 |
| `setVelocity` | 14–56 | 12–79 | 25–63 | No | 15–43 | 6–14.1 | ≤37–56 | 18–56 | 25–63 | 14–43 | 6–14.5 | 1.0–6.0 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PannerNode>

PasswordCredential
==================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.


**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The interface of the [Credential Management API](credential_management_api) provides information about a username/password pair. In supporting browsers an instance of this class may be passed in the `credential` member of the `init` object for global [`fetch()`](fetch).

  **Note:** This interface is restricted to top-level contexts and cannot be used from an [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe).

 
 Credential PasswordCredential

Constructor
-----------


 
[`PasswordCredential()`](passwordcredential/passwordcredential) Secure context  Experimental 
  Creates a new `PasswordCredential` object.

  
Instance properties
-------------------



*Inherits properties from its ancestor, [`Credential`](credential).*

  
[`PasswordCredential.iconURL`](passwordcredential/iconurl) Read only  Secure context  Experimental 
  A string containing a URL pointing to an image for an icon. This image is intended for display in a credential chooser. The URL must be accessible without authentication.

  
[`PasswordCredential.name`](passwordcredential/name) Read only  Secure context  Experimental 
  A human-readable string that provides public name for display in a credential chooser.

  
[`PasswordCredential.password`](passwordcredential/password) Read only  Secure context  Experimental 
  A string containing the password of the credential.

  

### Event handlers


None.


Instance methods
----------------


None.


Examples
--------



```
const cred = new PasswordCredential({
  id,
  password,
  name,
  iconURL,
});

navigator.credentials.store(cred).then(() => {
  // Do something else.
});

```

Specifications
--------------




| Specification |
| --- |
| [Credential Management Level 1 # passwordcredential-interface](https://w3c.github.io/webappsec-credential-management/#passwordcredential-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PasswordCredential` | 51 | 79 | No | No | 38 | No | 51 | 51 | No | 41 | No | 5.0 |
| `PasswordCredential` | 51 | 79 | No | No | 38 | No | 51 | 51 | No | 41 | No | 5.0 |
| `iconURL` | 51 | 79 | No | No | 38 | No | 51 | 51 | No | 41 | No | 5.0 |
| `name` | 51 | 79 | No | No | 38 | No | 51 | 51 | No | 41 | No | 5.0 |
| `password` | 60 | 79 | No | No | 47 | No | 60 | 60 | No | 44 | No | 8.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PasswordCredential>

Path2D
======


The `Path2D` interface of the Canvas 2D API is used to declare a path that can then be used on a [`CanvasRenderingContext2D`](canvasrenderingcontext2d) object. The [path methods](canvasrenderingcontext2d#paths) of the `CanvasRenderingContext2D` interface are also present on this interface, which gives you the convenience of being able to retain and replay your path whenever desired.


Constructors
------------


 [`Path2D()`](path2d/path2d)  `Path2D` constructor. Creates a new `Path2D` object.

  
Instance methods
----------------


 [`Path2D.addPath()`](path2d/addpath)  Adds a path to the current path.

  [`Path2D.closePath()`](canvasrenderingcontext2d/closepath)  Causes the point of the pen to move back to the start of the current sub-path. It tries to draw a straight line from the current point to the start. If the shape has already been closed or has only one point, this function does nothing.

  [`Path2D.moveTo()`](canvasrenderingcontext2d/moveto)  Moves the starting point of a new sub-path to the (`x, y`) coordinates.

  [`Path2D.lineTo()`](canvasrenderingcontext2d/lineto)  Connects the last point in the subpath to the (`x, y`) coordinates with a straight line.

  [`Path2D.bezierCurveTo()`](canvasrenderingcontext2d/beziercurveto)  Adds a cubic Bézier curve to the path. It requires three points. The first two points are control points and the third one is the end point. The starting point is the last point in the current path, which can be changed using `moveTo()` before creating the Bézier curve.

  [`Path2D.quadraticCurveTo()`](canvasrenderingcontext2d/quadraticcurveto)  Adds a quadratic Bézier curve to the current path.

  [`Path2D.arc()`](canvasrenderingcontext2d/arc)  Adds an arc to the path which is centered at (`x, y`) position with radius `r` starting at `startAngle` and ending at `endAngle` going in the given direction by `counterclockwise` (defaulting to clockwise).

  [`Path2D.arcTo()`](canvasrenderingcontext2d/arcto)  Adds a circular arc to the path with the given control points and radius, connected to the previous point by a straight line.

  [`Path2D.ellipse()`](canvasrenderingcontext2d/ellipse)  Adds an elliptical arc to the path which is centered at (`x, y`) position with the radii `radiusX` and `radiusY` starting at `startAngle` and ending at `endAngle` going in the given direction by `counterclockwise` (defaulting to clockwise).

  [`Path2D.rect()`](canvasrenderingcontext2d/rect)  Creates a path for a rectangle at position (`x, y`) with a size that is determined by `width` and `height`.

  [`Path2D.roundRect()`](canvasrenderingcontext2d/roundrect)  Creates a path for a rounded rectangle at position (`x, y`) with a size that is determined by `width` and `height` and the radii of the circular arc to be used for the corners of the rectangle is determined by `radii`.

  
Specifications
--------------




| Specification |
| --- |
| [HTML Standard # path2d-objects](https://html.spec.whatwg.org/multipage/canvas.html#path2d-objects) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Path2D` | 36 | 14Before Edge 79, the constructor for `Path2D` objects does not support invocation with a string consisting of SVG path data. | 31 | No | 23 | 8 | 37 | 36 | 31 | 24 | 8 | 3.0 |
| `Path2D` | 36 | 14 | 31 | No | 23 | 8 | 37 | 36 | 31 | 24 | 8 | 3.0 |
| `addPath` | 68 | 79 | 34 | No | 55 | 9 | 68 | 68 | 34 | 48 | 9 | 10.0 |
| `arc` | 36 | 14 | 31 | No | 23 | 8 | 37 | 36 | 31 | 24 | 8 | 3.0 |
| `arcTo` | 36 | 14 | 31 | No | 23 | 8 | 37 | 36 | 31 | 24 | 8 | 3.0 |
| `bezierCurveTo` | 36 | 14 | 31 | No | 23 | 8 | 37 | 36 | 31 | 24 | 8 | 3.0 |
| `closePath` | 36 | 14 | 31 | No | 23 | 8 | 37 | 36 | 31 | 24 | 8 | 3.0 |
| `ellipse` | 36 | 14 | 48 | No | 23 | 9 | 37 | 36 | 48 | 24 | 9 | 3.0 |
| `lineTo` | 36 | 14 | 31 | No | 23 | 8 | 37 | 36 | 31 | 24 | 8 | 3.0 |
| `moveTo` | 36 | 14 | 31 | No | 23 | 8 | 37 | 36 | 31 | 24 | 8 | 3.0 |
| `quadraticCurveTo` | 36 | 14 | 31 | No | 23 | 8 | 37 | 36 | 31 | 24 | 8 | 3.0 |
| `rect` | 36 | 14 | 31 | No | 23 | 8 | 37 | 36 | 31 | 24 | 8 | 3.0 |
| `roundRect` | 99 | 99 | 112 | No | 85 | 16 | 99 | 99 | 112 | 68 | 16 | 18.0 |


See also
--------


* [`CanvasRenderingContext2D`](canvasrenderingcontext2d)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Path2D>

PaymentAddress
==============



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.


**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The `PaymentAddress` interface of the [Payment Request API](payment_request_api) is used to store shipping or payment address information.

 It may be useful to refer to the Universal Postal Union web site's [Addressing S42 standard](https://www.upu.int/en/Postal-Solutions/Programmes-Services/Addressing-Solutions#addressing-s42-standard) materials, which provide information about international standards for postal addresses.



Instance properties
-------------------



 
[`PaymentAddress.addressLine`](paymentaddress/addressline) Read only   Deprecated   Non-standard 
  An array of strings providing each line of the address not included among the other properties. The exact size and content varies by country or location and can include, for example, a street name, house number, apartment number, rural delivery route, descriptive instructions, or post office box number.

  
[`PaymentAddress.country`](paymentaddress/country) Read only   Deprecated   Non-standard 
  A string specifying the country in which the address is located, using the [ISO-3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) standard. The string is always given in its canonical upper-case form. Some examples of valid `country` values: `"US"`, `"GB"`, `"CN"`, or `"JP"`.

  
[`PaymentAddress.city`](paymentaddress/city) Read only   Deprecated   Non-standard 
  A string which contains the city or town portion of the address.

  
[`PaymentAddress.dependentLocality`](paymentaddress/dependentlocality) Read only   Deprecated   Non-standard 
  A string giving the dependent locality or sublocality within a city, for example, a neighborhood, borough, district, or UK dependent locality.

  
[`PaymentAddress.organization`](paymentaddress/organization) Read only   Deprecated   Non-standard 
  A string specifying the name of the organization, firm, company, or institution at the payment address.

  
[`PaymentAddress.phone`](paymentaddress/phone) Read only   Deprecated   Non-standard 
  A string specifying the telephone number of the recipient or contact person.

  
[`PaymentAddress.postalCode`](paymentaddress/postalcode) Read only   Deprecated   Non-standard 
  A string specifying a code used by a jurisdiction for mail routing, for example, the ZIP code in the United States or the PIN code in India.

  
[`PaymentAddress.recipient`](paymentaddress/recipient) Read only   Deprecated   Non-standard 
  A string giving the name of the recipient, purchaser, or contact person at the payment address.

  
[`PaymentAddress.region`](paymentaddress/region) Read only   Deprecated   Non-standard 
  A string containing the top level administrative subdivision of the country, for example a state, province, oblast, or prefecture.

  
[`PaymentAddress.sortingCode`](paymentaddress/sortingcode) Read only   Deprecated   Non-standard 
  A string providing a postal sorting code such as is used in France.

    **Note:** Properties for which values were not specified contain empty strings.

 

Instance methods
----------------


 
[`PaymentAddress.toJSON()`](paymentaddress/tojson)  Deprecated   Non-standard 
  A standard serializer that returns a JSON representation of the `PaymentAddress` object's properties.

  
Examples
--------



In the following example, the [`PaymentRequest()`](paymentrequest/paymentrequest) constructor is used to create a new payment request, which takes three objects as parameters — one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object containing further options.

 The first of these three (`supportedInstruments` in the example below) contains a `data` property that has to conform to the structure defined by the payment method.

 
```
const supportedInstruments = [
  {
    supportedMethods: "https://example.com/pay",
  },
];

const details = {
  total: { label: "Donation", amount: { currency: "USD", value: "65.00" } },
  displayItems: [
    {
      label: "Original donation amount",
      amount: { currency: "USD", value: "65.00" },
    },
  ],
  shippingOptions: [
    {
      id: "standard",
      label: "Standard shipping",
      amount: { currency: "USD", value: "0.00" },
      selected: true,
    },
  ],
};

const options = { requestShipping: true };

async function doPaymentRequest() {
  const request = new PaymentRequest(supportedInstruments, details, options);
  // Add event listeners here.
  // Call show() to trigger the browser's payment flow.
  const response = await request.show();
  // Process payment.
  const json = response.toJSON();
  const httpResponse = await fetch("/pay/", { method: "POST", body: json });
  const result = httpResponse.ok ? "success" : "failure";

  await response.complete(result);
}
doPaymentRequest();

```
 Once the payment flow has been triggered using [`PaymentRequest.show()`](paymentrequest/show) and the promise resolves successfully, the [`PaymentResponse`](paymentresponse) object available from the fulfilled promise (`instrumentResponse` above) will have a [`PaymentResponse.details`](paymentresponse/details) property containing response details. This has to conform to the structure defined by the payment method provider.



Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PaymentAddress` | 60 | 15 | No | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `addressLine` | 60 | 15 | No | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `city` | 60 | 15 | No | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `country` | 60 | 15 | No | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `dependentLocality` | 60 | 15 | No | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `organization` | 60 | 15 | No | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `phone` | 60 | 15 | No | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `postalCode` | 60 | 15 | No | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `recipient` | 60 | 15 | No | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `region` | 60 | 15 | No | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `sortingCode` | 60 | 15 | No | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `toJSON` | 60 | 15 | No | No | 47 | 11.1 | No | 55 | No | 44 | 11.3 | 6.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PaymentAddress>

PaymentManager
==============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `PaymentManager` interface of the [Payment Handler API](payment_handler_api) is used to manage various aspects of payment app functionality.

 It is accessed via the [`ServiceWorkerRegistration.paymentManager`](serviceworkerregistration/paymentmanager) property.



Instance properties
-------------------


 
[`userHint`](paymentmanager/userhint)  Experimental 
  Provides a hint for the browser to display along with the payment app's name and icon in the Payment Handler UI.

  
Instance methods
----------------


 
[`enableDelegations()`](paymentmanager/enabledelegations)  Experimental   Non-standard 
  Delegates responsibility for providing various parts of the required payment information to the payment app rather than collecting it from the browser (for example, via autofill).

  
Examples
--------



```
navigator.serviceWorker.register("serviceworker.js").then((registration) => {
  registration.paymentManager.userHint = "Card number should be 16 digits";

  registration.paymentManager
    .enableDelegations(["shippingAddress", "payerName"])
    .then(() => {
      // ...
    });

  // ...
});

```

Specifications
--------------




| Specification |
| --- |
| [Payment Handler API # paymentmanager-interface](https://w3c.github.io/payment-handler/#paymentmanager-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PaymentManager` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |
| `enableDelegations` | 80 | 80 | No | No | 67 | No | No | 80 | No | 57 | No | 13.0 |
| `instruments` | 70–111 | 79–111 | No | No | 57–97 | No | No | 70–111 | No | 49 | No | 10.0 |
| `userHint` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |


See also
--------


* [Payment Handler API](payment_handler_api)
* [Web-based payment apps overview](https://web.dev/web-based-payment-apps-overview/)
* [Setting up a payment method](https://web.dev/setting-up-a-payment-method/)
* [Life of a payment transaction](https://web.dev/life-of-a-payment-transaction/)
* [Using the Payment Request API](payment_request_api/using_the_payment_request_api)
* [Payment processing concepts](payment_request_api/concepts)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PaymentManager>

PaymentMethodChangeEvent
========================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `PaymentMethodChangeEvent` interface of the [Payment Request API](payment_request_api) describes the [`paymentmethodchange`](paymentrequest/paymentmethodchange_event) event which is fired by some payment handlers when the user switches payment instruments (e.g., a user selects a "store" card to make a purchase while using Apple Pay).


 Event PaymentRequestUpdateEvent PaymentMethodChangeEvent

Constructor
-----------


 [`PaymentMethodChangeEvent()`](paymentmethodchangeevent/paymentmethodchangeevent)  Creates and returns a new `PaymentMethodChangeEvent` object, optionally initialized with values taken from a given `PaymentMethodChangeEventInit` dictionary.

  
Instance properties
-------------------



*In addition to the properties below, this interface includes properties inherited from [`PaymentRequestUpdateEvent`](paymentrequestupdateevent).*

  
[`methodDetails`](paymentmethodchangeevent/methoddetails) Read only  Secure context
  An object containing payment method-specific data useful when handling a payment method change. If no such information is available, this value is `null`.

  
[`methodName`](paymentmethodchangeevent/methodname) Read only  Secure context
  A string containing the payment method identifier, a string which uniquely identifies a particular payment method. This identifier is usually a URL used during the payment process, but may be a standardized non-URL string as well, such as `basic-card`. The default value is the empty string, `""`.

  

Instance methods
----------------


*This interface includes methods inherited from [`PaymentRequestUpdateEvent`](paymentrequestupdateevent).*


Specifications
--------------




| Specification |
| --- |
| [Payment Request API 1.1 # paymentmethodchangeevent-interface](https://w3c.github.io/payment-request/#paymentmethodchangeevent-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PaymentMethodChangeEvent` | 76 | 79 | 55 | No | 63 | 12.1 | No | 76 | No | 54 | 12.2 | 12.0 |
| `PaymentMethodChangeEvent` | 76 | 79 | 55 | No | 63 | 12.1 | No | 76 | No | 54 | 12.2 | 12.0 |
| `methodDetails` | 76 | 79 | 55 | No | 63 | 12.1 | No | 76 | No | 54 | 12.2 | 12.0 |
| `methodName` | 76 | 79 | 55 | No | 63 | 12.1 | No | 76 | No | 54 | 12.2 | 12.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PaymentMethodChangeEvent>

OverconstrainedError
====================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `OverconstrainedError` interface of the [Media Capture and Streams API](media_capture_and_streams_api) indicates that the set of desired capabilities for the current [`MediaStreamTrack`](mediastreamtrack) cannot currently be met. When this event is thrown on a MediaStreamTrack, it is muted until either the current constraints can be established or until satisfiable constraints are applied.


 DOMException OverconstrainedError

Constructor
-----------


 [`OverconstrainedError()`](overconstrainederror/overconstrainederror)  Creates a new `OverconstrainedError` object.

  
Instance properties
-------------------


 
[`OverconstrainedError.constraint`](overconstrainederror/constraint) Read only 
  Returns the constraint that was supplied in the constructor, meaning the constraint that was not satisfied.

  
[`DOMException.message`](domexception/message) Read only 
  Returns the text supplied in the constructor.

  
[`DOMException.name`](domexception/name) Read only 
  Will always return `OverconstrainedError`.

  
Instance methods
----------------


None.


Specifications
--------------




| Specification |
| --- |
| [Media Capture and Streams # overconstrainederror-interface](https://w3c.github.io/mediacapture-main/#overconstrainederror-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `OverconstrainedError` | 63 | 79 | No | No | 50 | 11 | 63 | 63 | No | 46 | 11 | 8.0 |
| `OverconstrainedError` | 63 | 79 | No | No | 50 | 11 | 63 | 63 | No | 46 | 11 | 8.0 |
| `constraint` | 63 | 79 | No | No | 50 | 11.1 | 63 | 63 | No | 46 | 11.3 | 8.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/OverconstrainedError>

PageTransitionEvent
===================



The `PageTransitionEvent` event object is available inside handler functions for the [`pageshow`](window/pageshow_event) and [`pagehide`](window/pagehide_event) events, fired when a document is being loaded or unloaded.


 Event PageTransitionEvent

Constructor
-----------


 [`PageTransitionEvent()`](pagetransitionevent/pagetransitionevent)  Creates a new `PageTransitionEvent` object.

  
Instance properties
-------------------



*This interface also inherits properties from its parent, [`Event`](event).*

  
[`PageTransitionEvent.persisted`](pagetransitionevent/persisted) Read only 
  Indicates if the document is loading from a cache.

  

Example
-------


### HTML



```
<!DOCTYPE html>
<html lang="en-US">
  <body></body>
</html>

```

### JavaScript



```
window.addEventListener("pageshow", (event) => {
  if (event.persisted) {
    alert("The page was cached by the browser");
  } else {
    alert("The page was NOT cached by the browser");
  }
});

```

Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-pagetransitionevent-interface](https://html.spec.whatwg.org/multipage/nav-history-apis.html#the-pagetransitionevent-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PageTransitionEvent` | 16 | 79 | 11 | No | 15 | 6 | 4.4 | 18 | 14 | 14 | 6 | 1.0 |
| `PageTransitionEvent` | 4 | 12 | 1.5 | 11 | 15 | 5 | ≤37 | 18 | 4 | 14 | 4 | 1.0 |
| `persisted` | 4 | 12 | 11 | 11The `persisted` property is known to be buggy in Internet Explorer. It is advised to check if `window.performance.navigation.type == 2` as well. | 15 | 5 | ≤37 | 18 | 14 | 14 | 4 | 1.0 |


See also
--------


* [`pageshow`](window/pageshow_event) event
* [`pagehide`](window/pagehide_event) event


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PageTransitionEvent>

PaymentRequest
==============



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The [Payment Request API's](payment_request_api) `PaymentRequest` interface is the primary access point into the API, and lets web content and apps accept payments from the end user on behalf of the operator of the site or the publisher of the app.


 EventTarget PaymentRequest

Constructor
-----------


 
[`PaymentRequest()`](paymentrequest/paymentrequest) Secure context
  Creates a new `PaymentRequest` object.

  
Instance properties
-------------------


 
[`PaymentRequest.id`](paymentrequest/id) Read only  Secure context
  An unique identifier for a particular `PaymentRequest`, which can be set via `details.id`. When none is set, it defaults to a UUID.

  
[`PaymentRequest.shippingAddress`](paymentrequest/shippingaddress) Read only  Secure context  Deprecated   Non-standard 
  If requested via payment options, returns the shipping address chosen by the user for the purposes of calculating shipping. This property is only populated if the constructor is called with the `requestShipping` flag set to true. Additionally, in some browsers, the parts of the address will be redacted for privacy until the user indicates they are ready to complete the transaction (i.e., they hit "Pay").

  
[`PaymentRequest.shippingOption`](paymentrequest/shippingoption) Read only  Secure context  Deprecated   Non-standard 
  Returns the identifier of the selected shipping option. This property is only populated if the constructor is called with the `requestShipping` flag set to true.

  
[`PaymentRequest.shippingType`](paymentrequest/shippingtype) Read only  Secure context  Deprecated   Non-standard 
  Returns the type of shipping used to fulfill the transaction. This will be one of `shipping`, `delivery`, `pickup`, or `null` if a value was not provided in the constructor.

  
Instance methods
----------------


 
[`PaymentRequest.canMakePayment()`](paymentrequest/canmakepayment) Secure context
  Indicates whether the `PaymentRequest` object can make a payment before calling `show()`.

  
[`PaymentRequest.show()`](paymentrequest/show) Secure context
  Causes the user agent to begin the user interaction for the payment request.

  
[`PaymentRequest.abort()`](paymentrequest/abort) Secure context
  Causes the user agent to end the payment request and to remove any user interface that might be shown.

  
Events
------


 
[`merchantvalidation`](paymentrequest/merchantvalidation_event) Secure context  Deprecated 
  With some payment handlers (e.g., Apple Pay), this event handler is called to handle the [`merchantvalidation`](paymentrequest/merchantvalidation_event) event, which is dispatched when the user agent requires that the merchant validate that the merchant or vendor requesting payment is legitimate.

  
[`paymentmethodchange`](paymentrequest/paymentmethodchange_event) Secure context
  With some payment handlers (e.g., Apple Pay), dispatched whenever the user changes payment instrument, like switching from a credit card to a debit card.

  
[`shippingaddresschange`](paymentrequest/shippingaddresschange_event) Secure context  Deprecated   Non-standard 
  Dispatched whenever the user changes their shipping address.

  
[`shippingoptionchange`](paymentrequest/shippingoptionchange_event) Secure context  Deprecated   Non-standard 
  Dispatched whenever the user changes a shipping option.

  
Specifications
--------------




| Specification |
| --- |
| [Payment Request API 1.1 # paymentrequest-interface](https://w3c.github.io/payment-request/#paymentrequest-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PaymentRequest` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `PaymentRequest` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `abort` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `canMakePayment` | 60 | 16 | 55 | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `id` | 60 | 16 | 55 | No | 47 | 11.1 | No | 60 | No | 44 | 11.3 | 8.0 |
| `merchantvalidation_event` | No | No | 55 | No | No | 11.1 | No | No | No | No | 11.3 | No |
| `paymentmethodchange_event` | 76 | 79 | 55 | No | 47 | 12.1 | No | 76 | No | 44 | 12.2 | 12.0 |
| `shippingAddress` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `shippingOption` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `shippingType` | 60 | 15 | 55 | No | 47 | 11.1 | No | 55 | No | 44 | 11.3 | 6.0 |
| `shippingaddresschange_event` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `shippingoptionchange_event` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |
| `show` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 44 | 11.3 | 6.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PaymentRequest>

PaymentRequestEvent
===================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `PaymentRequestEvent` interface of the [Payment Request API](payment_request_api) is the object passed to a payment handler when a [`PaymentRequest`](paymentrequest) is made.


 Event ExtendableEvent PaymentRequestEvent

Constructor
-----------


 
[`PaymentRequestEvent()`](paymentrequestevent/paymentrequestevent)  Experimental 
  Creates a new `PaymentRequestEvent` object instance.

  
Instance properties
-------------------


 
[`instrumentKey`](paymentrequestevent/instrumentkey) Read only   Deprecated   Non-standard 
  Returns a `PaymentInstrument` object reflecting the payment instrument selected by the user or an empty string if the user has not registered or chosen a payment instrument.

  
[`methodData`](paymentrequestevent/methoddata) Read only   Experimental 
  Returns an array of `PaymentMethodData` objects containing payment method identifiers for the payment methods that the web site accepts and any associated payment method specific data.

  
[`modifiers`](paymentrequestevent/modifiers) Read only   Experimental 
  Returns an array of objects containing changes to payment details.

  
[`paymentRequestId`](paymentrequestevent/paymentrequestid) Read only   Experimental 
  Returns the ID of the [`PaymentRequest`](paymentrequest) object.

  
[`paymentRequestOrigin`](paymentrequestevent/paymentrequestorigin) Read only   Experimental 
  Returns the origin where the [`PaymentRequest`](paymentrequest) object was initialized.

  
[`topOrigin`](paymentrequestevent/toporigin) Read only   Experimental 
  Returns the top-level origin where the [`PaymentRequest`](paymentrequest) object was initialized.

  
[`total`](paymentrequestevent/total) Read only   Experimental 
  Returns the total amount being requested for payment.

  
Instance methods
----------------


 
[`openWindow()`](paymentrequestevent/openwindow)  Experimental 
  Opens the specified URL in a new window, if and only if the given URL is on the same origin as the calling page. It returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with a reference to a [`WindowClient`](windowclient).

  
[`respondWith()`](paymentrequestevent/respondwith)  Experimental 
  Prevents the default event handling and allows you to provide a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) for a [`PaymentResponse`](paymentresponse) object yourself.

  
Examples
--------



When the [`PaymentRequest.show()`](paymentrequest/show) method is invoked, a [`paymentrequest`](serviceworkerglobalscope/paymentrequest_event) event is fired on the service worker of the payment app. This event is listened for inside the payment app's service worker to begin the next stage of the payment process.

 
```
let payment_request_event;
let resolver;
let client;

// `self` is the global object in service worker
self.addEventListener("paymentrequest", async (e) => {
  if (payment_request_event) {
    // If there's an ongoing payment transaction, reject it.
    resolver.reject();
  }
  // Preserve the event for future use
  payment_request_event = e;

  // ...
});

```
 When a `paymentrequest` event is received, the payment app can open a payment handler window by calling [`PaymentRequestEvent.openWindow()`](paymentrequestevent/openwindow). The payment handler window will present the customers with a payment app interface where they can authenticate, choose shipping address and options, and authorize the payment.

 When the payment has been handled, [`PaymentRequestEvent.respondWith()`](paymentrequestevent/respondwith) is used to pass the payment result back to the merchant website.

 See [Receive a payment request event from the merchant](https://web.dev/orchestrating-payment-transactions/#receive-payment-request-event) for more details of this stage.



Specifications
--------------




| Specification |
| --- |
| [Payment Handler API # the-paymentrequestevent](https://w3c.github.io/payment-handler/#the-paymentrequestevent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PaymentRequestEvent` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |
| `PaymentRequestEvent` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |
| `changePaymentMethod` | 76 | 79 | No | No | 63 | No | No | 76 | No | 54 | No | 12.0 |
| `changeShippingAddress` | 80 | 80 | No | No | 67 | No | No | 80 | No | 57 | No | 13.0 |
| `changeShippingOption` | 80 | 80 | No | No | 67 | No | No | 80 | No | 57 | No | 13.0 |
| `instrumentKey` | 70–111 | 79–111 | No | No | 57–97 | No | No | 70–111 | No | 49 | No | 10.0 |
| `methodData` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |
| `modifiers` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |
| `openWindow` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |
| `paymentOptions` | 80 | 80 | No | No | 67 | No | No | 80 | No | 57 | No | 13.0 |
| `paymentRequestId` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |
| `paymentRequestOrigin` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |
| `respondWith` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |
| `shippingOptions` | 80 | 80 | No | No | 67 | No | No | 80 | No | 57 | No | 13.0 |
| `topOrigin` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |
| `total` | 70 | 79 | No | No | 57 | No | No | 70 | No | 49 | No | 10.0 |


See also
--------


* [Web-based payment apps overview](https://web.dev/web-based-payment-apps-overview/)
* [Setting up a payment method](https://web.dev/setting-up-a-payment-method/)
* [Life of a payment transaction](https://web.dev/life-of-a-payment-transaction/)
* [Using the Payment Request API](payment_request_api/using_the_payment_request_api)
* [Payment processing concepts](payment_request_api/concepts)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PaymentRequestEvent>

PaymentRequestUpdateEvent
=========================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `PaymentRequestUpdateEvent` interface is used for events sent to a [`PaymentRequest`](paymentrequest) instance when changes are made to shipping-related information for a pending [`PaymentRequest`](paymentrequest). Those events are:

  
[`shippingaddresschange`](paymentrequest/shippingaddresschange_event) Secure context
  Dispatched whenever the user changes their shipping address.

  
[`shippingoptionchange`](paymentrequest/shippingoptionchange_event) Secure context
  Dispatched whenever the user changes a shipping option.

  
 Event PaymentRequestUpdateEvent

Constructor
-----------


 
[`PaymentRequestUpdateEvent()`](paymentrequestupdateevent/paymentrequestupdateevent) Secure context
  Creates a new `PaymentRequestUpdateEvent` object.

  
Instance properties
-------------------


*Provides only the properties inherited from its parent interface, [`Event`](event).*


Instance methods
----------------



*In addition to methods inherited from the parent interface, [`Event`](event), `PaymentRequestUpdateEvent` offers the following methods:*

  
[`PaymentRequestUpdateEvent.updateWith()`](paymentrequestupdateevent/updatewith) Secure context
  If the event handler determines that information included in the payment request needs to be changed, or that new information needs to be added, it calls `updateWith()` with the information that needs to be replaced or added.

  

Specifications
--------------




| Specification |
| --- |
| [Payment Request API 1.1 # paymentrequestupdateevent-interface](https://w3c.github.io/payment-request/#paymentrequestupdateevent-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PaymentRequestUpdateEvent` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 41 | 11.3 | 6.0 |
| `PaymentRequestUpdateEvent` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 41 | 11.3 | 6.0 |
| `updateWith` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 41 | 11.3 | 6.0 |


See also
--------


* [Using the Payment Request API](payment_request_api/using_the_payment_request_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PaymentRequestUpdateEvent>

PaymentResponse
===============



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `PaymentResponse` interface of the [Payment Request API](payment_request_api) is returned after a user selects a payment method and approves a payment request.


 EventTarget PaymentResponse

Instance properties
-------------------


 
[`PaymentResponse.details`](paymentresponse/details) Read only  Secure context
  Returns a JSON-serializable object that provides a payment method specific message used by the merchant to process the transaction and determine successful fund transfer. The contents of the object depend on the payment method being used. Developers need to consult whomever controls the URL for the expected shape of the details object.

  
[`PaymentResponse.methodName`](paymentresponse/methodname) Read only  Secure context
  Returns the payment method identifier for the payment method that the user selected, for example, Visa, Mastercard, Paypal, etc.

  
[`PaymentResponse.payerEmail`](paymentresponse/payeremail) Read only  Secure context  Deprecated   Non-standard 
  Returns the email address supplied by the user. This option is only present when the `requestPayerEmail` option is set to `true` in the `options` parameter of the [`PaymentRequest()`](paymentrequest/paymentrequest) constructor.

  
[`PaymentResponse.payerName`](paymentresponse/payername) Read only  Secure context  Deprecated   Non-standard 
  Returns the name supplied by the user. This option is only present when the `requestPayerName` option is set to true in the `options` parameter of the [`PaymentRequest()`](paymentrequest/paymentrequest) constructor.

  
[`PaymentResponse.payerPhone`](paymentresponse/payerphone) Read only  Secure context  Deprecated   Non-standard 
  Returns the phone number supplied by the user. This option is only present when the `requestPayerPhone` option is set to `true` in the `options` parameter of the [`PaymentRequest()`](paymentrequest/paymentrequest) constructor.

  
[`PaymentResponse.requestId`](paymentresponse/requestid) Read only  Secure context
  Returns the identifier of the [`PaymentRequest`](paymentrequest) that produced the current response. This is the same value supplied in the [`PaymentRequest()`](paymentrequest/paymentrequest) constructor by `details.id`.

  
[`PaymentResponse.shippingAddress`](paymentresponse/shippingaddress) Read only  Secure context  Deprecated   Non-standard 
  Returns the shipping Address supplied by the user. This option is only present when the `requestShipping` option is set to `true` in the `options` parameter of the [`PaymentRequest()`](paymentrequest/paymentrequest) constructor.

  
[`PaymentResponse.shippingOption`](paymentresponse/shippingoption) Read only  Secure context  Deprecated   Non-standard 
  Returns the ID attribute of the shipping option selected by the user. This option is only present when the `requestShipping` option is set to `true` in the `options` parameter of the [`PaymentRequest()`](paymentrequest/paymentrequest) constructor.

  
Instance methods
----------------


 
[`PaymentResponse.retry()`](paymentresponse/retry) Secure context
  If something is wrong with the payment response's data (and there is a recoverable error), this method allows a merchant to request that the user retry the payment. The method takes an object as argument, which is used to signal to the user exactly what is wrong with the payment response so they can try to correct any issues.

  
[`PaymentResponse.complete()`](paymentresponse/complete) Secure context
  Notifies the user agent that the user interaction is over. This causes any remaining user interface to be closed. This method should only be called after the Promise returned by the [`PaymentRequest.show()`](paymentrequest/show) method.

  
[`PaymentResponse.toJSON()`](paymentresponse/tojson) Secure context
  Returns a [JSON object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON) representing this `PaymentResponse` object.

  
Events
------



Listen to this event using [`addEventListener()`](eventtarget/addeventlistener) or by assigning an event listener to the `oneventname` property of this interface.

  
[`payerdetailchange`](paymentresponse/payerdetailchange_event) Secure context  Deprecated   Non-standard 
  Fired during a retry when the user makes changes to their personal information while filling out a payment request form. Allows the developer to revalidate any requested user data (e.g., the phone number or the email address) if it changes.

  

Specifications
--------------




| Specification |
| --- |
| [Payment Request API 1.1 # paymentresponse-interface](https://w3c.github.io/payment-request/#paymentresponse-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PaymentResponse` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 41 | 11.3 | 6.0 |
| `complete` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 41 | 11.3 | 6.0 |
| `details` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 41 | 11.3 | 6.0 |
| `methodName` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 41 | 11.3 | 6.0 |
| `payerEmail` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 41 | 11.3 | 6.0 |
| `payerName` | 60 | 15 | 55 | No | 47 | 11.1 | No | 56 | No | 43 | 11.3 | 6.0 |
| `payerPhone` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 41 | 11.3 | 6.0 |
| `payerdetailchange_event` | 78 | 79 | 55 | No | 47 | 12.1 | No | 78 | No | 43 | 12.2 | 12.0 |
| `requestId` | 60 | 16 | 55 | No | 47 | 11.1 | No | 60 | No | 43 | 11.3 | 8.0 |
| `retry` | 78 | 79 | 55 | No | 47 | 12.1 | No | 78 | No | 43 | 11.3 | 10.0 |
| `shippingAddress` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 41 | 11.3 | 6.0 |
| `shippingOption` | 60 | 15 | 55 | No | 47 | 11.1 | No | 53 | No | 41 | 11.3 | 6.0 |
| `toJSON` | 60 | 15 | 55 | No | 47 | 11.1 | No | 55 | No | 42 | 11.3 | 6.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PaymentResponse>

Performance
===========



The `Performance` interface provides access to performance-related information for the current page.

 An object of this type can be obtained by calling `window.performance` or `self.performance` in workers. Note that Performance entries are per context. If you create a mark on the main thread (or other worker), you cannot see it in a worker thread, and vice versa. See [`self.performance`](performance_property) for which APIs are available in window and worker contexts.


 EventTarget Performance

Instance properties
-------------------



*The `Performance` interface doesn't inherit any properties.*

  
[`Performance.eventCounts`](performance/eventcounts) Read only 
  An [`EventCounts`](eventcounts) map containing the number of events which have been dispatched per event type.

  
[`Performance.navigation`](performance/navigation) Read only   Deprecated 
  A legacy [`PerformanceNavigation`](performancenavigation) object that provides useful context about the operations included in the times listed in `timing`, including whether the page was a load or a refresh, how many redirections occurred, and so forth.

  
[`Performance.timing`](performance/timing) Read only   Deprecated 
  A legacy [`PerformanceTiming`](performancetiming) object containing latency-related performance information.

  
[`Performance.memory`](performance/memory) Read only   Non-standard   Deprecated 
  A *non-standard* extension added in Chrome, this property provides an object with basic memory usage information. *You **should not use** this non-standard API.*

  
[`Performance.timeOrigin`](performance/timeorigin) Read only 
  Returns the high resolution timestamp of the start time of the performance measurement.

  

Instance methods
----------------



*The `Performance` interface doesn't inherit any methods.*

  [`Performance.clearMarks()`](performance/clearmarks)  Removes the given *mark* from the browser's performance entry buffer.

  [`Performance.clearMeasures()`](performance/clearmeasures)  Removes the given *measure* from the browser's performance entry buffer.

  [`Performance.clearResourceTimings()`](performance/clearresourcetimings)  Removes all [`performance entries`](performanceentry) with a [`entryType`](performanceentry/entrytype) of "`resource`" from the browser's performance data buffer.

  [`Performance.getEntries()`](performance/getentries)  Returns a list of [`PerformanceEntry`](performanceentry) objects based on the given *filter*.

  [`Performance.getEntriesByName()`](performance/getentriesbyname)  Returns a list of [`PerformanceEntry`](performanceentry) objects based on the given *name* and *entry type*.

  [`Performance.getEntriesByType()`](performance/getentriesbytype)  Returns a list of [`PerformanceEntry`](performanceentry) objects of the given *entry type*.

  [`Performance.mark()`](performance/mark)  Creates a [`timestamp`](domhighrestimestamp) in the browser's *performance entry buffer* with the given name.

  [`Performance.measure()`](performance/measure)  Creates a named [`timestamp`](domhighrestimestamp) in the browser's performance entry buffer between two specified marks (known as the *start mark* and *end mark*, respectively).

  
[`Performance.measureUserAgentSpecificMemory()`](performance/measureuseragentspecificmemory)  Experimental 
  Estimates the memory usage of a web application including all its iframes and workers.

  [`Performance.now()`](performance/now)  Returns a [`DOMHighResTimeStamp`](domhighrestimestamp) representing the number of milliseconds elapsed since a reference instant.

  [`Performance.setResourceTimingBufferSize()`](performance/setresourcetimingbuffersize)  Sets the browser's resource timing buffer size to the specified number of "`resource`" [`type`](performanceentry/entrytype) [`performance entry`](performanceentry) objects.

  [`Performance.toJSON()`](performance/tojson)  Returns a JSON representation of the `Performance` object.

  

Events
------



Listen to these events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface.

  [`resourcetimingbufferfull`](performance/resourcetimingbufferfull_event)  Fired when the browser's [resource timing buffer](performance/setresourcetimingbuffersize) is full.

  

Specifications
--------------




| Specification |
| --- |
| [High Resolution Time # sec-performance](https://w3c.github.io/hr-time/#sec-performance) |
| [Performance Timeline # extensions-to-the-performance-interface](https://w3c.github.io/performance-timeline/#extensions-to-the-performance-interface) |
| [Resource Timing # sec-extensions-performance-interface](https://w3c.github.io/resource-timing/#sec-extensions-performance-interface) |
| [User Timing # extensions-performance-interface](https://w3c.github.io/user-timing/#extensions-performance-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Performance` | 6 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `clearMarks` | 2925–29 | 12 | 38 | 10 | 33 | 11 | 4.4 | 2925–29 | 42 | 33 | 11 | 2.01.5–2.0 |
| `clearMeasures` | 2925–29 | 12 | 38 | 10 | 33 | 11 | 4.4 | 2925–29 | 42 | 33 | 11 | 2.01.5–2.0 |
| `clearResourceTimings` | 4622–57 | 12 | 35 | 10 | 3315–44 | 11 | 464.4–57 | 4625–57 | 35 | 3314–43 | 11 | 5.01.5–7.0 |
| `eventCounts` | 85 | 85 | 89 | No | 71 | No | 85 | 85 | 89 | 60 | No | 14.0 |
| `getEntries` | 2825–36 | 12 | 35 | 10 | No | 11 | 4.4 | 2825–36 | 35 | No | 11 | 1.51.5–3.0 |
| `getEntriesByName` | 2825–36 | 12 | 35 | 10 | No | 11 | 4.4 | 2825–36 | 35 | No | 11 | 1.51.5–3.0 |
| `getEntriesByType` | 2825–36 | 12 | 35 | 10 | 1515–23 | 11 | 4.4 | 2825–36 | 35 | 1514–24 | 11 | 1.51.5–3.0 |
| `mark` | 2825–28 | 12 | 38 | 10 | 33 | 11 | 4.4 | 2825–28 | 42 | 33 | 11 | 1.5 |
| `measure` | 2825–28 | 12 | 38 | 10 | 33 | 11 | 4.4 | 2825–28 | 42 | 33 | 11 | 1.5 |
| `measureUserAgentSpecificMemory` | 89 | 89 | No | No | 75 | No | 89 | 89 | No | 63 | No | 15.0 |
| `memory` | 7 | 79 | No | No | 15 | No | ≤37 | 18 | No | 14 | No | 1.0 |
| `navigation` | 10 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | No | 9 | 1.0 |
| `now` | 2421–24 | 12 | 15["In Firefox 57.0.4 the accuracy was reduced to 20 microseconds.", "In Firefox 59 the accuracy was reduced to 2 milliseconds.", "In Firefox 60 the accuracy was increased to 1 millisecond."] | 10 | 15 | 8 | 4.4 | 25 | 15["In Firefox 57.0.4 the accuracy was reduced to 20 microseconds.", "In Firefox 59 the accuracy was reduced to 2 milliseconds.", "In Firefox 60 the accuracy was increased to 1 millisecond."] | 14 | 9 | 1.5 |
| `resourcetimingbufferfull_event` | 4622–57 | 79 | 35 | No | No | 11 | 464.4–57 | 4625–57 | 35 | 3314–43 | 11 | 5.01.5–7.0 |
| `setResourceTimingBufferSize` | 4622–57 | 12 | 35 | 10 | 3315–44 | 11 | 464.4–57 | 4625–57 | 35 | 3314–43 | 11 | 5.01.5–7.0 |
| `timeOrigin` | 62 | 16 | 53 | No | 49 | 15 | 62 | 62 | 53 | 46 | 15 | 8.0 |
| `timing` | 6 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `toJSON` | 56 | 12 | 25 | 9 | No | 14.1 | 56 | 56 | 25 | No | 14.5 | 6.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Performance>

PerformanceElementTiming
========================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `PerformanceElementTiming` interface contains render timing information for image and text node elements the developer annotated with an [`elementtiming`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/elementtiming) attribute for observation.



Description
-----------



The aim of the Element Timing API is to give web developers or analytics tools the ability to measure rendering timestamps of critical elements on a page.

 The API supports timing information on the following elements:

 * [`<img>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img) elements,
* [`<image>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/image) elements inside an [`<svg>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg),
* [poster](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#poster) images of [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) elements,
* elements which have a [`background-image`](https://developer.mozilla.org/en-US/docs/Web/CSS/background-image), and
* groups of text nodes, such as a [`<p>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p).

 The author flags an element for observation by adding the [`elementtiming`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/elementtiming) attribute on the element.

 `PerformanceElementTiming` inherits from [`PerformanceEntry`](performanceentry).


 PerformanceEntry PerformanceElementTiming

Instance properties
-------------------



This interface extends the following [`PerformanceEntry`](performanceentry) properties for event timing performance entry types by qualifying them as follows:

  
[`PerformanceEntry.duration`](performanceentry/duration) Read only   Experimental 
  Always returns `0` as `duration` does not apply to this interface.

  
[`PerformanceEntry.entryType`](performanceentry/entrytype) Read only   Experimental 
  Always returns `"element"`.

  
[`PerformanceEntry.name`](performanceentry/name) Read only   Experimental 
  Returns `"image-paint"` for images and `"text-paint"` for text.

  
[`PerformanceEntry.startTime`](performanceentry/starttime) Read only   Experimental 
  Returns the value of this entry's [`renderTime`](performanceelementtiming/rendertime) if it is not `0`, otherwise the value of this entry's [`loadTime`](performanceelementtiming/loadtime).

   This interface also supports the following properties:

  
[`PerformanceElementTiming.element`](performanceelementtiming/element) Read only   Experimental 
  An [`Element`](element) representing the element we are returning information about.

  
[`PerformanceElementTiming.id`](performanceelementtiming/id) Read only   Experimental 
  A string which is the [`id`](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#id) of the element.

  
[`PerformanceElementTiming.identifier`](performanceelementtiming/identifier) Read only   Experimental 
  A string which is the value of the [`elementtiming`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/for) attribute on the element.

  
[`PerformanceElementTiming.intersectionRect`](performanceelementtiming/intersectionrect) Read only   Experimental 
  A [`DOMRectReadOnly`](domrectreadonly) which is the rectangle of the element within the viewport.

  
[`PerformanceElementTiming.loadTime`](performanceelementtiming/loadtime) Read only   Experimental 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) with the loadTime of the element.

  
[`PerformanceElementTiming.naturalHeight`](performanceelementtiming/naturalheight) Read only   Experimental 
  An unsigned 32-bit integer (unsigned long) which is the intrinsic height of the image if this is applied to an image, 0 for text.

  
[`PerformanceElementTiming.naturalWidth`](performanceelementtiming/naturalwidth) Read only   Experimental 
  An unsigned 32-bit integer (unsigned long) which is the intrinsic width of the image if this is applied to an image, 0 for text.

  
[`PerformanceElementTiming.renderTime`](performanceelementtiming/rendertime) Read only   Experimental 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) with the renderTime of the element.

  
[`PerformanceElementTiming.url`](performanceelementtiming/url) Read only   Experimental 
  A string which is the initial URL of the resources request for images, 0 for text.

  

Instance methods
----------------


 
[`PerformanceElementTiming.toJSON()`](performanceelementtiming/tojson)  Experimental 
  Returns a JSON representation of the `PerformanceElementTiming` object.

  
Examples
--------


### Observing render time of specific elements



In this example two elements are being observed by adding the [`elementtiming`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/elementtiming) attribute. A [`PerformanceObserver`](performanceobserver) is registered to get all performance entries of type `"element"` and the `buffered` flag is used to access data from before observer creation.

 
```
<img src="image.jpg" elementtiming="big-image" />
<p elementtiming="text" id="text-id">text here</p>

```
 
```
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    console.log(entry);
  });
});
observer.observe({ type: "element", buffered: true });

```
 Two entries will be output to the console. The first containing details of the image, the second with details of the text node.



Specifications
--------------




| Specification |
| --- |
| [Element Timing API # sec-performance-element-timing](https://wicg.github.io/element-timing/#sec-performance-element-timing) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PerformanceElementTiming` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |
| `element` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |
| `id` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |
| `identifier` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |
| `intersectionRect` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |
| `loadTime` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |
| `naturalHeight` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |
| `naturalWidth` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |
| `renderTime` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |
| `toJSON` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |
| `url` | 77 | 79 | No | No | 64 | No | 77 | 77 | No | 55 | No | 12.0 |


See also
--------


* [`elementtiming`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/elementtiming) HTML attribute


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PerformanceElementTiming>

PerformanceLongTaskTiming
=========================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `PerformanceLongTaskTiming` interface provides information about tasks that occupy the UI thread for 50 milliseconds or more.



Description
-----------



Long tasks that block the main thread for 50ms or more cause, among other issues:

 * Delayed [Time to interactive](https://developer.mozilla.org/en-US/docs/Glossary/Time_to_interactive) (TTI).
* High/variable input latency.
* High/variable event handling latency.
* Janky animations and scrolling.

 A long task is any uninterrupted period where the main UI thread is busy for 50ms or longer. Common examples include:

 * Long-running event handlers.
* Expensive reflows and other re-renders.
* Work the browser does between different turns of the event loop that exceeds 50 ms.

 Long tasks refer to "culprit browsing context container", or "the container" for short, which is the top-level page, [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe), [`<embed>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/embed) or [`<object>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object) that the task occurred within.

 For tasks that don't occur within the top-level page and for figuring out which container is responsible for the long task, the [`TaskAttributionTiming`](taskattributiontiming) interface provides the `containerId`, `containerName` and `containerSrc` properties, which may provide more information about the source of the task.



Inheritance
-----------



`PerformanceLongTaskTiming` inherits from [`PerformanceEntry`](performanceentry).


 PerformanceEntry PerformanceLongTaskTiming

Instance properties
-------------------



This interface extends the following [`PerformanceEntry`](performanceentry) properties for long task timing performance entry types by qualifying them as follows:

  
[`PerformanceEntry.duration`](performanceentry/duration) Read only   Experimental 
  Returns a [`DOMHighResTimeStamp`](domhighrestimestamp) representing the elapsed time between the start and end of the task, with a 1ms granularity.

  
[`PerformanceEntry.entryType`](performanceentry/entrytype) Read only   Experimental 
  Always returns `"longtask"`

  
[`PerformanceEntry.name`](performanceentry/name) Read only   Experimental 
  Returns one of the following strings referring to the browsing context or frame that can be attributed to the long task:

 * `"cross-origin-ancestor"`
* `"cross-origin-descendant"`
* `"cross-origin-unreachable"`
* `"multiple-contexts"`
* `"same-origin-ancestor"`
* `"same-origin-descendant"`
* `"same-origin"`
* `"self"`
* `"unknown"`

  
[`PerformanceEntry.startTime`](performanceentry/starttime) Read only   Experimental 
  Returns a [`DOMHighResTimeStamp`](domhighrestimestamp) representing the time when the task started.

   This interface also supports the following properties:

  
[`PerformanceLongTaskTiming.attribution`](performancelongtasktiming/attribution) Read only   Experimental 
  Returns a sequence of [`TaskAttributionTiming`](taskattributiontiming) instances.

  

Instance methods
----------------


 
[`PerformanceLongTaskTiming.toJSON()`](performancelongtasktiming/tojson)  Experimental 
  Returns a JSON representation of the `PerformanceLongTaskTiming` object.

  
Examples
--------


### Getting long tasks



To get long task timing information, create a [`PerformanceObserver`](performanceobserver) instance and then call its [`observe()`](performanceobserver/observe) method, passing in `"longtask"` as the value of the [`type`](performanceentry/entrytype) option. You also need to set `buffered` to `true` to get access to long tasks the user agent buffered while constructing the document. The `PerformanceObserver` object's callback will then be called with a list of `PerformanceLongTaskTiming` objects which you can analyze.

 
```
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    console.log(entry);
  });
});

observer.observe({ type: "longtask", buffered: true });

```


Specifications
--------------




| Specification |
| --- |
| [Long Tasks API 1 # sec-PerformanceLongTaskTiming](https://w3c.github.io/longtasks/#sec-PerformanceLongTaskTiming) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PerformanceLongTaskTiming` | 58 | 79 | NoSee [bug 1348405](https://bugzil.la/1348405). | No | 45 | No | 58 | 58 | NoSee [bug 1348405](https://bugzil.la/1348405). | 43 | No | 7.0 |
| `attribution` | 58 | 79 | No | No | 45 | No | 58 | 58 | No | 43 | No | 7.0 |
| `toJSON` | 58 | 79 | No | No | 45 | No | 58 | 58 | No | 43 | No | 7.0 |


See also
--------


* [`TaskAttributionTiming`](taskattributiontiming)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PerformanceLongTaskTiming>

PerformanceMark
===============



`PerformanceMark` is an interface for [`PerformanceEntry`](performanceentry) objects with an [`entryType`](performanceentry/entrytype) of "`mark`".

 Entries of this type are typically created by calling [`performance.mark()`](performance/mark) to add a *named* [`DOMHighResTimeStamp`](domhighrestimestamp) (the *mark*) to the browser's performance timeline. To create a performance mark that isn't added to the browser's performance timeline, use the constructor.


 PerformanceEntry PerformanceMark  **Note:** This feature is available in [Web Workers](web_workers_api)

 

Constructor
-----------


 [`PerformanceMark()`](performancemark/performancemark)  Creates a new `PerformanceMark` object that isn't added to the browser's performance timeline.

  
Instance properties
-------------------



This interface extends the following [`PerformanceEntry`](performanceentry) properties by qualifying/constraining the properties as follows:

  
[`PerformanceEntry.entryType`](performanceentry/entrytype) Read only 
  Returns "`mark`".

  
[`PerformanceEntry.name`](performanceentry/name) Read only 
  Returns the name given to the mark when it was created via a call to [`performance.mark()`](performance/mark).

  
[`PerformanceEntry.startTime`](performanceentry/starttime) Read only 
  Returns the [`DOMHighResTimeStamp`](domhighrestimestamp) when [`performance.mark()`](performance/mark) was called.

  
[`PerformanceEntry.duration`](performanceentry/duration) Read only 
  Returns "`0`". (A mark has no *duration*.)

   This interface also supports the following properties:

  
[`PerformanceMark.detail`](performancemark/detail) Read only 
  Returns arbitrary metadata that has been included in the mark upon construction.

  

Instance methods
----------------


This interface has no methods.


Example
-------


See the example in [Using the User Timing API](performance_api/user_timing).


Specifications
--------------




| Specification |
| --- |
| [User Timing # performancemark](https://w3c.github.io/user-timing/#performancemark) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PerformanceMark` | 76 | 79 | 101 | No | 63 | 14.1 | 79 | 76 | 101 | 54 | 14.5 | 12.0 |
| `PerformanceMark` | 28 | 12 | 38 | 10 | 15 | 11 | 4.4 | 28 | 38 | 14 | 11 | 1.5 |
| `detail` | 78 | 79 | 101 | No | 65 | 14.1 | 79 | 78 | 101 | 56 | 14.5 | 12.0 |


See also
--------


* [User Timing (Overview)](performance_api/user_timing)
* [Using the User Timing API](performance_api/user_timing)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PerformanceMark>

PerformanceNavigation
=====================



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The legacy `PerformanceNavigation` interface represents information about how the navigation to the current document was done.

   **Warning:** This interface is deprecated in the [Navigation Timing Level 2 specification](https://w3c.github.io/navigation-timing/#obsolete). Please use the [`PerformanceNavigationTiming`](performancenavigationtiming) interface instead. 

  An object of this type can be obtained by calling the [`Performance.navigation`](performance/navigation) read-only attribute.



Instance properties
-------------------



*The `PerformanceNavigation` interface doesn't inherit any properties.*

  
[`PerformanceNavigation.type`](performancenavigation/type) Read only   Deprecated 
  An `unsigned short` which indicates how the navigation to this page was done. Possible values are:

  
`TYPE_NAVIGATE` (0)  The page was accessed by following a link, a bookmark, a form submission, or a script, or by typing the URL in the address bar.

  
`TYPE_RELOAD` (1)  The page was accessed by clicking the Reload button or via the [`Location.reload()`](location/reload) method.

  
`TYPE_BACK_FORWARD` (2)  The page was accessed by navigating into the history.

  
`TYPE_RESERVED` (255)  Any other way.

    
[`PerformanceNavigation.redirectCount`](performancenavigation/redirectcount) Read only   Deprecated 
  An `unsigned short` representing the number of REDIRECTs done before reaching the page.

  

Instance methods
----------------



*The `Performance` interface doesn't inherit any methods.*

  
[`PerformanceNavigation.toJSON()`](performancenavigation/tojson)  Deprecated 
  A [serializer](https://developer.mozilla.org/en-US/docs/Glossary/Serialization) returning a JSON object representing the `PerformanceNavigation` object.

  

Specifications
--------------


 This feature is no longer on track to become a standard, as the [Navigation Timing specification](https://w3c.github.io/navigation-timing/#obsolete) has marked it as deprecated. Use the [`PerformanceNavigationTiming`](performancenavigationtiming) interface instead. 


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PerformanceNavigation` | 10 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `redirectCount` | 10 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `toJSON` | 56 | 12 | 25This property can return incorrect values. See [bug 1459711](https://bugzil.la/1459711). | 9 | 43 | 14.1 | 56 | 56 | 25This property can return incorrect values. See [bug 1459711](https://bugzil.la/1459711). | 43 | 14.5 | 6.0 |
| `type` | 10 | 12 | 7This property can return incorrect values. See [bug 1459711](https://bugzil.la/1459711). | 9 | 15 | 8 | ≤37 | 18 | 7This property can return incorrect values. See [bug 1459711](https://bugzil.la/1459711). | 14 | 9 | 1.0 |


See also
--------


* The [`Performance`](performance) that allows access to an object of this type.
* [`PerformanceNavigationTiming`](performancenavigationtiming) (part of Navigation Timing Level 2) that has superseded this API.


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigation>

PerformanceNavigationTiming
===========================



The `PerformanceNavigationTiming` interface provides methods and properties to store and retrieve metrics regarding the browser's document navigation events. For example, this interface can be used to determine how much time it takes to load or unload a document.

 Only the current document is included in the performance timeline, so there is only one `PerformanceNavigationTiming` object in the performance timeline. It inherits all of the properties and methods of [`PerformanceResourceTiming`](performanceresourcetiming) and [`PerformanceEntry`](performanceentry).


 PerformanceEntry PerformanceResourceTiming PerformanceNavigationTiming The following diagram shows all of the timestamp properties defined in `PerformanceNavigationTiming`.

  ![Timestamp diagram listing timestamps in the order in which they are recorded for the fetching of a document](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming/timestamp-diagram.svg) 



Instance properties
-------------------



This interface extends the following [`PerformanceEntry`](performanceentry) properties by qualifying and constraining them as follows:

  
[`PerformanceEntry.entryType`](performanceentry/entrytype) Read only 
  Returns `"navigation"`.

  
[`PerformanceEntry.name`](performanceentry/name) Read only 
  Returns the [document's URL](document/url).

  
[`PerformanceEntry.startTime`](performanceentry/starttime) Read only 
  Returns a [`DOMHighResTimeStamp`](domhighrestimestamp) with a value of "`0`".

  
[`PerformanceEntry.duration`](performanceentry/duration) Read only 
  Returns a [`timestamp`](domhighrestimestamp) that is the difference between the [`PerformanceNavigationTiming.loadEventEnd`](performancenavigationtiming/loadeventend) and [`PerformanceEntry.startTime`](performanceentry/starttime) properties.

   This interface also extends the following [`PerformanceResourceTiming`](performanceresourcetiming) properties by qualifying and constraining them as follows:

  
[`PerformanceResourceTiming.initiatorType`](performanceresourcetiming/initiatortype) Read only 
  Returns `"navigation"`.

   The interface also supports the following properties:

  
[`PerformanceNavigationTiming.domComplete`](performancenavigationtiming/domcomplete) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) representing the time immediately before the user agent sets the document's [`readyState`](document/readystate) to `"complete"`.

  
[`PerformanceNavigationTiming.domContentLoadedEventEnd`](performancenavigationtiming/domcontentloadedeventend) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) representing the time immediately after the current document's [`DOMContentLoaded`](document/domcontentloaded_event) event handler completes.

  
[`PerformanceNavigationTiming.domContentLoadedEventStart`](performancenavigationtiming/domcontentloadedeventstart) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) representing the time immediately before the current document's [`DOMContentLoaded`](document/domcontentloaded_event) event handler starts.

  
[`PerformanceNavigationTiming.domInteractive`](performancenavigationtiming/dominteractive) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) representing the time immediately before the user agent sets the document's [`readyState`](document/readystate) to `"interactive"`.

  
[`PerformanceNavigationTiming.loadEventEnd`](performancenavigationtiming/loadeventend) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) representing the time immediately after the current document's [`load`](window/load_event) event handler completes.

  
[`PerformanceNavigationTiming.loadEventStart`](performancenavigationtiming/loadeventstart) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) representing the time immediately before the current document's [`load`](window/load_event) event handler starts.

  
[`PerformanceNavigationTiming.redirectCount`](performancenavigationtiming/redirectcount) Read only 
  A number representing the number of redirects since the last non-redirect navigation in the current browsing context.

  
[`PerformanceNavigationTiming.type`](performancenavigationtiming/type) Read only 
  A string representing the navigation type. Either `"navigate"`, `"reload"`, `"back_forward"` or `"prerender"`.

  
[`PerformanceNavigationTiming.unloadEventEnd`](performancenavigationtiming/unloadeventend) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) representing the time immediately after the current document's [`unload`](window/unload_event) event handler completes.

  
[`PerformanceNavigationTiming.unloadEventStart`](performancenavigationtiming/unloadeventstart) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) representing the time immediately before the current document's [`unload`](window/unload_event) event handler starts.

  

Instance methods
----------------


 [`PerformanceNavigationTiming.toJSON()`](performancenavigationtiming/tojson)  Returns a JSON representation of the `PerformanceNavigationTiming` object.

  
Specifications
--------------




| Specification |
| --- |
| [Navigation Timing Level 2 # sec-PerformanceNavigationTiming](https://w3c.github.io/navigation-timing/#sec-PerformanceNavigationTiming) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PerformanceNavigationTiming` | 57 | 12 | 58 | 11 | 44 | 15 | 57 | 57 | 58 | 43 | 15.1 | 7.0 |
| `activationStart` | 108 | 108 | No | No | 94 | No | 57 | 57 | No | 43 | No | 7.0 |
| `domComplete` | 57 | 12 | 58 | 11 | 44 | 15 | 57 | 57 | 58 | 43 | 15.1 | 7.0 |
| `domContentLoadedEventEnd` | 57 | 12 | 58 | 11 | 44 | 15 | 57 | 57 | 58 | 43 | 15.1 | 7.0 |
| `domContentLoadedEventStart` | 57 | 12 | 58 | 11 | 44 | 15 | 57 | 57 | 58 | 43 | 15.1 | 7.0 |
| `domInteractive` | 57 | 12 | 58 | 11 | 44 | 15 | 57 | 57 | 58 | 43 | 15.1 | 7.0 |
| `loadEventEnd` | 57 | 12 | 58 | 11 | 44 | 15 | 57 | 57 | 58 | 43 | 15.1 | 7.0 |
| `loadEventStart` | 57 | 12 | 58 | 11 | 44 | 15 | 57 | 57 | 58 | 43 | 15.1 | 7.0 |
| `redirectCount` | 57 | 12 | 58 | 11 | 44 | 15 | 57 | 57 | 58 | 43 | 15.1 | 7.0 |
| `toJSON` | 57 | 16 | 58 | No | 44 | 15 | 57 | 57 | 58 | 43 | 15.1 | 7.0 |
| `type` | 57 | 12 | 58 | 11 | 44 | 15 | 57 | 57 | 58 | 43 | 15.1 | 7.0 |
| `unloadEventEnd` | 57 | 12 | 58 | 11 | 44 | 15 | 57 | 57 | 58 | 43 | 15.1 | 7.0 |
| `unloadEventStart` | 57 | 12 | 58 | 11 | 44 | 15 | 57 | 57 | 58 | 43 | 15.1 | 7.0 |


See also
--------


* [`Performance.navigation`](performance/navigation)
* [`PerformanceNavigation`](performancenavigation)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming>

PerformancePaintTiming
======================



The `PerformancePaintTiming` interface provides timing information about "paint" (also called "render") operations during web page construction. "Paint" refers to conversion of the render tree to on-screen pixels.

 There are two key paint moments this API provides:

 * [First paint](https://developer.mozilla.org/en-US/docs/Glossary/First_paint) (FP): Time when anything is rendered. Note that the marking of the first paint is optional, not all user agents report it.
* [First contentful paint](https://developer.mozilla.org/en-US/docs/Glossary/First_contentful_paint) (FCP): Time when the first bit of DOM text or image content is rendered.

 A third key paint moment is provided by the [`LargestContentfulPaint`](largestcontentfulpaint) API:

 * [Largest contentful paint](https://developer.mozilla.org/en-US/docs/Glossary/Largest_contentful_paint) (LCP): Render time of the largest image or text block visible within the viewport, recorded from when the page first begins to load.

 The data this API provides helps you minimize the time that users have to wait before they can see the site's content start to appear. Decreasing the time until these key paint moments make sites feel more responsive, performant, and engaging for your users.

 Like other Performance APIs, this API extends [`PerformanceEntry`](performanceentry).


 PerformanceEntry PerformancePaintTiming

Instance properties
-------------------



This interface has no properties but it extends the following [`PerformanceEntry`](performanceentry) properties by qualifying and constraining the properties as follows:

  [`PerformanceEntry.entryType`](performanceentry/entrytype)  Returns "`paint`".

  [`PerformanceEntry.name`](performanceentry/name)  Returns either `"first-paint"` or `"first-contentful-paint"`.

  [`PerformanceEntry.startTime`](performanceentry/starttime)  Returns the [`timestamp`](domhighrestimestamp) when the paint occurred.

  [`PerformanceEntry.duration`](performanceentry/duration)  Returns 0.

  

Instance methods
----------------


This interface has no methods.


Examples
--------


### Getting paint timings



Example using a [`PerformanceObserver`](performanceobserver), which notifies of new `paint` performance entries as they are recorded in the browser's performance timeline. Use the `buffered` option to access entries from before the observer creation.

 
```
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    console.log(
      `The time to ${entry.name} was ${entry.startTime} milliseconds.`
    );
    // Logs "The time to first-paint was 386.7999999523163 milliseconds."
    // Logs "The time to first-contentful-paint was 400.6999999284744 milliseconds."
  });
});

observer.observe({ type: "paint", buffered: true });

```
 Example using [`Performance.getEntriesByType()`](performance/getentriesbytype), which only shows `paint` performance entries present in the browser's performance timeline at the time you call this method:

 
```
const entries = performance.getEntriesByType("paint");
entries.forEach((entry) => {
  console.log(`The time to ${entry.name} was ${entry.startTime} milliseconds.`);
  // Logs "The time to first-paint was 386.7999999523163 milliseconds."
  // Logs "The time to first-contentful-paint was 400.6999999284744 milliseconds."
});

```


Specifications
--------------




| Specification |
| --- |
| [Paint Timing 1 # sec-PerformancePaintTiming](https://w3c.github.io/paint-timing/#sec-PerformancePaintTiming) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PerformancePaintTiming` | 60 | 79 | 84 | No | 47 | 14.1 | 60 | 60 | 84 | 44 | 14.5 | 8.0 |


### See also


* [`LargestContentfulPaint`](largestcontentfulpaint)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PerformancePaintTiming>

PerformanceResourceTiming
=========================



 **Note:** This feature is available in [Web Workers](web_workers_api)

  The `PerformanceResourceTiming` interface enables retrieval and analysis of detailed network timing data regarding the loading of an application's resources. An application can use the timing metrics to determine, for example, the length of time it takes to fetch a specific resource, such as an [`XMLHttpRequest`](xmlhttprequest), [`<SVG>`](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg), image, or script.



Description
-----------



The interface's properties create a resource loading timeline with high-resolution timestamps for network events such as redirect start and end times, fetch start, DNS lookup start and end times, response start and end times, and more. Additionally, the interface extends [`PerformanceEntry`](performanceentry) with other properties which provide data about the size of the fetched resource as well as the type of resource that initiated the fetch.


 PerformanceEntry PerformanceResourceTiming

### Typical resource timing metrics



The properties of this interface allow you to calculate certain resource timing metrics. Common use cases include:

 * Measuring TCP handshake time (`connectEnd` - `connectStart`)
* Measuring DNS lookup time (`domainLookupEnd` - `domainLookupStart`)
* Measuring redirection time (`redirectEnd` - `redirectStart`)
* Measuring request time (`responseStart` - `requestStart`)
* Measuring TLS negotiation time (`requestStart` - `secureConnectionStart`)
* Measuring time to fetch (without redirects) (`responseEnd` - `fetchStart`)
* Measuring ServiceWorker processing time (`fetchStart` - `workerStart`)
* Checking if content was compressed (`decodedBodySize` should not be `encodedBodySize`)
* Checking if local caches were hit (`transferSize` should be `0`)
* Checking if modern and fast protocols are used (`nextHopProtocol` should be HTTP/2 or HTTP/3)
* Checking if the correct resources are render-blocking (`renderBlockingStatus`)



Instance properties
-------------------


### Inherited from `PerformanceEntry`



This interface extends the following [`PerformanceEntry`](performanceentry) properties for resource performance entry types by qualifying and constraining them as follows:

  
[`PerformanceEntry.duration`](performanceentry/duration) Read only 
  Returns a [`timestamp`](domhighrestimestamp) that is the difference between the [`responseEnd`](performanceresourcetiming/responseend) and the [`startTime`](performanceentry/starttime) properties.

  
[`PerformanceEntry.entryType`](performanceentry/entrytype) Read only 
  Returns `"resource"`.

  
[`PerformanceEntry.name`](performanceentry/name) Read only 
  Returns the resource's URL.

  
[`PerformanceEntry.startTime`](performanceentry/starttime) Read only 
  Returns the [`timestamp`](domhighrestimestamp) for the time a resource fetch started. This value is equivalent to [`PerformanceResourceTiming.fetchStart`](performanceresourcetiming/fetchstart).

  

### Timestamps



The interface supports the following timestamp properties which you can see in the diagram and are listed in the order in which they are recorded for the fetching of a resource. An alphabetical listing is shown in the navigation, at left.

  ![Timestamp diagram listing timestamps in the order in which they are recorded for the fetching of a resource](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming/timestamp-diagram.svg) 

  
[`PerformanceResourceTiming.redirectStart`](performanceresourcetiming/redirectstart) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) that represents the start time of the fetch which initiates the redirect.

  
[`PerformanceResourceTiming.redirectEnd`](performanceresourcetiming/redirectend) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) immediately after receiving the last byte of the response of the last redirect.

  
[`PerformanceResourceTiming.workerStart`](performanceresourcetiming/workerstart) Read only 
  Returns a [`DOMHighResTimeStamp`](domhighrestimestamp) immediately before dispatching the [`FetchEvent`](fetchevent) if a Service Worker thread is already running, or immediately before starting the Service Worker thread if it is not already running. If the resource is not intercepted by a Service Worker the property will always return 0.

  
[`PerformanceResourceTiming.fetchStart`](performanceresourcetiming/fetchstart) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) immediately before the browser starts to fetch the resource.

  
[`PerformanceResourceTiming.domainLookupStart`](performanceresourcetiming/domainlookupstart) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) immediately before the browser starts the domain name lookup for the resource.

  
[`PerformanceResourceTiming.domainLookupEnd`](performanceresourcetiming/domainlookupend) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) representing the time immediately after the browser finishes the domain name lookup for the resource.

  
[`PerformanceResourceTiming.connectStart`](performanceresourcetiming/connectstart) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) immediately before the browser starts to establish the connection to the server to retrieve the resource.

  
[`PerformanceResourceTiming.secureConnectionStart`](performanceresourcetiming/secureconnectionstart) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) immediately before the browser starts the handshake process to secure the current connection.

  
[`PerformanceResourceTiming.connectEnd`](performanceresourcetiming/connectend) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) immediately after the browser finishes establishing the connection to the server to retrieve the resource.

  
[`PerformanceResourceTiming.requestStart`](performanceresourcetiming/requeststart) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) immediately before the browser starts requesting the resource from the server.

  
[`PerformanceResourceTiming.responseStart`](performanceresourcetiming/responsestart) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) immediately after the browser receives the first byte of the response from the server.

  
[`PerformanceResourceTiming.responseEnd`](performanceresourcetiming/responseend) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) immediately after the browser receives the last byte of the resource or immediately before the transport connection is closed, whichever comes first.

  

### Additional resource information



Additionally, this interface exposes the following properties containing more information about a resource:

  
[`PerformanceResourceTiming.decodedBodySize`](performanceresourcetiming/decodedbodysize) Read only 
  A number that is the size (in octets) received from the fetch (HTTP or cache) of the message body, after removing any applied content encoding.

  
[`PerformanceResourceTiming.encodedBodySize`](performanceresourcetiming/encodedbodysize) Read only 
  A number representing the size (in octets) received from the fetch (HTTP or cache), of the payload body, before removing any applied content encodings.

  
[`PerformanceResourceTiming.initiatorType`](performanceresourcetiming/initiatortype) Read only 
  A string representing the web platform feature that initiated the performance entry.

  
[`PerformanceResourceTiming.nextHopProtocol`](performanceresourcetiming/nexthopprotocol) Read only 
  A string representing the network protocol used to fetch the resource, as identified by the [ALPN Protocol ID (RFC7301)](https://datatracker.ietf.org/doc/html/rfc7301).

  
[`PerformanceResourceTiming.renderBlockingStatus`](performanceresourcetiming/renderblockingstatus) Read only 
  A string representing the render-blocking status. Either "`blocking`" or "`non-blocking`".

  
[`PerformanceResourceTiming.responseStatus`](performanceresourcetiming/responsestatus)  Experimental  Read only 
  A number representing the HTTP response status code returned when fetching the resource.

  
[`PerformanceResourceTiming.transferSize`](performanceresourcetiming/transfersize) Read only 
  A number representing the size (in octets) of the fetched resource. The size includes the response header fields plus the response payload body.

  
[`PerformanceResourceTiming.serverTiming`](performanceresourcetiming/servertiming) Read only 
  An array of [`PerformanceServerTiming`](performanceservertiming) entries containing server timing metrics.

  

Instance methods
----------------


 [`PerformanceResourceTiming.toJSON()`](performanceresourcetiming/tojson)  Returns a JSON representation of the `PerformanceResourceTiming` object.

  
Examples
--------


### Logging resource timing information



Example using a [`PerformanceObserver`](performanceobserver), which notifies of new `resource` performance entries as they are recorded in the browser's performance timeline. Use the `buffered` option to access entries from before the observer creation.

 
```
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    console.log(entry);
  });
});

observer.observe({ type: "resource", buffered: true });

```
 Example using [`Performance.getEntriesByType()`](performance/getentriesbytype), which only shows `resource` performance entries present in the browser's performance timeline at the time you call this method:

 
```
const resources = performance.getEntriesByType("resource");
resources.forEach((entry) => {
  console.log(entry);
});

```


Security requirements
---------------------


### Cross-origin timing information



Many of the resource timing properties are restricted to return `0` or an empty string when the resource is a cross-origin request. To expose cross-origin timing information, the [`Timing-Allow-Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Timing-Allow-Origin) HTTP response header needs to be set.

 For example, to allow `https://developer.mozilla.org` to see resource timing information, the cross-origin resource should send:

 
```
Timing-Allow-Origin: https://developer.mozilla.org

```


Specifications
--------------




| Specification |
| --- |
| [Resource Timing # resources-included-in-the-performanceresourcetiming-interface](https://w3c.github.io/resource-timing/#resources-included-in-the-performanceresourcetiming-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PerformanceResourceTiming` | 29 | 12 | 31 | 10 | 16 | 11 | 4.4 | 29 | 31 | 16 | 11 | 2.0 |
| `connectEnd` | 43 | 12 | 31 | 10 | 32 | 11 | 43 | 43 | 31 | 32 | 11 | 4.0 |
| `connectStart` | 43 | 12 | 31 | 10 | 32 | 11 | 43 | 43 | 31 | 32 | 11 | 4.0 |
| `decodedBodySize` | 54 | 17 | 45 | No | 41 | 16.4 | 54 | 54 | 45 | 41 | 16.4 | 6.0 |
| `domainLookupEnd` | 43 | 12 | 31 | 10 | 30 | 11 | 43 | 43 | 31 | 30 | 11 | 4.0 |
| `domainLookupStart` | 43 | 12 | 31 | 10 | 30 | 11 | 43 | 43 | 31 | 30 | 11 | 4.0 |
| `encodedBodySize` | 54 | 17 | 45 | No | 41 | 16.4 | 54 | 54 | 45 | 41 | 16.4 | 6.0 |
| `fetchStart` | 43 | 12 | 31 | 10 | 30 | 11 | 43 | 43 | 31 | 30 | 11 | 4.0 |
| `initiatorType` | 43 | 12 | 31 | 10 | 30 | 11 | 43 | 43 | 31 | 30 | 11 | 4.0 |
| `nextHopProtocol` | 61 | 17 | 45 | No | 48 | 11 | 61 | 61 | 45 | 45 | 11 | 8.0 |
| `redirectEnd` | 43 | 12 | 31 | 10 | 30 | 11 | 43 | 43 | 31 | 30 | 11 | 4.0 |
| `redirectStart` | 43 | 12 | 31 | 10 | 30 | 11 | 43 | 43 | 31 | 30 | 11 | 4.0 |
| `renderBlockingStatus` | 107 | 107 | No | No | 93 | No | 107 | 107 | No | 73 | No | No |
| `requestStart` | 43 | 12 | 31 | 10 | 30 | 11 | 43 | 43 | 31 | 30 | 11 | 4.0 |
| `responseEnd` | 43 | 12 | 31 | 10 | 30 | 11 | 43 | 43 | 31 | 30 | 11 | 4.0 |
| `responseStart` | 43 | 12 | 31 | 10 | 30 | 11 | 43 | 43 | 31 | 30 | 11 | 4.0 |
| `responseStatus` | 109 | 109 | No | No | 95 | No | 109 | 109 | No | 74 | No | No |
| `secureConnectionStart` | 43 | 18 | 31 | No | 30 | 11 | 43 | 43 | 31 | 30 | 11 | 4.0 |
| `serverTiming` | 65 | 79 | 61 | No | 52 | 16.4 | 65 | 65 | 61 | 47 | 16.4 | 9.0 |
| `toJSON` | 45 | 16 | 34 | No | 32 | 11 | 45 | 45 | 34 | 32 | 11 | 5.0 |
| `transferSize` | 54 | 17 | 45 | No | 41 | 16.4 | 54 | 54 | 45 | 41 | 16.4 | 6.0 |
| `workerStart` | 46 | 16 | 58 | No | 32 | 11 | 46 | 46 | 58 | 32 | 11 | 5.0 |
| `worker_support` | 43 | 15 | 60 | No | 32 | 12 | 43 | 43 | 60 | 32 | No | 4.0 |


See also
--------


* [Resource timing (Overview)](performance_api/resource_timing)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming>

Pbkdf2Params
============


The `Pbkdf2Params` dictionary of the [Web Crypto API](web_crypto_api) represents the object that should be passed as the `algorithm` parameter into [`SubtleCrypto.deriveKey()`](subtlecrypto/derivekey), when using the [PBKDF2](subtlecrypto/derivekey#pbkdf2) algorithm.


Instance properties
-------------------


 `name`  A string. This should be set to `PBKDF2`.

  `hash`  A string representing the [digest algorithm](subtlecrypto/digest#supported_algorithms) to use. This may be one of:

 * `SHA-1`
* `SHA-256`
* `SHA-384`
* `SHA-512`

  **Warning:** `SHA-1` is considered vulnerable in most cryptographic applications, but is still considered safe in PBKDF2. However, it's advisable to transition away from it everywhere, so unless you need to use `SHA-1`, don't. Use a different digest algorithm instead.

   `salt`  An [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), a [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), or a [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). This should be a random or pseudo-random value of at least 16 bytes. Unlike the input key material passed into [`deriveKey()`](subtlecrypto/derivekey), `salt` does not need to be kept secret.

  `iterations`  A `Number` representing the number of times the hash function will be executed in `deriveKey()`. This determines how computationally expensive (that is, slow) the `deriveKey()` operation will be. In this context, slow is good, since it makes it more expensive for an attacker to run a dictionary attack against the keys. The general guidance here is to use as many iterations as possible, subject to keeping an acceptable level of performance for your application.

  
Examples
--------


See the examples for [`SubtleCrypto.deriveKey()`](subtlecrypto/derivekey).


Specifications
--------------




| Specification |
| --- |
| [Web Cryptography API # dfn-Pbkdf2Params](https://w3c.github.io/webcrypto/#dfn-Pbkdf2Params) |


Browser compatibility
---------------------


See also
--------


* [`SubtleCrypto.deriveKey()`](subtlecrypto/derivekey).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Pbkdf2Params>

PerformanceEntry
================



 **Note:** This feature is available in [Web Workers](web_workers_api)

  The `PerformanceEntry` object encapsulates a single performance metric that is part of the browser's performance timeline.

 The Performance API offers built-in metrics which are specialized subclasses of `PerformanceEntry`. This includes entries for resource loading, event timing, [first input delay](https://developer.mozilla.org/en-US/docs/Glossary/First_input_delay) (FID), and more.

 A performance entry can also be created by calling the [`Performance.mark()`](performance/mark) or [`Performance.measure()`](performance/measure) methods at an explicit point in an application. This allows you to add your own metrics to the performance timeline.

 The `PerformanceEntry` instances will always be one of the following subclasses:

 * [`LargestContentfulPaint`](largestcontentfulpaint)
* [`LayoutShift`](layoutshift)
* [`PerformanceEventTiming`](performanceeventtiming)
* [`PerformanceLongTaskTiming`](performancelongtasktiming)
* [`PerformanceMark`](performancemark)
* [`PerformanceMeasure`](performancemeasure)
* [`PerformanceNavigationTiming`](performancenavigationtiming)
* [`PerformancePaintTiming`](performancepainttiming)
* [`PerformanceResourceTiming`](performanceresourcetiming)
* [`PerformanceServerTiming`](performanceservertiming)
* [`TaskAttributionTiming`](taskattributiontiming)



Instance properties
-------------------


 
[`PerformanceEntry.name`](performanceentry/name) Read only 
  A string representing the name for a performance entry. The value depends on the subtype.

  
[`PerformanceEntry.entryType`](performanceentry/entrytype) Read only 
  A string representing the type of performance metric. For example, "`mark`" when [`PerformanceMark`](performancemark) is used.

  
[`PerformanceEntry.startTime`](performanceentry/starttime) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) representing the starting time for the performance metric.

  
[`PerformanceEntry.duration`](performanceentry/duration) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) representing the duration of the performance entry.

  
Instance methods
----------------


 [`PerformanceEntry.toJSON()`](performanceentry/tojson)  Returns a JSON representation of the `PerformanceEntry` object.

  
Example
-------


### Working with performance entries



 The following example creates `PerformanceEntry` objects that are of the types [`PerformanceMark`](performancemark) and [`PerformanceMeasure`](performancemeasure). The `PerformanceMark` and `PerformanceMeasure` subclasses inherit the `duration`, `entryType`, `name`, and `startTime` properties from `PerformanceEntry` and set them to their appropriate values. 

 
```
// Place at a location in the code that starts login
performance.mark("login-started");

// Place at a location in the code that finishes login
performance.mark("login-finished");

// Measure login duration
performance.measure("login-duration", "login-started", "login-finished");

function perfObserver(list, observer) {
  list.getEntries().forEach((entry) => {
    if (entry.entryType === "mark") {
      console.log(`${entry.name}'s startTime: ${entry.startTime}`);
    }
    if (entry.entryType === "measure") {
      console.log(`${entry.name}'s duration: ${entry.duration}`);
    }
  });
}
const observer = new PerformanceObserver(perfObserver);
observer.observe({ entryTypes: ["measure", "mark"] });

```


Specifications
--------------




| Specification |
| --- |
| [Performance Timeline # dom-performanceentry](https://w3c.github.io/performance-timeline/#dom-performanceentry) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PerformanceEntry` | 4625 | 12 | 35 | 10 | 3315 | 11 | 464.4 | 4625 | 35 | 3314 | 11 | 5.01.5 |
| `duration` | 28 | 12 | 35 | 10 | 15 | 11 | 4.4 | 28 | 35 | 14 | 11 | 1.5 |
| `entryType` | 28 | 12 | 35 | 10 | 15 | 11 | 4.4 | 28 | 35 | 14 | 11 | 1.5 |
| `name` | 28 | 12 | 35 | 10 | 15 | 11 | 4.4 | 28 | 35 | 14 | 11 | 1.5 |
| `startTime` | 28 | 12 | 35 | 10 | 15 | 11 | 4.4 | 28 | 35 | 14 | 11 | 1.5 |
| `toJSON` | 45 | 16 | 35 | No | 32 | 11 | 45 | 45 | 35 | 32 | 11 | 5.0 |
| `worker_support` | 62 | 15 | 60 | No | 49 | 11 | 62 | 62 | 60 | 46 | 11 | 8.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry>

PerformanceEventTiming
======================


The `PerformanceEventTiming` interface of the Event Timing API provides insights into the latency of certain event types triggered by user interaction.


Description
-----------



This API enables visibility into slow events by providing event timestamps and duration for certain event types ([see below](#events_exposed)). For example, you can monitor the time between a user action and the start of its event handler, or the time an event handler takes to run.

 This API is particularly useful for measuring the [first input delay](https://developer.mozilla.org/en-US/docs/Glossary/First_input_delay) (FID): the time from the point when a user first interacts with your app to the point when the browser is actually able to respond to that interaction.

 You typically work with `PerformanceEventTiming` objects by creating a [`PerformanceObserver`](performanceobserver) instance and then calling its [`observe()`](performanceobserver/observe) method, passing in `"event"` or `"first-input"` as the value of the [`type`](performanceentry/entrytype) option. The `PerformanceObserver` object's callback will then be called with a list of `PerformanceEventTiming` objects which you can analyze. See the [example below](#getting_event_timing_information) for more.

  By default, `PerformanceEventTiming` entries are exposed when their `duration` is 104ms or greater. Research suggests that user input that is not handled within 100ms is considered slow and 104ms is the first multiple of 8 greater than 100ms (for security reasons, this API is rounded to the nearest multiple of 8ms). However, you can set the [`PerformanceObserver`](performanceobserver) to a different threshold using the `durationThreshold` option in the [`observe()`](performanceobserver/observe) method. 

 This interface inherits methods and properties from its parent, [`PerformanceEntry`](performanceentry):


 PerformanceEntry PerformanceEventTiming

### Events exposed



The following event types are exposed by the Event Timing API:

 

|  |  |
| --- | --- |
| Click events | [`auxclick`](element/auxclick_event), [`click`](element/click_event), [`contextmenu`](element/contextmenu_event), [`dblclick`](element/dblclick_event) |
| Composition events | [`compositionend`](element/compositionend_event), [`compositionstart`](element/compositionstart_event), [`compositionupdate`](element/compositionupdate_event) |
| Drag & drop events | [`dragend`](htmlelement/dragend_event), [`dragenter`](htmlelement/dragenter_event), [`dragleave`](htmlelement/dragleave_event), [`dragover`](htmlelement/dragover_event), [`dragstart`](htmlelement/dragstart_event), [`drop`](htmlelement/drop_event) |
| Input events | [`beforeinput`](htmlelement/beforeinput_event), [`input`](htmlelement/input_event) |
| Keyboard events | [`keydown`](element/keydown_event), [`keypress`](element/keypress_event), [`keyup`](element/keyup_event) |
| Mouse events | [`mousedown`](element/mousedown_event), [`mouseenter`](element/mouseenter_event), [`mouseleave`](element/mouseleave_event), [`mouseout`](element/mouseout_event), [`mouseover`](element/mouseover_event), [`mouseup`](element/mouseup_event) |
| Pointer events | [`pointerover`](element/pointerover_event), [`pointerenter`](element/pointerenter_event), [`pointerdown`](element/pointerdown_event), [`pointerup`](element/pointerup_event), [`pointercancel`](element/pointercancel_event), [`pointerout`](element/pointerout_event), [`pointerleave`](element/pointerleave_event), [`gotpointercapture`](element/gotpointercapture_event), [`lostpointercapture`](element/lostpointercapture_event) |
| Touch events | [`touchstart`](element/touchstart_event), [`touchend`](element/touchend_event), [`touchcancel`](element/touchcancel_event) |

  Note that the following events are not included in the list because they are continuous events and no meaningful event counts or performance metrics can be obtained at this point: [`mousemove`](element/mousemove_event), [`pointermove`](element/pointermove_event), `pointerrawupdate`, [`touchmove`](element/touchmove_event), [`wheel`](element/wheel_event), [`drag`](htmlelement/drag_event). 

 To get a list of all exposed events, you can also look up keys in the [`performance.eventCounts`](performance/eventcounts) map:

 
```
const exposedEventsList = [...performance.eventCounts.keys()];

```


Constructor
-----------


This interface has no constructor on its own. See the [example below](#getting_event_timing_information) for how to typically get the information the `PerformanceEventTiming` interface holds.


Instance properties
-------------------



This interface extends the following [`PerformanceEntry`](performanceentry) properties for event timing performance entry types by qualifying them as follows:

  
[`PerformanceEntry.duration`](performanceentry/duration) Read only 
  Returns a [`DOMHighResTimeStamp`](domhighrestimestamp) representing the time from `startTime` to the next rendering paint (rounded to the nearest 8ms).

  
[`PerformanceEntry.entryType`](performanceentry/entrytype) Read only 
  Returns `"event"` (for long events) or `"first-input"` (for the first user interaction).

  
[`PerformanceEntry.name`](performanceentry/name) Read only 
  Returns the associated event's type.

  
[`PerformanceEntry.startTime`](performanceentry/starttime) Read only 
  Returns a [`DOMHighResTimeStamp`](domhighrestimestamp) representing the associated event's [`timestamp`](event/timestamp) property. This is the time the event was created and can be considered as a proxy for the time the user interaction occurred.

   This interface also supports the following properties:

  
[`PerformanceEventTiming.cancelable`](performanceeventtiming/cancelable) Read only 
  Returns the associated event's [`cancelable`](event/cancelable) property.

  
[`PerformanceEventTiming.interactionId`](performanceeventtiming/interactionid) Read only   Experimental 
  Returns the ID that uniquely identifies the user interaction which triggered the associated event.

  
[`PerformanceEventTiming.processingStart`](performanceeventtiming/processingstart) Read only 
  Returns a [`DOMHighResTimeStamp`](domhighrestimestamp) representing the time at which event dispatch started. To measure the time between a user action and the time the event handler starts to run, calculate `processingStart-startTime`.

  
[`PerformanceEventTiming.processingEnd`](performanceeventtiming/processingend) Read only 
  Returns a [`DOMHighResTimeStamp`](domhighrestimestamp) representing the time at which the event dispatch ended. To measure the time the event handler took to run, calculate `processingEnd-processingStart`.

  
[`PerformanceEventTiming.target`](performanceeventtiming/target) Read only 
  Returns the associated event's last target, if it is not removed.

  

Instance methods
----------------


 [`PerformanceEventTiming.toJSON()`](performanceeventtiming/tojson)  Returns a JSON representation of the `PerformanceEventTiming` object.

  
Examples
--------


### Getting event timing information



To get event timing information, create a [`PerformanceObserver`](performanceobserver) instance and then call its [`observe()`](performanceobserver/observe) method, passing in `"event"` or `"first-input"` as the value of the [`type`](performanceentry/entrytype) option. You also need to set `buffered` to `true` to get access to events the user agent buffered while constructing the document. The `PerformanceObserver` object's callback will then be called with a list of `PerformanceEventTiming` objects which you can analyze.

 
```
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    // Full duration
    const duration = entry.duration;

    // Input delay (before processing event)
    const delay = entry.processingStart - entry.startTime;

    // Synchronous event processing time
    // (between start and end dispatch)
    const eventHandlerTime = entry.processingEnd - entry.processingStart;
    console.log(`Total duration: ${duration}`);
    console.log(`Event delay: ${delay}`);
    console.log(`Event handler duration: ${eventHandlerTime}`);
  });
});

// Register the observer for events
observer.observe({ type: "event", buffered: true });

```
 You can also set a different [`durationThreshold`](performanceobserver/observe#durationthreshold). The default is 104ms and the minimum possible duration threshold is 16ms.

 
```
observer.observe({ type: "event", durationThreshold: 16, buffered: true });

```


### Reporting the First Input Delay (FID)



The [first input delay](https://developer.mozilla.org/en-US/docs/Glossary/First_input_delay) or FID, measures the time from when a user first interacts with a page (i.e. when they click a link or tap on a button) to the time when the browser is actually able to begin processing event handlers in response to that interaction.

 
```
// Keep track of whether (and when) the page was first hidden, see:
// https://github.com/w3c/page-visibility/issues/29
// NOTE: ideally this check would be performed in the document <head>
// to avoid cases where the visibility state changes before this code runs.
let firstHiddenTime = document.visibilityState === "hidden" ? 0 : Infinity;
document.addEventListener(
  "visibilitychange",
  (event) => {
    firstHiddenTime = Math.min(firstHiddenTime, event.timeStamp);
  },
  { once: true }
);

// Sends the passed data to an analytics endpoint. This code
// uses `/analytics`; you can replace it with your own URL.
function sendToAnalytics(data) {
  const body = JSON.stringify(data);
  // Use `navigator.sendBeacon()` if available,
  // falling back to `fetch()`.
  (navigator.sendBeacon && navigator.sendBeacon("/analytics", body)) ||
    fetch("/analytics", { body, method: "POST", keepalive: true });
}

// Use a try/catch instead of feature detecting `first-input`
// support, since some browsers throw when using the new `type` option.
// https://webkit.org/b/209216
try {
  function onFirstInputEntry(entry) {
    // Only report FID if the page wasn't hidden prior to
    // the entry being dispatched. This typically happens when a
    // page is loaded in a background tab.
    if (entry.startTime < firstHiddenTime) {
      const fid = entry.processingStart - entry.startTime;

      // Report the FID value to an analytics endpoint.
      sendToAnalytics({ fid });
    }
  }

  // Create a PerformanceObserver that calls
  // `onFirstInputEntry` for each entry.
  const po = new PerformanceObserver((entryList) => {
    entryList.getEntries().forEach(onFirstInputEntry);
  });

  // Observe entries of type `first-input`, including buffered entries,
  // i.e. entries that occurred before calling `observe()` below.
  po.observe({
    type: "first-input",
    buffered: true,
  });
} catch (e) {
  // Do nothing if the browser doesn't support this API.
}

```


Specifications
--------------




| Specification |
| --- |
| [Event Timing API # sec-performance-event-timing](https://w3c.github.io/event-timing/#sec-performance-event-timing) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PerformanceEventTiming` | 76 | 79 | 89 | No | 63 | No | 76 | 76 | 89 | 54 | No | 12.0 |
| `cancelable` | 76 | 79 | 89 | No | 63 | No | 76 | 76 | 89 | 54 | No | 12.0 |
| `interactionId` | 96 | 96 | No | No | 82 | No | 96 | 96 | No | 67 | No | 17.0 |
| `processingEnd` | 76 | 79 | 89 | No | 63 | No | 76 | 76 | 89 | 54 | No | 12.0 |
| `processingStart` | 76 | 79 | 89 | No | 63 | No | 76 | 76 | 89 | 54 | No | 12.0 |
| `target` | 85 | 85 | 89 | No | 71 | No | 85 | 85 | 89 | 60 | No | 14.0 |
| `toJSON` | 76 | 79 | 89 | No | 63 | No | 76 | 76 | 89 | 54 | No | 12.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEventTiming>

PerformanceMeasure
==================



`PerformanceMeasure` is an *abstract* interface for [`PerformanceEntry`](performanceentry) objects with an [`entryType`](performanceentry/entrytype) of "`measure`". Entries of this type are created by calling [`performance.measure()`](performance/measure) to add a *named* [`DOMHighResTimeStamp`](domhighrestimestamp) (the *measure*) between two *marks* to the browser's *performance timeline*.


 PerformanceEntry PerformanceMeasure  **Note:** This feature is available in [Web Workers](web_workers_api)

 

Instance properties
-------------------



This interface defines:

  [`PerformanceMeasure.detail`](performancemeasure/detail)  Contains arbitrary metadata about the measure.

   In addition, it extends the following [`PerformanceEntry`](performanceentry) properties by qualifying/constraining the properties as follows:

  [`PerformanceEntry.entryType`](performanceentry/entrytype)  Returns "`measure`".

  [`PerformanceEntry.name`](performanceentry/name)  Returns the name given to the measure when it was created via a call to [`performance.measure()`](performance/measure).

  [`PerformanceEntry.startTime`](performanceentry/starttime)  Returns a [`timestamp`](domhighrestimestamp) given to the measure when [`performance.measure()`](performance/measure) was called.

  [`PerformanceEntry.duration`](performanceentry/duration)  Returns a [`DOMHighResTimeStamp`](domhighrestimestamp) that is the duration of the measure (typically, the measure's end mark timestamp minus its start mark timestamp).

  

Instance methods
----------------


This interface has no methods.


Example
-------


See the example in [Using the User Timing API](performance_api/user_timing).


Specifications
--------------




| Specification |
| --- |
| [User Timing # performancemeasure](https://w3c.github.io/user-timing/#performancemeasure) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PerformanceMeasure` | 25 | 12 | 38 | 10 | 33 | 11 | 4.4 | 25 | 38 | 33 | 11 | 1.5 |
| `detail` | 78 | 79 | 103 | No | 65 | 14.1 | 78 | 78 | 103 | 56 | 14.5 | 12.0 |


See also
--------


* [User Timing (Overview)](performance_api/user_timing)
* [Using the User Timing API](performance_api/user_timing)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PerformanceMeasure>

PerformanceObserver
===================



 **Note:** This feature is available in [Web Workers](web_workers_api)

  The `PerformanceObserver` interface is used to observe performance measurement events and be notified of new [performance entries](performanceentry) as they are recorded in the browser's *performance timeline*.



Constructor
-----------


 [`PerformanceObserver()`](performanceobserver/performanceobserver)  Creates and returns a new `PerformanceObserver` object.

  
Static properties
-----------------


 
[`PerformanceObserver.supportedEntryTypes`](performanceobserver/supportedentrytypes) Read only 
  Returns an array of the [`entryType`](performanceentry/entrytype) values supported by the user agent.

  
Instance methods
----------------


 [`PerformanceObserver.observe()`](performanceobserver/observe)  Specifies the set of entry types to observe. The performance observer's callback function will be invoked when performance entry is recorded for one of the specified `entryTypes`.

  [`PerformanceObserver.disconnect()`](performanceobserver/disconnect)  Stops the performance observer callback from receiving performance entries.

  [`PerformanceObserver.takeRecords()`](performanceobserver/takerecords)  Returns the current list of performance entries stored in the performance observer, emptying it out.

  
Examples
--------


### Creating a PerformanceObserver



 The following example creates a `PerformanceObserver` watching for "mark" ([`PerformanceMark`](performancemark)) and "measure" ([`PerformanceMeasure`](performancemeasure)) events. The `perfObserver` callback provides a `list` ([`PerformanceObserverEntryList`](performanceobserverentrylist)) which allows you to get observed performance entries. 

 
```
function perfObserver(list, observer) {
  list.getEntries().forEach((entry) => {
    if (entry.entryType === "mark") {
      console.log(`${entry.name}'s startTime: ${entry.startTime}`);
    }
    if (entry.entryType === "measure") {
      console.log(`${entry.name}'s duration: ${entry.duration}`);
    }
  });
}
const observer = new PerformanceObserver(perfObserver);
observer.observe({ entryTypes: ["measure", "mark"] });

```


Specifications
--------------




| Specification |
| --- |
| [Performance Timeline # dom-performanceobserver](https://w3c.github.io/performance-timeline/#dom-performanceobserver) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PerformanceObserver` | 52 | 79 | 57 | No | 39 | 11 | 52 | 52 | 57 | 41 | 11 | 6.0 |
| `PerformanceObserver` | 52 | 79 | 57 | No | 39 | 11 | 52 | 52 | 57 | 41 | 11 | 6.0 |
| `disconnect` | 52 | 79 | 57 | No | 39 | 11 | 52 | 52 | 57 | 41 | 11 | 6.0 |
| `observe` | 52 | 79 | 57 | No | 39 | 11 | 52 | 52 | 57 | 41 | 11 | 6.0 |
| `supportedEntryTypes` | 73 | 79 | 68 | No | 60 | 13 | 73 | 73 | 68 | 52 | 13 | 11.0 |
| `takeRecords` | 65 | 79 | 60 | No | 52 | 15 | 65 | 65 | 60 | 47 | 15 | 9.0 |
| `worker_support` | 62 | 79 | 57 | No | 49 | 11 | 62 | 62 | 57 | 46 | 11 | 8.0 |


See also
--------


* [`MutationObserver`](mutationobserver)
* [`ResizeObserver`](resizeobserver)
* [`IntersectionObserver`](intersectionobserver)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserver>

PerformanceObserverEntryList
============================


The `PerformanceObserverEntryList` interface is a list of [performance events](performanceentry) that were explicitly observed via the [`observe()`](performanceobserver/observe) method.


Instance methods
----------------


 [`PerformanceObserverEntryList.getEntries()`](performanceobserverentrylist/getentries)  Returns a list of all explicitly observed [`PerformanceEntry`](performanceentry) objects.

  [`PerformanceObserverEntryList.getEntriesByType()`](performanceobserverentrylist/getentriesbytype)  Returns a list of all explicitly observed [`PerformanceEntry`](performanceentry) objects of the given entry type.

  [`PerformanceObserverEntryList.getEntriesByName()`](performanceobserverentrylist/getentriesbyname)  Returns a list of all explicitly observed [`PerformanceEntry`](performanceentry) objects based on the given name and entry type.

  
Example
-------


### Using PerformanceObserverEntryList



In the following example, `list` is the `PerformanceObserverEntryList` object. The [`getEntries()`](performanceobserverentrylist/getentries) method is called to get all explicitly observed [`PerformanceEntry`](performanceentry) objects which are "measure" and "mark" in this case.

 
```
function perfObserver(list, observer) {
  list.getEntries().forEach((entry) => {
    if (entry.entryType === "mark") {
      console.log(`${entry.name}'s startTime: ${entry.startTime}`);
    }
    if (entry.entryType === "measure") {
      console.log(`${entry.name}'s duration: ${entry.duration}`);
    }
  });
}
const observer = new PerformanceObserver(perfObserver);
observer.observe({ entryTypes: ["measure", "mark"] });

```


Specifications
--------------




| Specification |
| --- |
| [Performance Timeline # performanceobserverentrylist-interface](https://w3c.github.io/performance-timeline/#performanceobserverentrylist-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PerformanceObserverEntryList` | 52 | 79 | 57 | No | 39 | 11 | 52 | 52 | 57 | 41 | 11 | 6.0 |
| `getEntries` | 52 | 79 | 57 | No | 39 | 11 | 52 | 52 | 57 | 41 | 11 | 6.0 |
| `getEntriesByName` | 52 | 79 | 57 | No | 39 | 11 | 52 | 52 | 57 | 41 | 11 | 6.0 |
| `getEntriesByType` | 52 | 79 | 57 | No | 39 | 11 | 52 | 52 | 57 | 41 | 11 | 6.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserverEntryList>

PerformanceServerTiming
=======================



 **Note:** This feature is available in [Web Workers](web_workers_api)

  **Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `PerformanceServerTiming` interface surfaces server metrics that are sent with the response in the [`Server-Timing`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Server-Timing) HTTP header.

 This interface is restricted to the same origin, but you can use the [`Timing-Allow-Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Timing-Allow-Origin) header to specify the domains that are allowed to access the server metrics. Note that this interface is only available in secure contexts (HTTPS) in some browsers.



Instance properties
-------------------


 
[`PerformanceServerTiming.description`](performanceservertiming/description) Read only 
  A string value of the server-specified metric description, or an empty string.

  
[`PerformanceServerTiming.duration`](performanceservertiming/duration) Read only 
  A double that contains the server-specified metric duration, or value `0.0`.

  
[`PerformanceServerTiming.name`](performanceservertiming/name) Read only 
  A string value of the server-specified metric name.

  
Instance methods
----------------


 [`PerformanceServerTiming.toJSON()`](performanceservertiming/tojson)  Returns a JSON representation of the `PerformanceServerTiming` object.

  
Example
-------



Given a server that sends the [`Server-Timing`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Server-Timing) header, for example a Node.js server like this:

 
```
const http = require("http");

function requestHandler(request, response) {
  const headers = {
    "Server-Timing": `
 cache;desc="Cache Read";dur=23.2,
 db;dur=53,
 app;dur=47.2
 `.replace(/\n/g, ""),
  };
  response.writeHead(200, headers);
  response.write("");
  return setTimeout(() => {
    response.end();
  }, 1000);
}

http.createServer(requestHandler).listen(3000).on("error", console.error);

```
 The `PerformanceServerTiming` entries are now observable from JavaScript via the [`PerformanceResourceTiming.serverTiming`](performanceresourcetiming/servertiming) property and live on `navigation` and `resource` entries.

 Example using a [`PerformanceObserver`](performanceobserver), which notifies of new `navigation` and `resource` performance entries as they are recorded in the browser's performance timeline. Use the `buffered` option to access entries from before the observer creation.

 
```
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    entry.serverTiming.forEach((serverEntry) => {
      console.log(
        `${serverEntry.name} (${serverEntry.description}) duration: ${serverEntry.duration}`
      );
      // Logs "cache (Cache Read) duration: 23.2"
      // Logs "db () duration: 53"
      // Logs "app () duration: 47.2"
    });
  });
});

["navigation", "resource"].forEach((type) =>
  observer.observe({ type, buffered: true })
);

```
 Example using [`Performance.getEntriesByType()`](performance/getentriesbytype), which only shows `navigation` and `resource` performance entries present in the browser's performance timeline at the time you call this method:

 
```
for (const entryType of ["navigation", "resource"]) {
  for (const { name: url, serverTiming } of performance.getEntriesByType(
    entryType
  )) {
    if (serverTiming) {
      for (const { name, description, duration } of serverTiming) {
        console.log(`${name} (${description}) duration: ${duration}`);
        // Logs "cache (Cache Read) duration: 23.2"
        // Logs "db () duration: 53"
        // Logs "app () duration: 47.2"
      }
    }
  }
}

```


Specifications
--------------




| Specification |
| --- |
| [Server Timing # the-performanceservertiming-interface](https://w3c.github.io/server-timing/#the-performanceservertiming-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PerformanceServerTiming` | 65 | 79 | 61 | No | 52 | 16.4 | 65 | 65 | 61 | 47 | 16.4 | 9.0 |
| `description` | 65 | 79 | 61 | No | 52 | 16.4 | 65 | 65 | 61 | 47 | 16.4 | 9.0 |
| `duration` | 65 | 79 | 61 | No | 52 | 16.4 | 65 | 65 | 61 | 47 | 16.4 | 9.0 |
| `name` | 65 | 79 | 61 | No | 52 | 16.4 | 65 | 65 | 61 | 47 | 16.4 | 9.0 |
| `toJSON` | 65 | 79 | 61 | No | 52 | 16.4 | 65 | 65 | 61 | 47 | 16.4 | 9.0 |


See also
--------


* [`Server-Timing`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Server-Timing)
* [`PerformanceResourceTiming.serverTiming`](performanceresourcetiming/servertiming)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PerformanceServerTiming>

PerformanceTiming
=================



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

  **Warning:** This interface is deprecated in the [Navigation Timing Level 2 specification](https://w3c.github.io/navigation-timing/#obsolete). Please use the [`PerformanceNavigationTiming`](performancenavigationtiming) interface instead.

  The `PerformanceTiming` interface is a legacy interface kept for backwards compatibility and contains properties that offer performance timing information for various events which occur during the loading and use of the current page. You get a `PerformanceTiming` object describing your page using the [`window.performance.timing`](performance/timing) property.



Instance properties
-------------------



*The `PerformanceTiming` interface doesn't inherit any properties.*

 These properties each describe the time at which a particular point in the page loading process was reached. Some correspond to DOM events; others describe the time at which internal browser operations of interest took place.

 Each time is provided as a number representing the moment, in milliseconds since the UNIX epoch.

 These properties are listed in the order in which they occur during the navigation process.

  
[`PerformanceTiming.navigationStart`](performancetiming/navigationstart) Read only   Deprecated 
  When the prompt for unload terminates on the previous document in the same browsing context. If there is no previous document, this value will be the same as `PerformanceTiming.fetchStart`.

  
[`PerformanceTiming.unloadEventStart`](performancetiming/unloadeventstart) Read only   Deprecated 
  When the [`unload`](window/unload_event) event has been thrown, indicating the time at which the previous document in the window began to unload. If there is no previous document, or if the previous document or one of the needed redirects is not of the same origin, the value returned is `0`.

  
[`PerformanceTiming.unloadEventEnd`](performancetiming/unloadeventend) Read only   Deprecated 
  When the [`unload`](window/unload_event) event handler finishes. If there is no previous document, or if the previous document, or one of the needed redirects, is not of the same origin, the value returned is `0`.

  
[`PerformanceTiming.redirectStart`](performancetiming/redirectstart) Read only   Deprecated 
  When the first HTTP redirect starts. If there is no redirect, or if one of the redirects is not of the same origin, the value returned is `0`.

  
[`PerformanceTiming.redirectEnd`](performancetiming/redirectend) Read only   Deprecated 
  When the last HTTP redirect is completed, that is when the last byte of the HTTP response has been received. If there is no redirect, or if one of the redirects is not of the same origin, the value returned is `0`.

  
[`PerformanceTiming.fetchStart`](performancetiming/fetchstart) Read only   Deprecated 
  When the browser is ready to fetch the document using an HTTP request. This moment is *before* the check to any application cache.

  
[`PerformanceTiming.domainLookupStart`](performancetiming/domainlookupstart) Read only   Deprecated 
  When the domain lookup starts. If a persistent connection is used, or the information is stored in a cache or a local resource, the value will be the same as `PerformanceTiming.fetchStart`.

  
[`PerformanceTiming.domainLookupEnd`](performancetiming/domainlookupend) Read only   Deprecated 
  When the domain lookup is finished. If a persistent connection is used, or the information is stored in a cache or a local resource, the value will be the same as `PerformanceTiming.fetchStart`.

  
[`PerformanceTiming.connectStart`](performancetiming/connectstart) Read only   Deprecated 
  When the request to open a connection is sent to the network. If the transport layer reports an error and the connection establishment is started again, the last connection establishment start time is given. If a persistent connection is used, the value will be the same as `PerformanceTiming.fetchStart`.

  
[`PerformanceTiming.connectEnd`](performancetiming/connectend) Read only   Deprecated 
  When the connection is opened network. If the transport layer reports an error and the connection establishment is started again, the last connection establishment end time is given. If a persistent connection is used, the value will be the same as `PerformanceTiming.fetchStart`. A connection is considered as opened when all secure connection handshake, or SOCKS authentication, is terminated.

  
[`PerformanceTiming.secureConnectionStart`](performancetiming/secureconnectionstart) Read only   Deprecated 
  When the secure connection handshake starts. If no such connection is requested, it returns `0`.

  
[`PerformanceTiming.requestStart`](performancetiming/requeststart) Read only   Deprecated 
  When the browser sent the request to obtain the actual document, from the server or from a cache. If the transport layer fails after the start of the request and the connection is reopened, this property will be set to the time corresponding to the new request.

  
[`PerformanceTiming.responseStart`](performancetiming/responsestart) Read only   Deprecated 
  When the browser received the first byte of the response, from the server from a cache, or from a local resource.

  
[`PerformanceTiming.responseEnd`](performancetiming/responseend) Read only   Deprecated 
  When the browser received the last byte of the response, or when the connection is closed if this happened first, from the server, the cache, or from a local resource.

  
[`PerformanceTiming.domLoading`](performancetiming/domloading) Read only   Deprecated 
  When the parser started its work, that is when its [`Document.readyState`](document/readystate) changes to `'loading'` and the corresponding [`readystatechange`](document/readystatechange_event) event is thrown.

  
[`PerformanceTiming.domInteractive`](performancetiming/dominteractive) Read only   Deprecated 
  When the parser finished its work on the main document, that is when its [`Document.readyState`](document/readystate) changes to `'interactive'` and the corresponding [`readystatechange`](document/readystatechange_event) event is thrown.

  
[`PerformanceTiming.domContentLoadedEventStart`](performancetiming/domcontentloadedeventstart) Read only   Deprecated 
  Right before the parser sent the [`DOMContentLoaded`](document/domcontentloaded_event) event, that is right after all the scripts that need to be executed right after parsing have been executed.

  
[`PerformanceTiming.domContentLoadedEventEnd`](performancetiming/domcontentloadedeventend) Read only   Deprecated 
  Right after all the scripts that need to be executed as soon as possible, in order or not, have been executed.

  
[`PerformanceTiming.domComplete`](performancetiming/domcomplete) Read only   Deprecated 
  When the parser finished its work on the main document, that is when its [`Document.readyState`](document/readystate) changes to `'complete'` and the corresponding [`readystatechange`](document/readystatechange_event) event is thrown.

  
[`PerformanceTiming.loadEventStart`](performancetiming/loadeventstart) Read only   Deprecated 
  When the [`load`](window/load_event) event was sent for the current document. If this event has not yet been sent, it returns `0.`

  
[`PerformanceTiming.loadEventEnd`](performancetiming/loadeventend) Read only   Deprecated 
  When the [`load`](window/load_event) event handler terminated, that is when the load event is completed. If this event has not yet been sent, or is not yet completed, it returns `0.`

  

Instance methods
----------------



*The `PerformanceTiming`* *interface doesn't inherit any methods.*

  
[`PerformanceTiming.toJSON()`](performancetiming/tojson)  Deprecated 
  Returns a [JSON object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON) representing this `PerformanceTiming` object.

  

Specifications
--------------


 This feature is no longer on track to become a standard, as the [Navigation Timing specification](https://w3c.github.io/navigation-timing/#obsolete) has marked it as deprecated. Use the [`PerformanceNavigationTiming`](performancenavigationtiming) interface instead. 


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PerformanceTiming` | 6 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `connectEnd` | 6 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `connectStart` | 6 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `domComplete` | 6 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `domContentLoadedEventEnd` | 6 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `domContentLoadedEventStart` | 6 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `domInteractive` | 6 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `domLoading` | 6 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `domainLookupEnd` | 6 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `domainLookupStart` | 6 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `fetchStart` | 6 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `loadEventEnd` | 6 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `loadEventStart` | 6 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `navigationStart` | 6 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `redirectEnd` | 6 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `redirectStart` | 6 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `requestStart` | 6 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `responseEnd` | 6 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `responseStart` | 6 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `secureConnectionStart` | 6 | 18 | 56 | 9 | 15 | 8 | ≤37 | 18 | 56 | 14 | 9 | 1.0 |
| `toJSON` | 44 | 12 | 25 | 9 | 32 | 10.1 | 44 | 44 | 25 | 32 | 10.3 | 4.0 |
| `unloadEventEnd` | 6 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |
| `unloadEventStart` | 6 | 12 | 7 | 9 | 15 | 8 | ≤37 | 18 | 7 | 14 | 9 | 1.0 |


See also
--------


* The [`Performance.timing`](performance/timing) property that creates such an object.
* [`PerformanceNavigationTiming`](performancenavigationtiming) (part of Navigation Timing Level 2) that has superseded this API.


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PerformanceTiming>

PeriodicSyncEvent
=================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `PeriodicSyncEvent` interface of the [`Web Periodic Background Synchronization API`](web_periodic_background_synchronization_api) provides a way to run tasks in the service worker with network connectivity.

 An instance of this event is passed to the [`periodicsync`](serviceworkerglobalscope/periodicsync_event) handler. This happens periodically, at an interval greater than or equal to that set in the [`PeriodicSyncManager.register()`](periodicsyncmanager/register) method. Other implementation-specific factors such as the user's engagement with the site decide the actual interval.


 Event ExtendableEvent PeriodicSyncEvent

Constructor
-----------


 
[`PeriodicSyncEvent.PeriodicSyncEvent()`](periodicsyncevent/periodicsyncevent)  Experimental 
  Creates a new `PeriodicSyncEvent` object. This constructor is not typically used. The browser creates these objects itself and provides them to [`onperiodicsync`](serviceworkerglobalscope/periodicsync_event) callback.

  
Instance properties
-------------------


 
[`PeriodicSyncEvent.tag`](periodicsyncevent/tag) Read only   Experimental 
  Returns the developer-defined identifier for this `PeriodicSyncEvent`. Multiple tags can be used by the web app to run different periodic tasks at different frequencies.

  
Instance methods
----------------


Inherits methods from its parent [`ExtendableEvent`](extendableevent).


Examples
--------



The following example shows how to respond to a periodic sync event in the service worker.

 
```
self.addEventListener("periodicsync", (event) => {
  if (event.tag === "get-latest-news") {
    event.waitUntil(fetchAndCacheLatestNews());
  }
});

```
 `fetchAndCacheLatestNews` is a developer defined function.



Specifications
--------------




| Specification |
| --- |
| [Web Periodic Background Synchronization # periodicsync-event](https://wicg.github.io/periodic-background-sync/#periodicsync-event) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PeriodicSyncEvent` | 80 | 80 | No | No | 67 | No | No | 80 | No | 57 | No | 13.0 |
| `PeriodicSyncEvent` | 80 | 80 | No | No | 67 | No | No | 80 | No | 57 | No | 13.0 |
| `tag` | 80 | 80 | No | No | 67 | No | No | 80 | No | 57 | No | 13.0 |


See also
--------


* [Richer offline experiences with the Periodic Background Sync API](https://web.dev/periodic-background-sync/)
* [A Periodic Background Sync demo app](https://webplatformapis.com/periodic_sync/periodicSync_improved.html)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PeriodicSyncEvent>

PeriodicSyncManager
===================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `PeriodicSyncManager` interface of the [`Web Periodic Background Synchronization API`](web_periodic_background_synchronization_api) provides a way to register tasks to be run in a service worker at periodic intervals with network connectivity. These tasks are referred to as periodic background sync requests. Access `PeriodicSyncManager` through the [`ServiceWorkerRegistration.periodicSync`](serviceworkerregistration/periodicsync).



Instance properties
-------------------


None.


Instance methods
----------------


 
[`PeriodicSyncManager.register`](periodicsyncmanager/register)  Experimental 
  Registers a periodic sync request with the browser with the specified tag and options. Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves when the registration completes.

  
[`PeriodicSyncManager.getTags`](periodicsyncmanager/gettags)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with a list of [`strings`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) representing the tags that are currently registered for periodic syncing.

  
[`PeriodicSyncManager.unregister`](periodicsyncmanager/unregister)  Experimental 
  Unregisters the periodic sync request corresponding to the specified tag and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves when unregistration completes.

  
Examples
--------


The following examples show how to use the interface.


### Requesting a Periodic Background Sync



The following asynchronous function registers a periodic background sync at a minimum interval of one day from a browsing context:

 
```
async function registerPeriodicNewsCheck() {
  const registration = await navigator.serviceWorker.ready;
  try {
    await registration.periodicSync.register("get-latest-news", {
      minInterval: 24 \* 60 \* 60 \* 1000,
    });
  } catch {
    console.log("Periodic Sync could not be registered!");
  }
}

```


### Verifying a Background Periodic Sync by Tag



This code checks to see if a Periodic Background Sync task with a given tag is registered.

 
```
navigator.serviceWorker.ready.then((registration) => {
  registration.periodicSync.getTags().then((tags) => {
    if (tags.includes("get-latest-news")) skipDownloadingLatestNewsOnPageLoad();
  });
});

```


### Removing a Periodic Background Sync Task



The following code removes a Periodic Background Sync task to stop articles syncing in the background.

 
```
navigator.serviceWorker.ready.then((registration) => {
  registration.periodicSync.unregister("get-latest-news");
});

```


Specifications
--------------




| Specification |
| --- |
| [Web Periodic Background Synchronization # periodicsyncmanager-interface](https://wicg.github.io/periodic-background-sync/#periodicsyncmanager-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PeriodicSyncManager` | 80 | 80 | No | No | 67 | No | No | 80 | No | 57 | No | 13.0 |
| `getTags` | 80 | 80 | No | No | 67 | No | No | 80 | No | 57 | No | 13.0 |
| `register` | 80 | 80 | No | No | 67 | No | No | 80 | No | 57 | No | 13.0 |
| `unregister` | 80 | 80 | No | No | 67 | No | No | 80 | No | 57 | No | 13.0 |


See also
--------


* [Richer offline experiences with the Periodic Background Sync API](https://web.dev/periodic-background-sync/)
* [A Periodic Background Sync demo app](https://webplatformapis.com/periodic_sync/periodicSync_improved.html)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PeriodicSyncManager>

PeriodicWave
============



The `PeriodicWave` interface defines a periodic waveform that can be used to shape the output of an [`OscillatorNode`](oscillatornode).

 `PeriodicWave` has no inputs or outputs; it is used to define custom oscillators when calling [`OscillatorNode.setPeriodicWave()`](oscillatornode/setperiodicwave). The `PeriodicWave` itself is created/returned by [`BaseAudioContext.createPeriodicWave`](baseaudiocontext/createperiodicwave).



Constructor
-----------


 [`PeriodicWave()`](periodicwave/periodicwave)  Creates a new `PeriodicWave` object instance using the default values for all properties. If you wish to establish custom property values at the outset, use the [`BaseAudioContext.createPeriodicWave`](baseaudiocontext/createperiodicwave) factory method instead.

  
Instance properties
-------------------


None; also, `PeriodicWave` doesn't inherit any properties.


Instance methods
----------------


None; also, `PeriodicWave` doesn't inherit any methods.


Example
-------


See [`BaseAudioContext.createPeriodicWave`](baseaudiocontext/createperiodicwave) for simple example code that shows how to create a `PeriodicWave` object containing a simple sine wave.


Specifications
--------------




| Specification |
| --- |
| [Web Audio API # PeriodicWave](https://webaudio.github.io/web-audio-api/#PeriodicWave) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PeriodicWave` | 55 | 79 | 53 | No | 42 | 14.1 | 55 | 55 | 53 | 42 | 14.5 | 6.0 |
| `PeriodicWave` | 30 | 12 | 25 | No | 17 | 8 | ≤37 | 30 | 26 | 18 | 8 | 2.0 |


See also
--------


* [Using the Web Audio API](web_audio_api/using_web_audio_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PeriodicWave>

Permissions
===========


The Permissions interface of the [Permissions API](permissions_api) provides the core Permission API functionality, such as methods for querying and revoking permissions


Instance methods
----------------


 [`Permissions.query()`](permissions/query)  Returns the user permission status for a given API.

  
`Permissions.request()`  Experimental 
  Requests permission to use a given API. This is not currently supported in any browser.

  
`Permissions.requestAll()`  Experimental   Non-standard 
  Requests permission to use a given set of APIs. This is not currently supported in any browser.

  
[`Permissions.revoke()`](permissions/revoke)  Deprecated 
  Revokes the permission currently set on a given API.

  
Example
-------



```
navigator.permissions.query({ name: " geolocation" }).then((result) => {
  if (result.state === "granted") {
    showLocalNewsWithGeolocation();
  } else if (result.state === "prompt") {
    showButtonToEnableLocalNews();
  }
  // Don't do anything if the permission was denied.
});

```

Specifications
--------------




| Specification |
| --- |
| [Permissions # permissions-interface](https://w3c.github.io/permissions/#permissions-interface) |


Browser Support
---------------


BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Permissions>

PermissionStatus
================



The `PermissionStatus` interface of the [Permissions API](permissions_api) provides the state of an object and an event handler for monitoring changes to said state.


 EventTarget PermissionStatus

Instance properties
-------------------


 
[`PermissionStatus.name`](permissionstatus/name) Read only 
  Returns the name of a requested permission, identical to the `name` passed to [`Permissions.query`](permissions/query).

  
[`PermissionStatus.state`](permissionstatus/state) Read only 
  Returns the state of a requested permission; one of `'granted'`, `'denied'`, or `'prompt'`.

  
`PermissionStatus.status` Read only   Deprecated 
  Returns the state of a requested permission; one of `'granted'`, `'denied'`, or `'prompt'`. Later versions of the specification replace this with [`PermissionStatus.state`](permissionstatus/state).

  
### Events


 [`change`](permissionstatus/change_event)  An event called whenever `PermissionStatus.status` changes.

  
Example
-------



```
navigator.permissions
  .query({ name: "geolocation" })
  .then((permissionStatus) => {
    console.log(`geolocation permission status is ${permissionStatus.state}`);
    permissionStatus.onchange = () => {
      console.log(
        `geolocation permission status has changed to ${permissionStatus.state}`
      );
    };
  });

```

Specifications
--------------




| Specification |
| --- |
| [Permissions # permissionstatus-interface](https://w3c.github.io/permissions/#permissionstatus-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PermissionStatus` | 43 | 79 | 46 | No | 30 | 16 | NoSee [bug 490120](https://crbug.com/490120). | 43 | 46 | 30 | 16 | 4.0 |
| `change_event` | 43 | 79 | 46 | No | 30 | 16.4 | No | 43 | 46 | 30 | 16.4 | 4.0 |
| `name` | 97 | 97 | 93 | No | 83 | 16 | No | 97 | 93 | 68 | 16 | 18.0 |
| `state` | 4443–44 | 79 | 46 | No | 3130–31 | 16 | No | 4443–44 | 46 | 3230–32 | 16 | 4.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PermissionStatus>

PictureInPictureWindow
======================



The `PictureInPictureWindow` interface represents an object able to programmatically obtain the `width` and `height` and `resize event` of the floating video window.

 An object with this interface is obtained using the [`HTMLVideoElement.requestPictureInPicture()`](htmlvideoelement/requestpictureinpicture) promise return value.


 EventTarget PictureInPictureWindow

Instance properties
-------------------



*The `PictureInPictureWindow` interface doesn't inherit any properties.*

  
[`PictureInPictureWindow.width`](pictureinpicturewindow/width) Read only 
  Determines the width of the floating video window.

  
[`PictureInPictureWindow.height`](pictureinpicturewindow/height) Read only 
  Determines the height of the floating video window.

  

Instance methods
----------------


*The `PictureInPictureWindow` interface doesn't inherit any methods.*


Events
------



*The `PictureInPictureWindow` interface doesn't inherit any events.*

  [`resize`](pictureinpicturewindow/resize_event)  Sent to a [`PictureInPictureWindow`](pictureinpicturewindow) when the floating video window is resized.

  

Examples
--------



Given a `<button>` and a `<video>`, clicking the button will make the video enter the picture-in-picture mode; we then attach an event to print the floating video window dimensions to the console.

 
```
const button = document.querySelector("button");
const video = document.querySelector("video");

function printPipWindowDimensions(evt) {
  const pipWindow = evt.target;
  console.log(
    `The floating window dimensions are: ${pipWindow.width}x${pipWindow.height}px`
  );
  // will print:
  // The floating window dimensions are: 640x360px
}

button.onclick = () => {
  video.requestPictureInPicture().then((pictureInPictureWindow) => {
    pictureInPictureWindow.onresize = printPipWindowDimensions;
  });
};

```


Specifications
--------------




| Specification |
| --- |
| [Picture-in-Picture # interface-picture-in-picture-window](https://w3c.github.io/picture-in-picture/#interface-picture-in-picture-window) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PictureInPictureWindow` | 69 | 79 | No | No | 56 | 13.1 | No | 105 | No | 72 | 13.4 | 20.0 |
| `height` | 69 | 79 | No | No | 56 | 13.1 | No | 105 | No | 72 | 13.4 | 20.0 |
| `resize_event` | 69 | 79 | No | No | 56 | 13.1 | No | 105 | No | 72 | 13.4 | 20.0 |
| `width` | 69 | 79 | No | No | 56 | 13.1 | No | 105 | No | 72 | 13.4 | 20.0 |


See also
--------


* [`Picture-in-Picture API`](picture-in-picture_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PictureInPictureWindow>

Plugin
======



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The `Plugin` interface provides information about a browser plugin.

  **Note:** Own properties of `Plugin` objects are no longer enumerable in the latest browser versions.

 

Instance properties
-------------------


 
`Plugin.description` Read only   Deprecated 
  A human-readable description of the plugin.

  
`Plugin.filename` Read only   Deprecated 
  The filename of the plugin file.

  
`Plugin.name` Read only   Deprecated 
  The name of the plugin.

  
`Plugin.version` Read only   Deprecated 
  The plugin's version number string.

  
Instance methods
----------------


 
`Plugin.item`  Deprecated 
  Returns the MIME type of a supported content type, given the index number into a list of supported types.

  
`Plugin.namedItem`  Deprecated 
  Returns the MIME type of a supported item.

  
Specifications
--------------




| Specification |
| --- |
| [HTML Standard # dom-plugin](https://html.spec.whatwg.org/multipage/obsolete.html#dom-plugin) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Plugin` | 1 | 12 | 1 | 4 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `description` | 1 | 12 | 1 | 4 | ≤12.1 | 1 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `filename` | 1 | 12 | 1 | 4 | ≤12.1 | 1 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `item` | 1Starting with version 59, method parameters are required instead of optional. | 12 | 1 | 4 | 15 | 4 | ≤37Starting with version 59, method parameters are required instead of optional. | 18Starting with version 59, method parameters are required instead of optional. | 4 | 14 | 3.2 | 1.0Starting with Samsung Internet 7.0, method parameters are required instead of optional. |
| `length` | 1 | 12 | 1 | 11 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `name` | 1 | 12 | 1 | 4 | ≤12.1 | 1 | ≤37 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `namedItem` | 1Starting with version 59, method parameters are required instead of optional. | 12 | 1 | 4 | 15 | 4 | ≤37Starting with version 59, method parameters are required instead of optional. | 18Starting with version 59, method parameters are required instead of optional. | 4 | 14 | 3.2 | 1.0Starting with Samsung Internet 7.0, method parameters are required instead of optional. |
| `version` | No | 12–79 | 3.6 | 4 | No | No | No | No | 4 | No | No | No |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Plugin>

PluginArray
===========



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

 The `PluginArray` interface is used to store a list of [`Plugin`](plugin) objects describing the available [plugins](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/Plugins); it's returned by the [`navigator.plugins`](navigator/plugins) property. The `PluginArray` is not a JavaScript array, but has the `length` property and supports accessing individual items using bracket notation (`plugins[2]`), as well as via `item(index)` and `namedItem("name")` methods.

  **Note:** Own properties of `PluginArray` objects are no longer enumerable in the latest browser versions.

 

Instance properties
-------------------


 
`PluginArray.length` Read only   Deprecated 
  The number of plugins in the array.

  
Instance methods
----------------


 
`PluginArray.item`  Deprecated 
  Returns the [`Plugin`](plugin) at the specified index into the array.

  
`PluginArray.namedItem`  Deprecated 
  Returns the [`Plugin`](plugin) with the specified name.

  
`PluginArray.refresh`  Deprecated 
  Refreshes all plugins on the current page, optionally reloading documents.

  
Examples
--------



The following example function returns the version of the Shockwave Flash plugin.

 
```
const pluginsLength = navigator.plugins.length;

document.body.innerHTML =
  `${pluginsLength} Plugin(s)<br>` +
  `<table id="pluginTable"><thead>` +
  `<tr><th>Name</th><th>Filename</th><th>description</th><th>version</th></tr>` +
  `</thead><tbody></tbody></table>`;

const table = document.getElementById("pluginTable");

for (let i = 0; i < pluginsLength; i++) {
  let newRow = table.insertRow();
  newRow.insertCell().textContent = navigator.plugins[i].name;
  newRow.insertCell().textContent = navigator.plugins[i].filename;
  newRow.insertCell().textContent = navigator.plugins[i].description;
  newRow.insertCell().textContent = navigator.plugins[i].version ?? "";
}

```
 The following example displays information about the installed plugin(s).

 
```
const pluginsLength = navigator.plugins.length;

document.write(
  `${pluginsLength.toString()} Plugin(s)<br>` +
    `Name | Filename | description<br>`
);

for (let i = 0; i < pluginsLength; i++) {
  document.write(
    `${navigator.plugins[i].name} | ${navigator.plugins[i].filename} | ${navigator.plugins[i].description} | ${navigator.plugins[i].version}<br>`
  );
}

```


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # pluginarray](https://html.spec.whatwg.org/multipage/obsolete.html#pluginarray) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PluginArray` | 1 | 12 | 1 | 4 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `item` | 1Since Chrome 59, method parameters are required instead of optional. | 12Since Edge 79, method parameters are required instead of optional. | 1 | 6 | ≤12.1Since Opera 46, method parameters are required instead of optional. | 4 | ≤37Since WebView 59, method parameters are required instead of optional. | 18Since Chrome 59, method parameters are required instead of optional. | 4 | ≤12.1Since Opera Android 43, method parameters are required instead of optional. | 3.2 | 1.0Since Samsung Internet 7.0, method parameters are required instead of optional. |
| `length` | 1 | 12 | 1 | 4 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `namedItem` | 1Since Chrome 59, method parameters are required instead of optional. | 12Since Edge 79, method parameters are required instead of optional. | 1 | 6 | ≤12.1Since Opera 46, method parameters are required instead of optional. | 4 | ≤37Since WebView 59, method parameters are required instead of optional. | 18Since Chrome 59, method parameters are required instead of optional. | 4 | ≤12.1Since Opera Android 43, method parameters are required instead of optional. | 3.2 | 1.0Since Samsung Internet 7.0, method parameters are required instead of optional. |
| `refresh` | 1Since Chrome 59, method parameters are required instead of optional. | 12Since Edge 79, method parameters are required instead of optional. | 1 | 6 | ≤12.1Since Opera 46, method parameters are required instead of optional. | 1 | 4.4Since Chrome 59, method parameters are required instead of optional. | 18Since Chrome 59, method parameters are required instead of optional. | 4 | ≤12.1Since Opera Android 43, method parameters are required instead of optional. | 1 | 1.0Since Samsung Internet 7.0, method parameters are required instead of optional. |


In addition to listing each plugin as a pseudo-array by zero-indexed numeric properties, Firefox provides properties that are the plugin name directly on the PluginArray object.



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PluginArray>

Point
=====



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.


**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 `Point` is an interface which represents a point in 2-dimensional space. It is non-standard, not broadly compatible, and should not be used.

  **Note:** Although it is not directly related to this defunct interface, you are probably looking for [`DOMPoint`](dompoint).

 

Instance properties
-------------------


 
`x`  Deprecated   Non-standard 
  A floating-point value specifying the point's position with respect to the X (horizontal) axis.

  
`y`  Deprecated   Non-standard 
  A floating-point value specifying the point's position with respect to the Y (vertical) axis.

  
Specifications
--------------


This class was specified in [the defunct 20 March 2009 Working Draft of CSS 2D Transforms Module Level 3](https://www.w3.org/TR/2009/WD-css3-2d-transforms-20090320/). It is not present in any current specification.


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `WebKitPoint` | 2–39 | 12–79 | No | No | 15–26 | 4 | 2–39 | 18–39 | No | 14–26 | 3.2 | 1.0–4.0 |
| `x` | 2–39 | 12–79 | No | No | 15–26 | 4 | 2–39 | 18–39 | No | 14–26 | 3.2 | 1.0–4.0 |
| `y` | 2–39 | 12–79 | No | No | 15–26 | 4 | 2–39 | 18–39 | No | 14–26 | 3.2 | 1.0–4.0 |


See also
--------


* [`Window.webkitConvertPointFromNodeToPage()`](window/webkitconvertpointfromnodetopage)
* [`Window.webkitConvertPointFromPageToNode()`](window/webkitconvertpointfrompagetonode)
* [`WebKitPoint` documentation at the IE Dev Center](https://msdn.microsoft.com/library/ie/dn760730(v=vs.85).aspx)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/WebKitPoint>

PointerEvent
============



The `PointerEvent` interface represents the state of a DOM event produced by a pointer such as the geometry of the contact point, the device type that generated the event, the amount of pressure that was applied on the contact surface, etc.

 A *pointer* is a hardware agnostic representation of input devices (such as a mouse, pen or contact point on a touch-enable surface). The pointer can target a specific coordinate (or set of coordinates) on the contact surface such as a screen.

 A pointer's *hit test* is the process a browser uses to determine the target element for a pointer event. Typically, this is determined by considering the pointer's location and also the visual layout of elements in a document on screen media.


 Event UIEvent MouseEvent PointerEvent

Constructors
------------


 [`PointerEvent()`](pointerevent/pointerevent)  Creates a synthetic—and untrusted—`PointerEvent`.

  
Instance properties
-------------------



*This interface inherits properties from [`MouseEvent`](mouseevent) and [`Event`](event).*

  
[`PointerEvent.pointerId`](pointerevent/pointerid) Read only 
  A unique identifier for the pointer causing the event.

  
[`PointerEvent.width`](pointerevent/width) Read only 
  The width (magnitude on the X axis), in CSS pixels, of the contact geometry of the pointer.

  
[`PointerEvent.height`](pointerevent/height) Read only 
  The height (magnitude on the Y axis), in CSS pixels, of the contact geometry of the pointer.

  
[`PointerEvent.pressure`](pointerevent/pressure) Read only 
  The normalized pressure of the pointer input in the range `0` to `1`, where `0` and `1` represent the minimum and maximum pressure the hardware is capable of detecting, respectively.

  
[`PointerEvent.tangentialPressure`](pointerevent/tangentialpressure) Read only 
  The normalized tangential pressure of the pointer input (also known as barrel pressure or [cylinder stress](https://en.wikipedia.org/wiki/Cylinder_stress)) in the range `-1` to `1`, where `0` is the neutral position of the control.

  
[`PointerEvent.tiltX`](pointerevent/tiltx) Read only 
  The plane angle (in degrees, in the range of `-90` to `90`) between the Y–Z plane and the plane containing both the pointer (e.g. pen stylus) axis and the Y axis.

  
[`PointerEvent.tiltY`](pointerevent/tilty) Read only 
  The plane angle (in degrees, in the range of `-90` to `90`) between the X–Z plane and the plane containing both the pointer (e.g. pen stylus) axis and the X axis.

  
[`PointerEvent.twist`](pointerevent/twist) Read only 
  The clockwise rotation of the pointer (e.g. pen stylus) around its major axis in degrees, with a value in the range `0` to `359`.

  
[`PointerEvent.pointerType`](pointerevent/pointertype) Read only 
  Indicates the device type that caused the event (mouse, pen, touch, etc.).

  
[`PointerEvent.isPrimary`](pointerevent/isprimary) Read only 
  Indicates if the pointer represents the primary pointer of this pointer type.

  

Instance methods
----------------


 [`PointerEvent.getCoalescedEvents()`](pointerevent/getcoalescedevents)  Returns a sequence of all `PointerEvent` instances that were coalesced into the dispatched [`pointermove`](element/pointermove_event) event.

  `PointerEvent.getPredictedEvents()`  Returns a sequence of `PointerEvent` instances that the browser predicts will follow the dispatched [`pointermove`](element/pointermove_event) event's coalesced events.

  
Pointer event types
-------------------



The `PointerEvent` interface has several event types. To determine which event fired, look at the event's [`type`](event/type) property.

  **Note:** It's important to note that in many cases, both pointer and mouse events get sent (in order to let non-pointer-specific code still interact with the user). If you use pointer events, you should call [`event.preventDefault()`](event/preventdefault) to keep the mouse event from being sent as well.

   [`pointerover`](element/pointerover_event)  This event is fired when a pointing device is moved into an element's hit test boundaries.

  [`pointerenter`](element/pointerenter_event)  This event is fired when a pointing device is moved into the hit test boundaries of an element or one of its descendants, including as a result of a `pointerdown` event from a device that does not support hover (see `pointerdown`). This event type is similar to `pointerover`, but differs in that it does not bubble.

  [`pointerdown`](element/pointerdown_event)  The event is fired when a pointer becomes *active*. For mouse, it is fired when the device transitions from no buttons pressed to at least one button pressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.

  **Note:** For touchscreen browsers that allow [direct manipulation](https://w3c.github.io/pointerevents/#dfn-direct-manipulation), a `pointerdown` event triggers [implicit pointer capture](https://w3c.github.io/pointerevents/#dfn-implicit-pointer-capture), which causes the target to capture all subsequent pointer events as if they were occurring over the capturing target. Accordingly, `pointerover`, `pointerenter`, `pointerleave`, and `pointerout` **will not fire** as long as this capture is set. The capture can be released manually by calling [`element.releasePointerCapture`](element/releasepointercapture) on the target element, or it will be implicitly released after a `pointerup` or `pointercancel` event.

   [`pointermove`](element/pointermove_event)  This event is fired when a pointer changes coordinates.

  
`pointerrawupdate`  Experimental 
  This event is fired when any of a pointer's properties change.

  [`pointerup`](element/pointerup_event)  This event is fired when a pointer is no longer *active*.

  [`pointercancel`](element/pointercancel_event)  A browser fires this event if it concludes the pointer will no longer be able to generate events (for example the related device is deactivated).

  [`pointerout`](element/pointerout_event)  This event is fired for several reasons including: pointing device is moved out of the hit test boundaries of an element; firing the `pointerup` event for a device that does not support hover (see `pointerup`); after firing the `pointercancel` event (see `pointercancel`); when a pen stylus leaves the hover range detectable by the digitizer.

  [`pointerleave`](element/pointerleave_event)  This event is fired when a pointing device is moved out of the hit test boundaries of an element. For pen devices, this event is fired when the stylus leaves the hover range detectable by the digitizer.

  [`gotpointercapture`](element/gotpointercapture_event)  This event is fired when an element receives pointer capture.

  [`lostpointercapture`](element/lostpointercapture_event)  This event is fired after pointer capture is released for a pointer.

  

Example
-------


Examples of each property, event type, and global event handler are included in their respective reference pages.


Specifications
--------------




| Specification |
| --- |
| [Pointer Events # pointerevent-interface](https://w3c.github.io/pointerevents/#pointerevent-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PointerEvent` | 55 | 12 | 59 | 1110See [MSDN Pointer events updates](https://msdn.microsoft.com/library/dn304886). | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `PointerEvent` | 55 | 12 | 59 | 1110See [MSDN Pointer events updates](https://msdn.microsoft.com/library/dn304886). | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `altitudeAngle` | 86 | 86 | No | No | 72 | No | 86 | 86 | No | 61 | No | 14.0 |
| `azimuthAngle` | 86 | 86 | No | No | 72 | No | 86 | 86 | No | 61 | No | 14.0 |
| `getCoalescedEvents` | 58 | 79 | 59 | No | 45 | No | 58 | 58 | 79The method always returns an empty array, regardless of the user's actions. | 43 | No | 7.0 |
| `getPredictedEvents` | 77 | 79 | 89 | No | 64 | No | 77 | 77 | 89 | 55 | No | 12.0 |
| `height` | 55 | 12 | 59 | 1110Returns values in screen pixels instead of CSS document pixels. | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `isPrimary` | 55 | 12 | 59 | 10 | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `pointerId` | 55 | 12 | 59 | 10 | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `pointerType` | 55 | 12 | 59 | 1110Returns an integer enumeration instead of a string. | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `pressure` | 55 | 12 | 59 | 1110Returns 0 instead of 0.5 on hardware that doesn't support pressure. | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `tangentialPressure` | 57 | 79 | 59 | No | 44 | 13 | 57 | 57 | 79 | 43 | 13 | 7.0 |
| `tiltX` | 55 | 12 | 59 | 10 | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `tiltY` | 55 | 12 | 59 | 10 | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |
| `twist` | 57 | 18 | 59 | No | 44 | 13 | 57 | 57 | 79 | 43 | 13 | 7.0 |
| `width` | 55 | 12 | 59 | 1110Returns values in screen pixels instead of CSS document pixels. | 42 | 13 | 55 | 55 | 79 | 42 | 13 | 6.0 |


See also
--------


* [`Touch Events`](touch_events)
* [`GestureEvent`](gestureevent)
* [`touch-action`](https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent>

PictureInPictureEvent
=====================



The `PictureInPictureEvent` interface represents picture-in-picture-related events, including [`enterpictureinpicture`](htmlvideoelement/enterpictureinpicture_event), [`leavepictureinpicture`](htmlvideoelement/leavepictureinpicture_event) and [`resize`](pictureinpicturewindow/resize_event)


 Event PictureInPictureEvent

Constructor
-----------


 [`PictureInPictureEvent()`](pictureinpictureevent/pictureinpictureevent)  Creates a `PictureInPictureEvent` event with the given parameters.

  
Instance properties
-------------------



*This interface also inherits properties from its parent [`Event`](event)*.

  `PictureInPictureEvent.pictureInPictureWindow`  Returns the [`PictureInPictureWindow`](pictureinpicturewindow) the event relates to.

  

Instance methods
----------------


*This interface also inherits methods from its parent [`Event`](event)*.


Specifications
--------------




| Specification |
| --- |
| [Picture-in-Picture # event-types](https://w3c.github.io/picture-in-picture/#event-types) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PictureInPictureEvent` | 8569–85 | 8579–85 | No | No | 7156–71 | 1613.1 | No | 105 | No | 72 | 1613.4 | 20.0 |
| `PictureInPictureEvent` | 8569–85 | 8579–85 | No | No | 7156–71 | 1613.1 | No | 105 | No | 72 | 1613.4 | 20.0 |
| `pictureInPictureWindow` | 69 | 79 | No | No | 56 | 13.1 | No | 105 | No | 72 | 13.4 | 20.0 |


See also
--------


* The [`Event`](event) base interface


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PictureInPictureEvent>

PopStateEvent
=============



`PopStateEvent` is an interface for the [`popstate`](window/popstate_event) event.

  A `popstate` event is dispatched to the window every time the active history entry changes between two history entries for the same document. If the history entry being activated was created by a call to `history.pushState()` or was affected by a call to `history.replaceState()`, the `popstate` event's `state` property contains a copy of the history entry's state object. 


 Event PopStateEvent

Constructor
-----------


 [`PopStateEvent()`](popstateevent/popstateevent)  Creates a new `PopStateEvent` object.

  
Instance properties
-------------------



*This interface also inherits the properties of its parent, [`Event`](event).*

  
[`PopStateEvent.state`](popstateevent/state) Read only 
  Returns a copy of the information that was provided to `pushState()` or `replaceState()`.

  

Instance methods
----------------


*This interface has no methods of its own, but inherits the methods of its parent, [`Event`](event).*


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-popstateevent-interface](https://html.spec.whatwg.org/multipage/nav-history-apis.html#the-popstateevent-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PopStateEvent` | 16 | 14 | 11 | No | 15 | 6 | 4.4 | 18 | 14 | 14 | 6 | 1.0 |
| `PopStateEvent` | 4 | 12 | 4 | 10 | ≤12.1 | 6 | 4.4 | 18 | 4 | ≤12.1 | 6 | 1.0 |
| `state` | 4 | 12 | 4 | 10 | ≤12.1 | 6 | 4.4 | 18 | 4 | ≤12.1 | 6 | 1.0 |


See also
--------


* [`popstate`](window/popstate_event) event
* [`hashchange`](window/hashchange_event) event


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PopStateEvent>

PositionSensorVRDevice
======================



**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the [compatibility table](#browser_compatibility) at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.


**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The `PositionSensorVRDevice` interface of the [WebVR API](webvr_api) represents VR hardware's position sensor. You can access information such as the current position and orientation of the sensor in relation to the head mounted display through the [`PositionSensorVRDevice.getState()`](positionsensorvrdevice/getstate) method.



Instance methods
----------------


 
[`PositionSensorVRDevice.getState()`](positionsensorvrdevice/getstate)  Deprecated   Non-standard 
  Returns the current state of the position sensor for the current frame (e.g. within the current [`window.requestAnimationFrame`](window/requestanimationframe) callback) or for the previous frame, contained with a [`VRPose`](vrpose) object. This is the method you'd normally want to use, versus `getImmediateState()`.

  
[`PositionSensorVRDevice.getImmediateState()`](positionsensorvrdevice/getimmediatestate)  Deprecated   Non-standard 
  Returns the current instantaneous position sensor state. This is intended to only be used rarely, for certain special uses, for example sampling the immediate position of a hand orientation sensor — or at least it will be, in the future.

  
[`PositionSensorVRDevice.resetSensor()`](positionsensorvrdevice/resetsensor)  Deprecated   Non-standard 
  *Can be used to reset the sensor if desired, returning the* position and orientation values to zero.

  
Instance properties
-------------------



*This interface doesn't define any properties of its own, but it does inherit the properties of its parent interface, [`VRDisplay`](vrdisplay).*

  
[`VRDisplay.hardwareUnitId`](vrfieldofview) Read only 
  Returns the distinct hardware ID for the overall hardware unit that this `VRDevice` is a part of. All devices that are part of the same physical piece of hardware will have the same `hardwareUnitId`.

  
[`VRDisplay.displayId`](vrdisplay/displayid) Read only 
  Returns the ID for this specific `VRDevice`. The ID shouldn't change across browser restarts, allowing configuration data to be saved based on it.

  
[`VRDisplay.displayName`](vrdisplay/displayname) Read only 
  A human-readable name to identify the `VRDevice`.

  

Examples
--------



The following example uses the WebVR API to update the view of a simple [`2D canvas`](canvasrenderingcontext2d) scene on each frame of a [`requestAnimationFrame`](window/requestanimationframe) loop.

 
```
function setView() {
  const posState = gPositionSensor.getState();
  if (posState.hasPosition) {
    posPara.textContent = `Position: x${roundToTwo(
 posState.position.x
 )} y${roundToTwo(posState.position.y)} z${roundToTwo(posState.position.z)}`;
    xPos = -posState.position.x \* WIDTH \* 2;
    yPos = posState.position.y \* HEIGHT \* 2;
    zPos = -posState.position.z > 0.01 ? -posState.position.z : 0.01;
  }

  if (posState.hasOrientation) {
    orientPara.textContent = `Orientation: x${roundToTwo(
 posState.orientation.x
 )} y${roundToTwo(posState.orientation.y)} z${roundToTwo(
 posState.orientation.z
 )}`;
    xOrient = posState.orientation.x \* WIDTH;
    yOrient = -posState.orientation.y \* HEIGHT \* 2;
    zOrient = posState.orientation.z \* 180;
  }
}

```
 Here we are grabbing a [`VRPose`](vrpose) object using [`PositionSensorVRDevice.getState()`](positionsensorvrdevice/getstate) and storing it in `posState`. We then check to make sure that position and orientation info is present in the current frame using [`VRPose.hasPosition`](vrpose/position) and [`VRPose.hasOrientation`](vrpose/orientation) (these return `null` if, for example the head mounted display is turned off or not pointing at the position sensor, which would cause an error.)

 We then output the x, y and z position and orientation values for informational purposes, and use those values to update the `xPos`, `yPos`, `zPos`, `xOrient`, `yOrient`, and `zOrient` variables, which are used to update the scene rendering on each frame.



Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PositionSensorVRDevice` | No | No | 39 | No | No | No | No | No | No | No | No | No |
| `getImmediateState` | No | No | 39 | No | No | No | No | No | No | No | No | No |
| `getState` | No | No | 39 | No | No | No | No | No | No | No | No | No |
| `resetSensor` | No | No | 39 | No | No | No | No | No | No | No | No | No |


See also
--------


* [WebVR API homepage](webvr_api).
* <https://mixedreality.mozilla.org/> — demos, downloads, and other resources from the Mozilla VR team.


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PositionSensorVRDevice>

Presentation
============



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.


**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `Presentation` can be defined as two possible user agents in the context: *Controlling user agent* and *Receiving user agent*.

 In controlling browsing context, the `Presentation` interface provides a mechanism to override the browser default behavior of launching presentation to external screen. In receiving browsing context, `Presentation` interface provides the access to the available presentation connections.



Instance properties
-------------------


 
[`Presentation.defaultRequest`](presentation/defaultrequest)  Experimental 
  In a [controlling user agent](https://www.w3.org/TR/presentation-api/#dfn-controlling-user-agent), the `defaultRequest` attribute *MUST* return the [default presentation request](https://www.w3.org/TR/presentation-api/#dfn-default-presentation-request) if any, `null` otherwise. In a [receiving browsing context](https://www.w3.org/TR/presentation-api/#dfn-receiving-browsing-context), it *MUST* return `null`.

  
[`Presentation.receiver`](presentation/receiver)  Experimental 
  In a [receiving user agent](https://www.w3.org/TR/presentation-api/#dfn-receiving-user-agent), the `receiver` attribute *MUST* return the [`PresentationReceiver`](presentationreceiver) instance associated with the [receiving browsing context](https://www.w3.org/TR/presentation-api/#dfn-receiving-browsing-context) and created by the [receiving user agent](https://www.w3.org/TR/presentation-api/#dfn-receiving-user-agent) when the [receiving browsing context](https://www.w3.org/TR/presentation-api/#dfn-receiving-browsing-context) is created.

  
Instance methods
----------------


None.


Specifications
--------------




| Specification |
| --- |
| [Presentation API # interface-presentation](https://w3c.github.io/presentation-api/#interface-presentation) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Presentation` | 47 | 79 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |
| `defaultRequest` | 47 | 79 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |
| `receiver` | 59 | 79 | No | No | 46 | No | No | 59 | No | 43 | No | 7.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Presentation>

PresentationConnection
======================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.


**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `PresentationConnection` interface of the [Presentation API](presentation_api) provides methods and properties for managing a single presentation. Each [presentation connection](https://www.w3.org/TR/presentation-api/#dfn-presentation-connection) is represented by a `PresentationConnection` object. Both the [controlling user agent](https://www.w3.org/TR/presentation-api/#dfn-controlling-user-agent) and [receiving user agent](https://www.w3.org/TR/presentation-api/#dfn-receiving-user-agent) *MUST* implement `PresentationConnection`.


 EventTarget PresentationConnection

Instance properties
-------------------


 
[`PresentationConnection.binaryType`](presentationconnection/binarytype)  Experimental 
  Returns either blob or arrayBuffer. When a `PresentationConnection` object is created, its [`binaryType`](https://www.w3.org/TR/presentation-api/#idl-def-presentationconnection-binarytype) IDL attribute *MUST* be set to the string " [`arraybuffer`](https://www.w3.org/TR/presentation-api/#dom-binarytype-arraybuffer)".

  
[`PresentationConnection.id`](presentationconnection/id) Read only   Experimental 
  Provides the presentation connection identifier.

  
[`PresentationConnection.state`](presentationconnection/state) Read only   Experimental 
  Returns the [presentation connection](https://www.w3.org/TR/presentation-api/#dfn-presentation-connection)'s current state.

  
[`PresentationConnection.url`](presentationconnection/url) Read only   Experimental 
  Returns the URL used to create or reconnect to the presentation.

  
### Event handlers


 
`PresentationConnection.onclose`  Experimental 
  Fired when there is a call to [`PresentationConnection.close()`](presentationconnection/close).

  
`PresentationConnection.onconnect`  Experimental 
  Fired when a presentation connection is established.

  
`PresentationConnection.onmessage`  Experimental 
  Fired when there is a call to [`PresentationConnection.send()`](presentationconnection/send).

  `PresentationConnection.onterminated`  Fired when there is a call to [`PresentationConnection.terminate()`](presentationconnection/terminate).

  
Instance methods
----------------


 
[`PresentationConnection.close()`](presentationconnection/close)  Experimental 
  Closes the current connection and sends a [`PresentationConnectionCloseEvent`](presentationconnectioncloseevent) to `PresentationConnection.onclosed`.

  
[`PresentationConnection.send()`](presentationconnection/send)  Experimental 
  Sends either binary or text data between a controlling browsing context and a presenting browsing context.

  
[`PresentationConnection.terminate()`](presentationconnection/terminate)  Experimental 
  Terminates the current connection and fires `PresentationConnection.onterminated`.

  
Specifications
--------------




| Specification |
| --- |
| [Presentation API # interface-presentationconnection](https://w3c.github.io/presentation-api/#interface-presentationconnection) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PresentationConnection` | 47 | 79 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |
| `binaryType` | 47 | 79 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |
| `close` | 49 | 79 | No | No | 36 | No | No | 49 | No | 36 | No | 5.0 |
| `close_event` | 50 | 79 | No | No | 37 | No | No | 50 | No | 37 | No | 5.0 |
| `connect_event` | 50 | 79 | No | No | 37 | No | No | 50 | No | 37 | No | 5.0 |
| `id` | 47 | 79 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |
| `message_event` | 47 | 79 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |
| `send` | 47 | 79 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |
| `state` | 47 | 79 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |
| `terminate` | 48 | 79 | No | No | 35 | No | No | 48 | No | 35 | No | 5.0 |
| `terminate_event` | 50 | 79 | No | No | 37 | No | No | 50 | No | 37 | No | 5.0 |
| `url` | 57 | 79 | No | No | 44 | No | No | 57 | No | 43 | No | 7.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PresentationConnection>

PresentationConnectionAvailableEvent
====================================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.


**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `PresentationConnectionAvailableEvent` interface of the [Presentation API](presentation_api) is fired on a [`PresentationRequest`](presentationrequest) when a connection associated with the object is created.

 A [controlling user agent](https://www.w3.org/TR/presentation-api/#dfn-controlling-user-agent) [fires](https://www.w3.org/TR/presentation-api/#dfn-firing-an-event) a [trusted event](https://www.w3.org/TR/presentation-api/#dfn-trusted-event) named [`connectionavailable`](https://www.w3.org/TR/presentation-api/#dfn-connectionavailable) on a [`PresentationRequest`](https://www.w3.org/TR/presentation-api/#idl-def-presentationrequest) when a connection associated with the object is created. It is fired at the `PresentationRequest` instance, using the [`PresentationConnectionAvailableEvent`](https://www.w3.org/TR/presentation-api/#idl-def-presentationconnectionavailableevent) interface, with the [`connection`](https://www.w3.org/TR/presentation-api/#idl-def-presentationconnectionavailableevent-connection) attribute set to the [`PresentationConnection`](https://www.w3.org/TR/presentation-api/#idl-def-presentationconnection) object that was created. The event is fired for each connection that is created for the [controller](https://www.w3.org/TR/presentation-api/#dfn-controller), either by the [controller](https://www.w3.org/TR/presentation-api/#dfn-controller) calling `start()` or `reconnect()`, or by the [controlling user agent](https://www.w3.org/TR/presentation-api/#dfn-controlling-user-agent) creating a connection on the controller's behalf via [`defaultRequest`](https://www.w3.org/TR/presentation-api/#dom-presentation-defaultrequest).


 Event PresentationConnectionAvailableEvent

Constructor
-----------


 
[`PresentationConnectionAvailableEvent()`](presentationconnectionavailableevent/presentationconnectionavailableevent)  Experimental 
  Creates a new PresentationConnectionAvailableEvent.

  
Instance properties
-------------------


 
[`PresentationConnectionAvailableEvent.connection`](presentationconnectionavailableevent/connection) Read only   Experimental 
  Returns a references to the [`PresentationConnection`](presentationconnection) object that fired the event.

  
Specifications
--------------




| Specification |
| --- |
| [Presentation API # interface-presentationconnectionavailableevent](https://w3c.github.io/presentation-api/#interface-presentationconnectionavailableevent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PresentationConnectionAvailableEvent` | 47 | 79 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |
| `PresentationConnectionAvailableEvent` | 47 | 79 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |
| `connection` | 47 | 79 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PresentationConnectionAvailableEvent>

PresentationConnectionCloseEvent
================================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.


**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `PresentationConnectionCloseEvent` interface of the [Presentation API](presentation_api) is fired on a [`PresentationConnection`](presentationconnection) when it is closed.


 Event PresentationConnectionCloseEvent

Constructor
-----------


 
`PresentationConnectionCloseEvent()`  Experimental 
  Creates a new PresentationConnectionCloseEvent.

  
Instance properties
-------------------


 
`PresentationConnectionCloseEvent.message` Read only   Experimental 
  A human-readable message that provides more information about why the connection was closed.

  
`PresentationConnectionCloseEvent.reason` Read only   Experimental 
  Indicates why the connection was closed. This property takes one of the following values: `error`, `closed`, or `wentaway`.

  
Specifications
--------------




| Specification |
| --- |
| [Presentation API # interface-presentationconnectioncloseevent](https://w3c.github.io/presentation-api/#interface-presentationconnectioncloseevent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PresentationConnectionCloseEvent` | 50 | 79 | No | No | 37 | No | No | 50 | No | 37 | No | 5.0 |
| `PresentationConnectionCloseEvent` | 50 | 79 | No | No | 37 | No | No | 50 | No | 37 | No | 5.0 |
| `message` | 50 | 79 | No | No | 37 | No | No | 50 | No | 37 | No | 5.0 |
| `reason` | 50 | 79 | No | No | 37 | No | No | 50 | No | 37 | No | 5.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PresentationConnectionCloseEvent>

PresentationAvailability
========================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.


**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 A `PresentationAvailability` object is associated with available [presentation displays](https://www.w3.org/TR/presentation-api/#dfn-presentation-display) and represents the *presentation display availability* for a presentation request. If the [controlling user agent](https://www.w3.org/TR/presentation-api/#dfn-controlling-user-agent) can [monitor the list of available presentation displays](https://www.w3.org/TR/presentation-api/#dfn-monitor-the-list-of-available-presentation-displays) in the background (without a pending request to `start()`), the `PresentationAvailability` object *MUST* be implemented in a [controlling browsing context](https://www.w3.org/TR/presentation-api/#dfn-controlling-browsing-context).

 The `value` attribute *MUST* return the last value it was set to. The value is updated by the [monitor the list of available presentation displays](https://www.w3.org/TR/presentation-api/#dfn-monitor-the-list-of-available-presentation-displays) algorithm.

 The `onchange` attribute is an [event handler](https://www.w3.org/TR/presentation-api/#dfn-event-handler) whose corresponding [event handler event type](https://www.w3.org/TR/presentation-api/#dfn-event-handler-event-type) is `change`.


 EventTarget PresentationAvailability

Instance properties
-------------------


 
[`PresentationAvailability.value`](presentationavailability/value) Read only   Experimental 
  A boolean value indicating whether the given presentation display is available. The `value` attribute *MUST* return the last value it was set to.

  
### Event


 
`change`  Experimental 
  Indicates that the availability of the presentation display has changed.

  
Instance methods
----------------


None.


Specifications
--------------




| Specification |
| --- |
| [Presentation API # interface-presentationavailability](https://w3c.github.io/presentation-api/#interface-presentationavailability) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PresentationAvailability` | 47 | 79 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |
| `change_event` | 47 | 79 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |
| `value` | 47 | 79 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PresentationAvailability>

PresentationConnectionList
==========================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 `PresentationConnectionList` is the collection of incoming presentation connections.


 EventTarget PresentationConnectionList

Instance properties
-------------------


 
`PresentationConnectionList.connections` Read only   Experimental 
  Returns the non-terminated set of [`PresentationConnection`](presentationconnection)s in the [set of presentation controllers](https://www.w3.org/TR/presentation-api/#dfn-set-of-presentation-controllers).

  
### Event Handlers


 
`PresentationConnectionList.onconnectionavailable`  Experimental 
  Fired whenever a new [presentation connection](https://www.w3.org/TR/presentation-api/#dfn-presentation-connection) becomes available.

  
Specifications
--------------




| Specification |
| --- |
| [Presentation API # interface-presentationconnectionlist](https://w3c.github.io/presentation-api/#interface-presentationconnectionlist) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PresentationConnectionList` | 59 | 79 | No | No | 46 | No | No | 59 | No | 43 | No | 7.0 |
| `connectionavailable_event` | 59 | 79 | No | No | 46 | No | No | 59 | No | 43 | No | 7.0 |
| `connections` | 59 | 79 | No | No | 46 | No | No | 59 | No | 43 | No | 7.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PresentationConnectionList>

PresentationRequest
===================



**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.


**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 A `PresentationRequest` object is used to initiate or reconnect to a presentation made by a [controlling browsing context](https://www.w3.org/TR/presentation-api/#dfn-controlling-browsing-context). The `PresentationRequest` object *MUST* be implemented in a [controlling browsing context](https://www.w3.org/TR/presentation-api/#dfn-controlling-browsing-context) provided by a [controlling user agent](https://www.w3.org/TR/presentation-api/#dfn-controlling-user-agent).

 When a `PresentationRequest` is constructed, the given `urls` *MUST* be used as the list of *presentation request URLs* which are each a possible [presentation URL](https://www.w3.org/TR/presentation-api/#dfn-presentation-url) for the `PresentationRequest` instance.


 EventTarget PresentationRequest

Constructor
-----------


 
[`PresentationRequest()`](presentationrequest/presentationrequest)  Experimental 
  Creates a `PresentationRequest`.

  
Instance properties
-------------------


None


### Event handlers


 
[`PresentationRequest.onconnectionavailable`](presentationrequest)  Experimental 
  Fires on a successful call to [`PresentationRequest.start()`](presentationrequest/start) or `PresentationRequest.join()`. This method provides an object with a reference to the created or joined object.

  
Instance methods
----------------


 
[`PresentationRequest.start()`](presentationrequest/start)  Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with a [`PresentationConnection`](presentationconnection) after the user agent prompts the user to select a display and grant permission to use that display.

  
[`PresentationRequest.reconnect()`](presentationrequest/reconnect)  Experimental 
  When the `reconnect(presentationId)` method is called on a `PresentationRequest` *presentationRequest*, the [user agent](https://www.w3.org/TR/presentation-api/#dfn-user-agents) *MUST* run the following steps to *reconnect to a presentation*.

  
[`PresentationRequest.getAvailability()`](presentationrequest/getavailability)  Experimental 
  When the `getAvailability()` method is called, the user agent *MUST* run the steps as the link.

  
Specifications
--------------




| Specification |
| --- |
| [Presentation API # interface-presentationrequest](https://w3c.github.io/presentation-api/#interface-presentationrequest) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PresentationRequest` | 47 | 79 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |
| `PresentationRequest` | 47 | 79 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |
| `connectionavailable_event` | 47 | 79 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |
| `getAvailability` | 47 | 79 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |
| `reconnect` | 47 | 79 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |
| `secure_context_required` | 61 | 79 | 51–61 | No | 48 | No | No | 61 | 51–79 | 45 | No | 8.0 |
| `start` | 47 | 79 | No | No | 34 | No | No | 47 | No | 34 | No | 5.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PresentationRequest>

PublicKeyCredential
===================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `PublicKeyCredential` interface provides information about a public key / private key pair, which is a credential for logging in to a service using an un-phishable and data-breach resistant asymmetric key pair instead of a password. It inherits from [`Credential`](credential), and was created by the [Web Authentication API](web_authentication_api) extension to the [Credential Management API](credential_management_api). Other interfaces that inherit from [`Credential`](credential) are [`PasswordCredential`](passwordcredential) and [`FederatedCredential`](federatedcredential).


 Credential PublicKeyCredential  **Note:** This API is restricted to top-level contexts. Use from within an [`<iframe>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe) element will not have any effect.

 

Instance properties
-------------------


 
`PublicKeyCredential.type` Read only  Secure context
  Inherited from [`Credential`](credential). Always set to `public-key` for `PublicKeyCredential` instances.

  
[`PublicKeyCredential.id`](publickeycredential/id) Read only  Secure context
  Inherited from [`Credential`](credential) and overridden to be the [base64url encoding](https://developer.mozilla.org/en-US/docs/Glossary/Base64) of [`PublicKeyCredential.rawId`](publickeycredential/rawid).

  
[`PublicKeyCredential.rawId`](publickeycredential/rawid) Read only  Secure context
  An [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) that holds the globally unique identifier for this `PublicKeyCredential`. This identifier can be used to look up credentials for future calls to [`CredentialsContainer.get`](credentialscontainer/get).

  
[`PublicKeyCredential.response`](publickeycredential/response) Read only  Secure context
  An instance of an [`AuthenticatorResponse`](authenticatorresponse) object. It is either of type [`AuthenticatorAttestationResponse`](authenticatorattestationresponse) if the `PublicKeyCredential` was the results of a [`navigator.credentials.create()`](credentialscontainer/create) call, or of type [`AuthenticatorAssertionResponse`](authenticatorassertionresponse) if the `PublicKeyCredential` was the result of a [`navigator.credentials.get()`](credentialscontainer/get) call.

  
Static methods
--------------


 
[`PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()`](publickeycredential/isuserverifyingplatformauthenticatoravailable) Secure context
  A static method returning a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which resolves to `true` if an authenticator bound to the platform is capable of *verifying* the user.

  
Instance methods
----------------


 
[`PublicKeyCredential.getClientExtensionResults()`](publickeycredential/getclientextensionresults) Secure context
  If any extensions were requested, this method will return the results of processing those extensions.

  
Examples
--------


### Creating a new instance of PublicKeyCredential



Here, we use [`navigator.credentials.create()`](credentialscontainer/create) to generate a new credential.

 
```
const publicKey = {
  challenge: new Uint8Array([
    21, 31, 105 /\* 29 more random bytes generated by the server \*/,
  ]),
  rp: {
    name: "Example CORP",
    id: "login.example.com",
  },
  user: {
    id: new Uint8Array(16),
    name: "canand@example.com",
    displayName: "Carina Anand",
  },
  pubKeyCredParams: [
    {
      type: "public-key",
      alg: -7,
    },
  ],
};

navigator.credentials
  .create({ publicKey })
  .then((newCredentialInfo) => {
    const response = newCredentialInfo.response;
    const clientExtensionsResults =
      newCredentialInfo.getClientExtensionResults();
  })
  .catch((err) => {
    console.error(err);
  });

```


### Getting an existing instance of PublicKeyCredential



Here, we fetch an existing credential from an authenticator, using [`navigator.credentials.get()`](credentialscontainer/get).

 
```
const options = {
  challenge: new Uint8Array([
    /\* bytes sent from the server \*/
  ]),
};

navigator.credentials
  .get({ publicKey: options })
  .then((credentialInfoAssertion) => {
    // send assertion response back to the server
    // to proceed with the control of the credential
  })
  .catch((err) => {
    console.error(err);
  });

```


Specifications
--------------




| Specification |
| --- |
| [Web Authentication: An API for accessing Public Key Credentials - Level 3 # iface-pkcredential](https://w3c.github.io/webauthn/#iface-pkcredential) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PublicKeyCredential` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 49 | 13 | 10.0 |
| `authenticatorAttachment` | 98 | 98 | No | No | 84 | 15.5 | No | 98 | No | 68 | 15.5 | 18.0 |
| `getClientExtensionResults` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 49 | 13 | 10.0 |
| `isConditionalMediationAvailable` | 108 | 108 | No | No | 94 | 16 | No | 108 | No | 73 | No | No |
| `isUserVerifyingPlatformAuthenticatorAvailable` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 49 | 13 | 10.0 |
| `rawId` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 49 | 13 | 10.0 |
| `response` | 67 | 18 | 60Only supports USB U2F tokens. | No | 54 | 13 | No | 70 | 9260–92Only supports USB U2F tokens. | 49 | 13 | 10.0 |


See also
--------


* The parent interface [`Credential`](credential)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential>

PublicKeyCredentialRequestOptions
=================================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).

 The `PublicKeyCredentialRequestOptions` dictionary of the [Web Authentication API](web_authentication_api) holds the options passed to [`navigator.credentials.get()`](credentialscontainer/get) in order to fetch a given [`PublicKeyCredential`](publickeycredential).



Instance properties
-------------------


 [`PublicKeyCredentialRequestOptions.challenge`](credentialscontainer/get)  An [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), a [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), or a [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView), emitted by the relying party's server and used as a [cryptographic challenge](https://en.wikipedia.org/wiki/Challenge%E2%80%93response_authentication). This value will be signed by the authenticator and the signature will be sent back as part of [`AuthenticatorAssertionResponse.signature`](authenticatorassertionresponse/signature).

  
[`PublicKeyCredentialRequestOptions.timeout`](credentialscontainer/get) Optional
  A numerical hint, in milliseconds, which indicates the time the caller is willing to wait for the retrieval operation to complete. This hint may be overridden by the browser.

  
[`PublicKeyCredentialRequestOptions.rpId`](credentialscontainer/get) Optional
  A string which indicates the relying party's identifier (ex. `"login.example.org"`). If this option is not provided, the client will use the current origin's domain.

  
[`PublicKeyCredentialRequestOptions.allowCredentials`](credentialscontainer/get) Optional
  An [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of credentials descriptor which restricts the acceptable existing credentials for retrieval.

  
[`PublicKeyCredentialRequestOptions.userVerification`](credentialscontainer/get) Optional
  A string qualifying how the user verification should be part of the authentication process.

  
[`PublicKeyCredentialRequestOptions.extensions`](credentialscontainer/get) Optional
  An object with several client extensions' inputs. Those extensions are used to request additional processing (e.g. dealing with legacy FIDO APIs credentials, prompting a specific text on the authenticator, etc.).

  
Instance methods
----------------


None.


Examples
--------



```
const options = {
  challenge: new Uint8Array([
    /\* bytes sent from the server \*/
  ]),
  rpId: "example.com" /\* will only work if the current domain
 is something like foo.example.com \*/,
  userVerification: "preferred",
  timeout: 60000, // Wait for a minute
  allowCredentials: [
    {
      transports: "usb",
      type: "public-key",
      id: new Uint8Array(26), // actually provided by the server
    },
    {
      transports: "internal",
      type: "public-key",
      id: new Uint8Array(26), // actually provided by the server
    },
  ],
  extensions: {
    uvm: true, // RP wants to know how the user was verified
    loc: false,
    txAuthSimple: "Could you please verify yourself?",
  },
};

navigator.credentials
  .get({ publicKey: options })
  .then((credentialInfoAssertion) => {
    // send assertion response back to the server
    // to proceed with the control of the credential
  })
  .catch((err) => {
    console.error(err);
  });

```

Specifications
--------------




| Specification |
| --- |
| [Web Authentication: An API for accessing Public Key Credentials - Level 3 # dictdef-publickeycredentialrequestoptions](https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptions) |


See also
--------


* [`PublicKeyCredentialCreationOptions`](credentialscontainer/create): the dictionary which provides option for the public key credential creation


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions>

PushEvent
=========



The `PushEvent` interface of the [Push API](push_api) represents a push message that has been received. This event is sent to the [global scope](serviceworkerglobalscope) of a [`ServiceWorker`](serviceworker). It contains the information sent from an application server to a [`PushSubscription`](pushsubscription).


 Event ExtendableEvent PushEvent

Constructor
-----------


 [`PushEvent()`](pushevent/pushevent)  Creates a new `PushEvent` object.

  
Instance properties
-------------------



*Inherits properties from its parent, [`ExtendableEvent`](extendableevent). Additional properties:*

  
[`PushEvent.data`](pushevent/data) Read only 
  Returns a reference to a [`PushMessageData`](pushmessagedata) object containing data sent to the [`PushSubscription`](pushsubscription).

  

Instance methods
----------------


*Inherits methods from its parent, [`ExtendableEvent`](extendableevent)*.


Examples
--------



The following example takes data from a `PushEvent` and displays it on all of the service worker's clients.

 
```
self.addEventListener("push", (event) => {
  if (!(self.Notification && self.Notification.permission === "granted")) {
    return;
  }

  const data = event.data?.json() ?? {};
  const title = data.title || "Something Has Happened";
  const message =
    data.message || "Here's something you might want to check out.";
  const icon = "images/new-notification.png";

  const notification = new self.Notification(title, {
    body: message,
    tag: "simple-push-demo-notification",
    icon,
  });

  notification.addEventListener("click", () => {
    clients.openWindow(
      "https://example.blog.com/2015/03/04/something-new.html"
    );
  });
});

```


Specifications
--------------




| Specification |
| --- |
| [Push API # pushevent-interface](https://w3c.github.io/push-api/#pushevent-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PushEvent` | 42 | 17 | 44 | No | 37 | 16Supported on macOS 13 and later | No | 42 | 48 | 37 | 16.4 | 4.0 |
| `PushEvent` | 42 | 17 | 44 | No | 37 | 16Supported on macOS 13 and later | NoSee [bug 421921](https://crbug.com/421921). | 42 | 48 | 37 | 16.4 | 4.0 |
| `data` | 50 | 17 | 44 | No | 37 | 16Supported on macOS 13 and later | No | 50 | 48 | 37 | 16.4 | 5.0 |


See also
--------


* [Push API](push_api)
* [Service Worker API](service_worker_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PushEvent>

PushSubscription
================



The `PushSubscription` interface of the [Push API](push_api) provides a subscription's URL endpoint and allows unsubscribing from a push service.

 An instance of this interface can be serialized.



Instance properties
-------------------


 
[`PushSubscription.endpoint`](pushsubscription/endpoint) Read only 
  A string containing the endpoint associated with the push subscription.

  
[`PushSubscription.expirationTime`](pushsubscription/expirationtime) Read only 
  A [`DOMHighResTimeStamp`](domhighrestimestamp) of the subscription expiration time associated with the push subscription, if there is one, or null otherwise.

  
[`PushSubscription.options`](pushsubscription/options) Read only 
  An object containing the options used to create the subscription.

  
[`PushSubscription.subscriptionId`](pushsubscription/subscriptionid)  Deprecated  Read only 
  A string containing the subscription ID associated with the push subscription.

  
Instance methods
----------------


 [`PushSubscription.getKey()`](pushsubscription/getkey)  Returns an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) which contains the client's public key, which can then be sent to a server and used in encrypting push message data.

  [`PushSubscription.toJSON()`](pushsubscription/tojson)  Standard serializer — returns a JSON representation of the subscription properties.

  [`PushSubscription.unsubscribe()`](pushsubscription/unsubscribe)  Starts the asynchronous process of unsubscribing from the push service, returning a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to a boolean value when the current subscription is successfully unregistered.

  
Example
-------



```
navigator.serviceWorker.ready.then((reg) => {
  reg.pushManager.getSubscription().then((subscription) => {
    subscription
      .unsubscribe()
      .then((successful) => {
        // You've successfully unsubscribed
      })
      .catch((e) => {
        // Unsubscribing failed
      });
  });
});

```

Specifications
--------------




| Specification |
| --- |
| [Push API # pushsubscription-interface](https://w3c.github.io/push-api/#pushsubscription-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PushSubscription` | 42 | 17 | 44 | No | 29 | 16Supported on macOS 13 and later | NoSee [bug 421921](https://crbug.com/421921). | 42 | 48 | 29 | 16.4 | 4.0 |
| `endpoint` | 42 | 17 | 44 | No | 29 | 16Supported on macOS 13 and later | No | 42 | 48 | 29 | 16.4 | 4.0 |
| `expirationTime` | 60 | 17 | 96 | No | 47 | 16Supported on macOS 13 and later | No | 60 | 96 | 44 | 16.4 | 8.0 |
| `getKey` | 42 | 17 | 44 | No | 29 | 16Supported on macOS 13 and later | No | 42 | 48 | 29 | 16.4 | 4.0 |
| `options` | 54 | 17 | 44 | No | 41 | 16Supported on macOS 13 and later | No | 54 | 48 | 41 | 16.4 | 6.0 |
| `subscriptionId` | 42 | ≤18 | No | No | 29 | No | No | 42 | No | 29 | No | 4.0 |
| `toJSON` | 42 | 17 | 44 | No | 29 | 16Supported on macOS 13 and later | No | 50 | 48 | 37 | 16.4 | 5.0 |
| `unsubscribe` | 42 | 17 | 44 | No | 29 | 16Supported on macOS 13 and later | No | 50 | 48 | 37 | 16.4 | 5.0 |


See also
--------


* [Push API](push_api)
* [Service Worker API](service_worker_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PushSubscription>

PresentationReceiver
====================



**Secure context:** This feature is available only in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS), in some or all [supporting browsers](#browser_compatibility).


**Experimental:** **This is an [experimental technology](https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Experimental_deprecated_obsolete#experimental)**  
Check the [Browser compatibility table](#browser_compatibility) carefully before using this in production.

 The `PresentationReceiver` interface of the [Presentation API](presentation_api) provides a means for a receiving browsing context to access controlling browsing contexts and communicate with them.



Instance properties
-------------------


 
`PresentationReceiver.connectionList` Read only   Experimental 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with a [`PresentationConnectionList`](presentationconnectionlist) object containing a list of *incoming presentation connections.*

  
Specifications
--------------




| Specification |
| --- |
| [Presentation API # interface-presentationreceiver](https://w3c.github.io/presentation-api/#interface-presentationreceiver) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PresentationReceiver` | 59 | 79 | No | No | 46 | No | No | 59 | No | 43 | No | 7.0 |
| `connectionList` | 59 | 79 | No | No | 46 | No | No | 59 | No | 43 | No | 7.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PresentationReceiver>

ProcessingInstruction
=====================



The `ProcessingInstruction` interface represents a [processing instruction](https://www.w3.org/TR/xml/#sec-pi); that is, a [`Node`](node) which embeds an instruction targeting a specific application but that can be ignored by any other applications which don't recognize the instruction.

  **Warning:** `ProcessingInstruction` nodes are only supported in XML documents, not in HTML documents. In these, a process instruction will be considered as a comment and be represented as a [`Comment`](comment) object in the tree.

  A processing instruction may be different than the [XML declaration](https://developer.mozilla.org/en-US/docs/Web/XML/XML_introduction#xml_declaration).

  **Note:** User-defined processing instructions cannot begin with "`xml`", as `xml`-prefixed processing-instruction target names are reserved by the XML specification for particular, standard uses (see, for example, `<?xml-stylesheet ?>`.

  For example:

 
```
<?xml version="1.0"?>

```
 is a processing instruction whose `target` is `xml`.


 EventTarget Node CharacterData ProcessingInstruction

Instance properties
-------------------



*This interface also inherits properties from its parent interfaces, [`CharacterData`](characterdata), [`Node`](node), and [`EventTarget`](eventtarget).*

  
[`ProcessingInstruction.sheet`](processinginstruction/sheet) Read only 
  Returns the associated [`StyleSheet`](stylesheet) object, if any; or `null` if none.

  
[`ProcessingInstruction.target`](processinginstruction/target) Read only 
  A name identifying the application to which the instruction is targeted.

  

Instance methods
----------------


*This interface doesn't have any specific method, but inherits methods from its parent interfaces, [`CharacterData`](characterdata), [`Node`](node), and [`EventTarget`](eventtarget).*


Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-processinginstruction](https://dom.spec.whatwg.org/#interface-processinginstruction) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ProcessingInstruction` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `sheet` | 1 | 79 | 1 | No | 15 | 1 | 4.4 | 18 | 4 | 14 | 1 | 1.0 |
| `target` | 1 | 12 | 1 | 9 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |


See also
--------


* [document.createProcessingInstruction()](document/createprocessinginstruction)
* The [DOM API](document_object_model)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ProcessingInstruction>

ProgressEvent
=============



The `ProgressEvent` interface represents events measuring progress of an underlying process, like an HTTP request (for an `XMLHttpRequest`, or the loading of the underlying resource of an [`<img>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img), [`<audio>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio), [`<video>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video), [`<style>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style) or [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)).


 Event ProgressEvent

Constructor
-----------


 [`ProgressEvent()`](progressevent/progressevent)  Creates a `ProgressEvent` event with the given parameters.

  
Instance properties
-------------------



*Also inherits properties from its parent [`Event`](event)*.

  
[`ProgressEvent.lengthComputable`](progressevent/lengthcomputable) Read only 
  A boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not.

  
[`ProgressEvent.loaded`](progressevent/loaded) Read only 
  A 64-bit unsigned integer value indicating the amount of work already performed by the underlying process. The ratio of work done can be calculated by dividing `total` by the value of this property. When downloading a resource using HTTP, this only counts the body of the HTTP message, and doesn't include headers and other overhead.

  
[`ProgressEvent.total`](progressevent/total) Read only 
  A 64-bit unsigned integer representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this is the `Content-Length` (the size of the body of the message), and doesn't include the headers and other overhead.

  

Instance methods
----------------


*Inherits methods from its parent, [`Event`](event).*


Examples
--------



The following example adds a `ProgressEvent` to a new [`XMLHTTPRequest`](xmlhttprequest) and uses it to display the status of the request.

 
```
const progressBar = document.getElementById("p"),
  client = new XMLHttpRequest();
client.open("GET", "magical-unicorns");
client.onprogress = (pe) => {
  if (pe.lengthComputable) {
    progressBar.max = pe.total;
    progressBar.value = pe.loaded;
  }
};
client.onloadend = (pe) => {
  progressBar.value = pe.loaded;
};
client.send();

```


Specifications
--------------




| Specification |
| --- |
| [XMLHttpRequest Standard # interface-progressevent](https://xhr.spec.whatwg.org/#interface-progressevent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ProgressEvent` | 16 | 14 | 18 | No | ≤12.1 | 6 | 4.4 | 18 | 18 | ≤12.1 | 6 | 1.0 |
| `ProgressEvent` | 1 | 12 | 3.5 | 10 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 2 | 1.0 |
| `lengthComputable` | 1 | 12 | 3.5 | 10 | ≤12.1 | 3.1 | 4.4 | 18 | 4 | ≤12.1 | 2 | 1.0 |
| `loaded` | 1 | 12 | 3.5 | 10 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 2 | 1.0 |
| `total` | 1 | 12 | 3.5 | 10 | ≤12.1 | 3.1 | ≤37 | 18 | 4 | ≤12.1 | 2 | 1.0 |


See also
--------


* The [`Event`](event) base interface.


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ProgressEvent>

PromiseRejectionEvent
=====================



The `PromiseRejectionEvent` interface represents events which are sent to the global script context when JavaScript [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)s are rejected. These events are particularly useful for telemetry and debugging purposes.

 For details, see [Promise rejection events](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#promise_rejection_events).


 Event PromiseRejectionEvent

Constructor
-----------


 [`PromiseRejectionEvent()`](promiserejectionevent/promiserejectionevent)  Creates a `PromiseRejectionEvent` event, given the type of event ([`unhandledrejection`](window/unhandledrejection_event) or [`rejectionhandled`](window/rejectionhandled_event)) and other details.

  
Instance properties
-------------------



*Also inherits properties from its parent [`Event`](event)*.

  
[`PromiseRejectionEvent.promise`](promiserejectionevent/promise) Read only 
  The JavaScript [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that was rejected.

  
[`PromiseRejectionEvent.reason`](promiserejectionevent/reason) Read only 
  A value or [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) indicating why the promise was rejected, as passed to [`Promise.reject()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/reject).

  

Instance methods
----------------


*This interface has no unique methods; inherits methods from its parent [`Event`](event)*.


Events
------


 [`rejectionhandled`](window/rejectionhandled_event)  Fired when a JavaScript [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) is rejected, and after the rejection is handled by the promise's rejection handling code.

  [`unhandledrejection`](window/unhandledrejection_event)  Fired when a JavaScript [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) is rejected but there is no rejection handler to deal with the rejection.

  
Examples
--------



This simple example catches unhandled promise rejections and logs them for debugging purposes.

 
```
window.onunhandledrejection = (e) => {
  console.log(e.reason);
};

```


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # the-promiserejectionevent-interface](https://html.spec.whatwg.org/multipage/webappapis.html#the-promiserejectionevent-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PromiseRejectionEvent` | 49 | 79 | 69 | No | 36 | 11 | 49 | 49 | 79 | 36 | 11.3 | 5.0 |
| `PromiseRejectionEvent` | 49 | 79 | 69 | No | 36 | 11 | 49 | 49 | 79 | 36 | 11.3 | 5.0 |
| `promise` | 49 | 79 | 69 | No | 36 | 11 | 49 | 49 | 79 | 36 | 11.3 | 5.0 |
| `reason` | 49 | 79 | 69 | No | 36 | 11 | 49 | 49 | 79 | 36 | 11.3 | 5.0 |


See also
--------


* [Using promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises)
* [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
* [`rejectionhandled`](window/rejectionhandled_event)
* [`unhandledrejection`](window/unhandledrejection_event)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent>

PushManager
===========



The `PushManager` interface of the [Push API](push_api) provides a way to receive notifications from third-party servers as well as request URLs for push notifications.

 This interface is accessed via the [`ServiceWorkerRegistration.pushManager`](serviceworkerregistration/pushmanager) property.



Instance properties
-------------------


 [`PushManager.supportedContentEncodings`](pushmanager/supportedcontentencodings)  Returns an array of supported content codings that can be used to encrypt the payload of a push message.

  
Instance methods
----------------


 [`PushManager.getSubscription()`](pushmanager/getsubscription)  Retrieves an existing push subscription. It returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to a [`PushSubscription`](pushsubscription) object containing details of an existing subscription. If no existing subscription exists, this resolves to a `null` value.

  [`PushManager.permissionState()`](pushmanager/permissionstate)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to the permission state of the current [`PushManager`](pushmanager), which will be one of `'granted'`, `'denied'`, or `'prompt'`.

  [`PushManager.subscribe()`](pushmanager/subscribe)  Subscribes to a push service. It returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to a [`PushSubscription`](pushsubscription) object containing details of a push subscription. A new push subscription is created if the current service worker does not have an existing subscription.

  
### Deprecated methods


 
[`PushManager.hasPermission()`](pushmanager/haspermission)  Deprecated 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves to the `PushPermissionStatus` of the requesting webapp, which will be one of `granted`, `denied`, or `default`. Replaced by [`PushManager.permissionState()`](pushmanager/permissionstate).

  
[`PushManager.register()`](pushmanager/register)  Deprecated 
  Subscribes to a push subscription. Replaced by [`PushManager.subscribe()`](pushmanager/subscribe).

  
[`PushManager.registrations()`](pushmanager/registrations)  Deprecated 
  Retrieves existing push subscriptions. Replaced by [`PushManager.getSubscription()`](pushmanager/getsubscription).

  
[`PushManager.unregister()`](pushmanager/unregister)  Deprecated 
  Unregisters and deletes a specified subscription endpoint. In the updated API, a subscription is unregistered by calling the [`PushSubscription.unsubscribe()`](pushsubscription/unsubscribe) method.

  
Example
-------



```
this.onpush = (event) => {
  console.log(event.data);
  // From here we can write the data to IndexedDB, send it to any open
  // windows, display a notification, etc.
};

navigator.serviceWorker
  .register("serviceworker.js")
  .then((serviceWorkerRegistration) => {
    serviceWorkerRegistration.pushManager.subscribe().then(
      (pushSubscription) => {
        console.log(pushSubscription.endpoint);
        // The push subscription details needed by the application
        // server are now available, and can be sent to it using,
        // for example, an XMLHttpRequest.
      },
      (error) => {
        console.error(error);
      }
    );
  });

```

Specifications
--------------




| Specification |
| --- |
| [Push API # pushmanager-interface](https://w3c.github.io/push-api/#pushmanager-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PushManager` | 42 | 17 | 44 | No | 29 | 16Supported on macOS 13 and later | NoSee [bug 421921](https://crbug.com/421921). | 42 | 48 | 29 | 16.4 | 4.0 |
| `getSubscription` | 42 | 17 | 44 | No | 29 | 16Supported on macOS 13 and later | No | 42 | 48 | 29 | 16.4 | 4.0 |
| `hasPermission` | 42 | 17 | 44 | No | 29 | No | No | 42 | 48 | 29 | No | 4.0 |
| `permissionState` | 44 | 17 | 44 | No | 31 | 16Supported on macOS 13 and later | No | 44 | 48 | 32 | 16.4 | 4.0 |
| `register` | 42 | 17 | 44 | No | 29 | No | No | 42 | 48 | 29 | No | 4.0 |
| `registrations` | 42 | 17 | 44 | No | 29 | No | No | 42 | 48 | 29 | No | 4.0 |
| `subscribe` | 42The `options` parameter with a `applicationServerKey` value is required. | 17 | 44From Firefox 72 onwards, can only be called in response to a user gesture such as a `click` event. | No | 29 | 16Supported on macOS 13 and later | No | 42 | 48From Firefox Android 79 onwards, can only be called in response to a user gesture such as a `click` event. | 29 | 16.4 | 4.0 |
| `supportedContentEncodings` | 60 | 17 | 44 | No | 47 | 16Supported on macOS 13 and later | No | 60 | 48 | 44 | 16.4 | 4.0 |
| `unregister` | 42 | 17 | 44 | No | 29 | No | No | 42 | 48 | 29 | No | 4.0 |
| `worker_support` | 42 | 17 | 44 | No | 29 | No | No | 42 | 48 | 29 | No | 4.0 |


See also
--------


* [Push API](push_api)
* [Service Worker API](service_worker_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PushManager>

PushMessageData
===============



The `PushMessageData` interface of the [Push API](push_api) provides methods which let you retrieve the push data sent by a server in various formats.

 Unlike the similar methods in the [Fetch API](fetch_api), which only allow the method to be invoked once, these methods can be called multiple times.

 Messages received through the Push API are sent encrypted by push services and then automatically decrypted by browsers before they are made accessible through the methods of the `PushMessageData` interface.



Instance properties
-------------------


None.


Instance methods
----------------


 [`PushMessageData.arrayBuffer()`](pushmessagedata/arraybuffer)  Extracts the data as an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) object.

  [`PushMessageData.blob()`](pushmessagedata/blob)  Extracts the data as a [`Blob`](blob) object.

  [`PushMessageData.json()`](pushmessagedata/json)  Extracts the data as a [JSON](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON) object.

  [`PushMessageData.text()`](pushmessagedata/text)  Extracts the data as a plain text string.

  
Examples
--------



```
self.addEventListener("push", (event) => {
  const obj = event.data.json();

  if (obj.action === "subscribe" || obj.action === "unsubscribe") {
    fireNotification(obj, event);
    port.postMessage(obj);
  } else if (obj.action === "init" || obj.action === "chatMsg") {
    port.postMessage(obj);
  }
});

```

Specifications
--------------




| Specification |
| --- |
| [Push API # pushmessagedata-interface](https://w3c.github.io/push-api/#pushmessagedata-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PushMessageData` | 50 | 17 | 44 | No | 37 | 16Supported on macOS 13 and later | NoSee [bug 421921](https://crbug.com/421921). | 50 | 48 | 37 | 16.4 | 5.0 |
| `arrayBuffer` | 50 | 17 | 44 | No | 37 | 16Supported on macOS 13 and later | No | 50 | 48 | 37 | 16.4 | 5.0 |
| `blob` | 50 | 17 | 44 | No | 37 | 16Supported on macOS 13 and later | No | 50 | 48 | 37 | 16.4 | 5.0 |
| `json` | 50 | 17 | 44 | No | 37 | 16Supported on macOS 13 and later | No | 50 | 48 | 37 | 16.4 | 5.0 |
| `text` | 50 | 17 | 44 | No | 37 | 16Supported on macOS 13 and later | No | 50 | 48 | 37 | 16.4 | 5.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PushMessageData>

PushSubscriptionOptions
=======================



The `PushSubscriptionOptions` interface of the [Push API](push_api) represents the options associated with a push subscription.

 The read-only `PushSubscriptionOptions` object is returned by calling [`PushSubscription.options`](pushsubscription/options) on a [`PushSubscription`](pushsubscription). This interface has no constructor of its own.



Instance properties
-------------------


 
[`PushSubscriptionOptions.userVisibleOnly`](pushsubscriptionoptions/uservisibleonly) Read only 
   A boolean value indicating that the returned push subscription will only be used for messages whose effect is made visible to the user. 

  
[`PushSubscriptionOptions.applicationServerKey`](pushsubscriptionoptions/applicationserverkey) Read only 
   A public key your push server will use to send messages to client apps via a push server. 

  
Examples
--------



Calling [`PushSubscription.options`](pushsubscription/options) on a [`PushSubscription`](pushsubscription) returns a `PushSubscriptionOptions` object. In the example below this is printed to the console.

 
```
navigator.serviceWorker.ready.then((reg) => {
  reg.pushManager.getSubscription().then((subscription) => {
    const options = subscription.options;
    console.log(options); // a PushSubscriptionOptions object
  });
});

```


Specifications
--------------




| Specification |
| --- |
| [Push API # dom-pushsubscriptionoptions](https://w3c.github.io/push-api/#dom-pushsubscriptionoptions) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `PushSubscriptionOptions` | 54 | 17 | 44 | No | 41 | 16Supported on macOS 13 and later | NoSee [bug 421921](https://crbug.com/421921). | 54 | 48 | 41 | 16.4 | 6.0 |
| `applicationServerKey` | 54 | 17 | 44 | No | 41 | 16Supported on macOS 13 and later | No | 54 | 48 | 41 | 16.4 | 6.0 |
| `userVisibleOnly` | 54 | 17 | No | No | 41 | 16Supported on macOS 13 and later | No | 54 | No | 41 | 16.4 | 6.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/PushSubscriptionOptions>

RadioNodeList
=============



The `RadioNodeList` interface represents a collection of radio elements in a [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) or a [`<fieldset>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset) element.


 NodeList RadioNodeList

Instance properties
-------------------



*The `RadioNodeList` interface inherits the properties of* [`NodeList`](nodelist).

  [`RadioNodeList.value`](radionodelist/value)  If the underlying element collection contains radio buttons, the `value` property represents the checked radio button. On retrieving the `value` property, the `value` of the currently `checked` radio button is returned as a string. If the collection does not contain any radio buttons or none of the radio buttons in the collection is in `checked` state, the empty string is returned. On setting the `value` property, the first radio button input element whose `value` property is equal to the new value will be set to `checked`.

  

Instance methods
----------------


*The `RadioNodeList` interface inherits the methods of* [`NodeList`](nodelist).


Specifications
--------------




| Specification |
| --- |
| [HTML Standard # radionodelist](https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#radionodelist) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `RadioNodeList` | 21 | 12 | 33 | 9 | 15 | 7 | 4.4 | 25 | 33 | 14 | 7 | 1.5 |
| `value` | 21 | 12 | 33 | 9 | 15 | 7 | 4.4 | 25 | 33 | 14 | 7 | 1.5 |


See also
--------


* The [`<form>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form), [`<fieldset>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset), [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) elements.


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList>

ReadableByteStreamController
============================



 The `ReadableByteStreamController` interface of the [Streams API](streams_api) represents a controller for a [readable byte stream](streams_api/using_readable_byte_streams). It allows control of the state and internal queue of a [`ReadableStream`](readablestream) with an underlying byte source, and enables efficient zero-copy transfer of data from the underlying source to a consumer when the stream's internal queue is empty. 

  An instance of this controller type is created if an `underlyingSource` object with the property `type="bytes"` is passed as an argument to the [`ReadableStream()` constructor](readablestream/readablestream#type). The `underlyingSource` object may also define [`start()`](readablestream/readablestream#start) and [`pull()`](readablestream/readablestream#pull) callback functions. These are called with the controller as a parameter, in order to setup the underlying source, and request data when needed. 

  The underlying source uses the controller to supply data to the stream via its [`byobRequest`](#readablebytestreamcontroller.byobrequest) property or [`enqueue()`](#readablebytestreamcontroller.enqueue) method. [`byobRequest`](#readablebytestreamcontroller.byobrequest) is a [`ReadableStreamBYOBRequest`](readablestreambyobrequest) object that represents a pending request from a consumer to make a zero-copy transfer of data direct to a consumer. `byobRequest` must be used to copy data if it exists (do not use `enqueue()` in this case)! If the underlying source needs to pass data to the stream and `byobRequest` is `null` then the source can call [`enqueue()`](#readablebytestreamcontroller.enqueue) to add the data to the stream's internal queues. 

  Note that the [`byobRequest`](#readablebytestreamcontroller.byobrequest) is only created in "BYOB mode" when there is a request from a reader and the stream's internal queue is empty. "BYOB mode" is enabled when using a [`ReadableStreamBYOBReader`](readablestreambyobreader) (typically constructed by calling [`ReadableStream.getReader()`](readablestream/getreader) with the argument `{ mode: 'byob' }`). It is also enabled when using a default reader and [`autoAllocateChunkSize`](readablestream/readablestream#autoallocatechunksize) is specified in the [`ReadableController()` constructor](readablestream/readablestream#autoallocatechunksize). 

  An underlying byte source can also use the controller to [`close()`](#readablebytestreamcontroller.close) the stream when all the data has been sent and report errors from the underlying source using [`error()`](#readablebytestreamcontroller.error). The controller's [`desiredSize`](#readablebytestreamcontroller.desiredsize) property is used to apply "backpressure", informing the underlying source of the size of the internal queue (small values indicate that the queue is filling up, hinting to the underlying source that it is be desirable to pause or throttle the inflow). 

 Note that even though the controller is primarily used by the underlying byte source, there is no reason it cannot be stored used by other parts of the system to signal the stream.



Constructor
-----------


None. `ReadableByteStreamController` instances are automatically created if an `underlyingSource` with the property `type="bytes"` is passed to the [`ReadableStream()` constructor](readablestream/readablestream#type).


Instance properties
-------------------


 
[`ReadableByteStreamController.byobRequest`](readablebytestreamcontroller/byobrequest) Read only 
  Returns the current BYOB pull request, or `null` if there no outstanding request.

  
[`ReadableByteStreamController.desiredSize`](readablebytestreamcontroller/desiredsize) Read only 
  Returns the desired size required to fill the stream's internal queue.

  
Instance methods
----------------


 [`ReadableByteStreamController.close()`](readablebytestreamcontroller/close)  Closes the associated stream.

  [`ReadableByteStreamController.enqueue()`](readablebytestreamcontroller/enqueue)  Enqueues a given chunk in the associated stream.

  [`ReadableByteStreamController.error()`](readablebytestreamcontroller/error)  Causes any future interactions with the associated stream to error.

  
Examples
--------



The controller is used by an underlying source to transfer or enqueue data, to signal that the stream has no more data (has closed) or has errored. It is also used to signal the underlying source from "upstream" of the desired data rate, using [`desiredSize`](readablebytestreamcontroller/desiredsize).

 The example in [Using readable byte streams](streams_api/using_readable_byte_streams), in particular [Creating a readable socket push byte stream](streams_api/using_readable_byte_streams#creating_a_readable_socket_push_byte_stream), show most of these cases.



Specifications
--------------




| Specification |
| --- |
| [Streams Standard # rbs-controller-class](https://streams.spec.whatwg.org/#rbs-controller-class) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ReadableByteStreamController` | 89 | 89 | 102 | No | 75 | No | 89 | 89 | 102 | 63 | No | 15.0 |
| `byobRequest` | 89 | 89 | 102 | No | 75 | No | 89 | 89 | 102 | 63 | No | 15.0 |
| `close` | 89 | 89 | 102 | No | 75 | No | 89 | 89 | 102 | 63 | No | 15.0 |
| `desiredSize` | 89 | 89 | 102 | No | 75 | No | 89 | 89 | 102 | 63 | No | 15.0 |
| `enqueue` | 89 | 89 | 102 | No | 75 | No | 89 | 89 | 102 | 63 | No | 15.0 |
| `error` | 89 | 89 | 102 | No | 75 | No | 89 | 89 | 102 | 63 | No | 15.0 |


See also
--------


* [Using readable byte streams](streams_api/using_readable_byte_streams)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ReadableByteStreamController>

ReadableStreamBYOBReader
========================



 The `ReadableStreamBYOBReader` interface of the [Streams API](streams_api) defines a reader for a [`ReadableStream`](readablestream) that supports zero-copy reading from an underlying byte source. It is used for efficient copying from underlying sources where the data is delivered as an "anonymous" sequence of bytes, such as files. 

  An instance of this reader type should usually be obtained by calling [`ReadableStream.getReader()`](readablestream/getreader) on the stream, specifying `mode: "byob"` in the options parameter. The readable stream must have an *underlying byte source*. In other words, it must have been [constructed](readablestream/readablestream) specifying an underlying source with [`type: "bytes"`](readablestream/readablestream#type)). 

  Using this kind of reader, a [`read()`](#readablestreambyobreader.read) request when the readable stream's internal queues are empty will result in a zero copy transfer from the underlying source (bypassing the stream's internal queues). If the internal queues are not empty, a `read()` will satisfy the request from the buffered data. 

  Note that the methods and properties are similar to those for the default reader ([`ReadableStreamDefaultReader`](readablestreamdefaultreader)). The `read()` method differs in that it provide a view into which data should be written. 



Constructor
-----------


 [`ReadableStreamBYOBReader()`](readablestreambyobreader/readablestreambyobreader)  Creates and returns a `ReadableStreamBYOBReader` object instance.

  
Instance properties
-------------------


 
[`ReadableStreamBYOBReader.closed`](readablestreambyobreader/closed) Read only 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process.

  
Instance methods
----------------


 [`ReadableStreamBYOBReader.cancel()`](readablestreambyobreader/cancel)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. The supplied `reason` argument will be given to the underlying source, which may or may not use it.

  [`ReadableStreamBYOBReader.read()`](readablestreambyobreader/read)  Passes a view into which data must be written, and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with the next chunk in the stream or rejects with an indication that the stream is closed or has errored.

  [`ReadableStreamBYOBReader.releaseLock()`](readablestreambyobreader/releaselock)  Releases the reader's lock on the stream.

  
Examples
--------



The example below is taken from the live examples in [Using readable byte streams](streams_api/using_readable_byte_streams#examples).

  First create the reader using [`ReadableStream.getReader()`](readablestream/getreader) on the stream, specifying `mode: "byob"` in the options parameter. As this is a "Bring Your Own Buffer" reader, we also need to create an `ArrayBuffer` to read into. 

 
```
const reader = stream.getReader({ mode: "byob" });
let buffer = new ArrayBuffer(4000);

```
  A function that uses the reader is shown below. This calls the `read()` method recursively to read data into the buffer. The method takes a [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) [typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) which is a view over the part of the original array buffer that has not yet been written. The parameters of the view are calculated from the data that was received in previous calls, which define an offset into the original array buffer. 

 
```
readStream(reader);

function readStream(reader) {
  let bytesReceived = 0;
  let offset = 0;

  while (offset < buffer.byteLength) {
    // read() returns a promise that resolves when a value has been received
    reader
      .read(new Uint8Array(buffer, offset, buffer.byteLength - offset))
      .then(function processBytes({ done, value }) {
        // Result objects contain two properties:
        // done - true if the stream has already given all its data.
        // value - some data. Always undefined when done is true.

        if (done) {
          // There is no more data in the stream
          return;
        }

        buffer = value.buffer;
        offset += value.byteLength;
        bytesReceived += value.byteLength;

        // Read some more, and call this function again
        return reader
          .read(new Uint8Array(buffer, offset, buffer.byteLength - offset))
          .then(processBytes);
      });
  }
}

```
 When there is no more data in the stream, the `read()` method resolves with an object with the property `done` set to `true`, and the function returns.

 The [`ReadableStreamBYOBReader.closed`](readablestreambyobreader/closed) property returns a promise that can be used to monitor for the stream being closed or errored, or the reader lock being released.

 
```
reader.closed
  .then(() => {
    // Resolved - code to handle stream closing
  })
  .catch(() => {
    // Rejected - code to handle error
  });

```
  To cancel the stream call [`ReadableStreamBYOBReader.cancel()`](readablestreambyobreader/cancel), optionally specifying a *reason*. This returns a promise that will resolve when the stream has been cancelled. When the stream is cancelled the controller will in turn call `cancel()` on the underlying source, passing in the optional reason. 

 The example code in [Using readable byte streams](streams_api/using_readable_byte_streams#examples) calls the cancel method when a button is pressed, as shown:

 
```
button.addEventListener("click", () => {
  reader.cancel("user choice").then(() => console.log("cancel complete"));
});

```
 The consumer can also call `releaseLock()` to release the reader's hold on the stream, but only when no read is pending:

 
```
reader.releaseLock();

```


Specifications
--------------




| Specification |
| --- |
| [Streams Standard # byob-reader-class](https://streams.spec.whatwg.org/#byob-reader-class) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ReadableStreamBYOBReader` | 89 | 89 | 102 | No | 75 | No | 89 | 89 | 102 | 63 | No | 15.0 |
| `ReadableStreamBYOBReader` | 89 | 89 | 102 | No | 75 | No | 89 | 89 | 102 | 63 | No | 15.0 |
| `cancel` | 89 | 89 | 102 | No | 75 | No | 89 | 89 | 102 | 63 | No | 15.0 |
| `closed` | 89 | 89 | 102 | No | 75 | No | 89 | 89 | 102 | 63 | No | 15.0 |
| `read` | 89 | 89 | 102 | No | 75 | No | 89 | 89 | 102 | 63 | No | 15.0 |
| `releaseLock` | 89 | 89 | 102 | No | 75 | No | 89 | 89 | 102 | 63 | No | 15.0 |


See also
--------


* [Using readable byte stream](streams_api/using_readable_byte_streams)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamBYOBReader>

Range
=====



The `Range` interface represents a fragment of a document that can contain nodes and parts of text nodes.

 A range can be created by using the [`Document.createRange()`](document/createrange) method. Range objects can also be retrieved by using the [`getRangeAt()`](selection/getrangeat) method of the [`Selection`](selection) object or the [`caretRangeFromPoint()`](document/caretrangefrompoint) method of the [`Document`](document) object.

 There also is the [`Range()`](range/range) constructor available.


 AbstractRange Range

Instance properties
-------------------



*There are no inherited properties.*

  
[`Range.collapsed`](range/collapsed) Read only 
  Returns a boolean value indicating whether the range's start and end points are at the same position.

  
[`Range.commonAncestorContainer`](range/commonancestorcontainer) Read only 
  Returns the deepest [`Node`](node) that contains the `startContainer` and `endContainer` nodes.

  
[`Range.endContainer`](range/endcontainer) Read only 
  Returns the [`Node`](node) within which the `Range` ends.

  
[`Range.endOffset`](range/endoffset) Read only 
  Returns a number representing where in the `endContainer` the `Range` ends.

  
[`Range.startContainer`](range/startcontainer) Read only 
  Returns the [`Node`](node) within which the `Range` starts.

  
[`Range.startOffset`](range/startoffset) Read only 
  Returns a number representing where in the `startContainer` the `Range` starts.

  

Constructor
-----------


 [`Range()`](range/range)  Returns a `Range` object with the global [`Document`](document) as its start and end.

  
Instance methods
----------------



*There are no inherited methods.*

  [`Range.collapse()`](range/collapse)  Collapses the `Range` to one of its boundary points.

  [`Range.compareBoundaryPoints()`](range/compareboundarypoints)  Compares the boundary points of the `Range` with another `Range`.

  
[`Range.compareNode()`](range/comparenode)  Deprecated   Non-standard 
  Returns a constant representing whether the [`Node`](node) is before, after, inside, or surrounding the range.

  [`Range.comparePoint()`](range/comparepoint)  Returns -1, 0, or 1 indicating whether the point occurs before, inside, or after the `Range`.

  [`Range.cloneContents()`](range/clonecontents)  Returns a [`DocumentFragment`](documentfragment) copying the nodes of a `Range`.

  [`Range.cloneRange()`](range/clonerange)  Returns a `Range` object with boundary points identical to the cloned `Range`.

  [`Range.createContextualFragment()`](range/createcontextualfragment)  Returns a [`DocumentFragment`](documentfragment) created from a given string of code.

  [`Range.deleteContents()`](range/deletecontents)  Removes the contents of a `Range` from the [`Document`](document).

  [`Range.detach()`](range/detach)  Does nothing. Kept for compatibility.

  [`Range.extractContents()`](range/extractcontents)  Moves contents of a `Range` from the document tree into a [`DocumentFragment`](documentfragment).

  [`Range.getBoundingClientRect()`](range/getboundingclientrect)  Returns a [`DOMRect`](domrect) object which bounds the entire contents of the `Range`; this would be the union of all the rectangles returned by [`range.getClientRects()`](range/getclientrects).

  [`Range.getClientRects()`](range/getclientrects)  Returns a list of [`DOMRect`](domrect) objects that aggregates the results of [`Element.getClientRects()`](element/getclientrects) for all the elements in the `Range`.

  [`Range.isPointInRange()`](range/ispointinrange)  Returns a `boolean` indicating whether the given point is in the `Range`.

  [`Range.insertNode()`](range/insertnode)  Insert a [`Node`](node) at the start of a `Range`.

  [`Range.intersectsNode()`](range/intersectsnode)  Returns a `boolean` indicating whether the given node intersects the `Range`.

  [`Range.selectNode()`](range/selectnode)  Sets the `Range` to contain the [`Node`](node) and its contents.

  [`Range.selectNodeContents()`](range/selectnodecontents)  Sets the `Range` to contain the contents of a [`Node`](node).

  [`Range.setEnd()`](range/setend)  Sets the end position of a `Range`.

  [`Range.setStart()`](range/setstart)  Sets the start position of a `Range`.

  [`Range.setEndAfter()`](range/setendafter)  Sets the end position of a `Range` relative to another [`Node`](node).

  [`Range.setEndBefore()`](range/setendbefore)  Sets the end position of a `Range` relative to another [`Node`](node).

  [`Range.setStartAfter()`](range/setstartafter)  Sets the start position of a `Range` relative to another [`Node`](node).

  [`Range.setStartBefore()`](range/setstartbefore)  Sets the start position of a `Range` relative to another [`Node`](node).

  [`Range.surroundContents()`](range/surroundcontents)  Moves content of a `Range` into a new [`Node`](node).

  [`Range.toString()`](range/tostring)  Returns the text of the `Range`.

  

Specifications
--------------




| Specification |
| --- |
| [DOM Standard # interface-range](https://dom.spec.whatwg.org/#interface-range) |
| [DOM Parsing and Serialization # extensions-to-the-range-interface](https://w3c.github.io/DOM-Parsing/#extensions-to-the-range-interface) |
| [CSSOM View Module # extensions-to-the-range-interface](https://w3c.github.io/csswg-drafts/cssom-view/#extensions-to-the-range-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Range` | 29 | 15 | 24 | No | 16 | 8 | 4.4 | 29 | 24 | 16 | 8 | 2.0 |
| `Range` | 1 | 12 | 1Starting with Firefox 13, the `Range` object throws a `DOMException` as defined in DOM 4, instead of a `RangeException` defined in prior specifications. | 9 | 9 | 1 | 4.4 | 18 | 4Starting with Firefox 13, the `Range` object throws a `DOMException` as defined in DOM 4, instead of a `RangeException` defined in prior specifications. | 10.1 | 1 | 1.0 |
| `cloneContents` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `cloneRange` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `collapse` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `collapsed` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `commonAncestorContainer` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `compareBoundaryPoints` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `compareNode` | 1–45 | No | 1–3 | No | 15–32 | 3 | 4.4–45 | 18–45 | No | 14–32 | 1 | 1.0–5.0 |
| `comparePoint` | 1 | 17 | 1 | No | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `createContextualFragment` | 1 | 12 | 1 | 10 | ≤12.1 | 1 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `deleteContents` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `detach` | 1Starting in Chrome 37, this method is a no-op and has no effect. | 12 | 1–15Starting in Firefox 15.0, this method is a no-op and has no effect. | 9 | 9Starting in Opera 24, this method is a no-op and has no effect. | 1Since August 2015 this method is a no-op in [WebKit-based browsers](https://webkit.org/b/148454). | 4.4Starting in Chrome 37, this method is a no-op and has no effect. | 18Starting in Chrome 37, this method is a no-op and has no effect. | 4–15Starting in Firefox 15.0, this method is a no-op and has no effect. | 10.1Starting in Opera 24, this method is a no-op and has no effect. | 1Since August 2015 this method is a no-op in [WebKit-based browsers](https://webkit.org/b/148454). | 1.0Starting in Samsung Internet 3.0, this method is a no-op and has no effect. |
| `endContainer` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `endOffset` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `extractContents` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `getBoundingClientRect` | 4 | 12 | 4 | 9 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 |
| `getClientRects` | 4 | 12 | 4 | 9 | ≤12.1 | 5 | ≤37 | 18 | 4 | ≤12.1 | 4 | 1.0 |
| `insertNode` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `intersectsNode` | 1 | 17 | 17 | No | ≤12.1 | 3 | 4.4 | 18 | 19 | ≤12.1 | 1 | 1.0 |
| `isPointInRange` | 1 | 15 | 1 | No | ≤12.1 | 3 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
| `selectNode` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `selectNodeContents` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `setEnd` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `setEndAfter` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `setEndBefore` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `setStart` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `setStartAfter` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `setStartBefore` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `startContainer` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `startOffset` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `surroundContents` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |
| `toString` | 1 | 12 | 1 | 9 | 9 | 1 | 4.4 | 18 | 4 | 10.1 | 1 | 1.0 |


See also
--------


* [The DOM interfaces index](document_object_model)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Range>

ReadableStream
==============



The `ReadableStream` interface of the [Streams API](streams_api) represents a readable stream of byte data. The [Fetch API](fetch_api) offers a concrete instance of a `ReadableStream` through the [`body`](response/body) property of a [`Response`](response) object.

 `ReadableStream` is a [transferable object](web_workers_api/transferable_objects).



Constructor
-----------


 [`ReadableStream()`](readablestream/readablestream)  Creates and returns a readable stream object from the given handlers.

  
Instance properties
-------------------


 
[`ReadableStream.locked`](readablestream/locked) Read only 
  Returns a boolean indicating whether or not the readable stream is locked to a reader.

  
Instance methods
----------------


 [`ReadableStream.cancel()`](readablestream/cancel)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. The supplied `reason` argument will be given to the underlying source, which may or may not use it.

  [`ReadableStream.getReader()`](readablestream/getreader)  Creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released.

  [`ReadableStream.pipeThrough()`](readablestream/pipethrough)  Provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair.

  [`ReadableStream.pipeTo()`](readablestream/pipeto)  Pipes the current ReadableStream to a given [`WritableStream`](writablestream) and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that fulfills when the piping process completes successfully, or rejects if any errors were encountered.

  [`ReadableStream.tee()`](readablestream/tee)  The `tee` method [tees](https://streams.spec.whatwg.org/#tee-a-readable-stream) this readable stream, returning a two-element array containing the two resulting branches as new [`ReadableStream`](readablestream) instances. Each of those streams receives the same incoming data.

  
Async iteration
---------------



 `ReadableStream` implements the [async iterable protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols). This enables asynchronous iteration over the chunks in a stream using the [`for await...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) syntax: 

 
```
const stream = new ReadableStream(getSomeSource());

for await (const chunk of stream) {
  // Do something with each 'chunk'
}

```
  The async iterator consumes the stream until it runs out of data or otherwise terminates. The loop can also exit early due to a `break`, `throw`, or `return` statement. 

  While iterating, the stream is locked to prevent other consumers from acquiring a reader (attempting to iterate over a stream that is already locked will throw a `TypeError`). This lock is released when the loop exits. 

  By default, exiting the loop will also cancel the stream, so that it can no longer be used. To continue to use a stream after exiting the loop, pass `{ preventCancel: true }` to the stream's `values()` method: 

 
```
for await (const chunk of stream.values({ preventCancel: true })) {
  // Do something with 'chunk'
  break;
}
// Acquire a reader for the stream and continue reading ...

```


Examples
--------


### Fetch stream



In the following example, an artificial [`Response`](response) is created to stream HTML fragments fetched from another resource to the browser.

 It demonstrates the usage of a [`ReadableStream`](readablestream) in combination with a [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array).

 
```
fetch("https://www.example.org")
  .then((response) => response.body)
  .then((rb) => {
    const reader = rb.getReader();

    return new ReadableStream({
      start(controller) {
        // The following function handles each data chunk
        function push() {
          // "done" is a Boolean and value a "Uint8Array"
          reader.read().then(({ done, value }) => {
            // If there is no more data to read
            if (done) {
              console.log("done", done);
              controller.close();
              return;
            }
            // Get the data and send it to the browser via the controller
            controller.enqueue(value);
            // Check chunks by logging to the console
            console.log(done, value);
            push();
          });
        }

        push();
      },
    });
  })
  .then((stream) =>
    // Respond with our stream
    new Response(stream, { headers: { "Content-Type": "text/html" } }).text()
  )
  .then((result) => {
    // Do things with result
    console.log(result);
  });

```


### Convert async iterator to stream



Converting an [(async) iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators) to a readable stream:

 
```
function iteratorToStream(iterator) {
  return new ReadableStream({
    async pull(controller) {
      const { value, done } = await iterator.next();

      if (done) {
        controller.close();
      } else {
        controller.enqueue(value);
      }
    },
  });
}

```
 This works with both async and non-async iterators.



### Async iteration of a stream using for await...of



This example shows how you can process the `fetch()` response using a [`for await...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) loop to iterate through the arriving chunks.

 
```
const response = await fetch("https://www.example.org");
let total = 0;

// Iterate response.body (a ReadableStream) asynchronously
for await (const chunk of response.body) {
  // Do something with each chunk
  // Here we just accumulate the size of the response.
  total += chunk.length;
}

// Do something with the total
console.log(total);

```


Specifications
--------------




| Specification |
| --- |
| [Streams Standard # rs-class](https://streams.spec.whatwg.org/#rs-class) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `@@asyncIterator` | No | No | 110 | No | No | No | No | No | 110 | No | No | No |
| `ReadableStream` | 52 | 79 | 65 | No | 39 | 10.1 | 52 | 52 | 65 | 41 | 10.3 | 6.0 |
| `ReadableStream` | 43 | 14 | 65 | No | 30 | 10.1 | 43 | 43 | 65 | 30 | 10.3 | 4.0 |
| `cancel` | 43 | 14 | 65 | No | 30 | 10.1 | 43 | 43 | 65 | 30 | 10.3 | 4.0 |
| `getReader` | 43 | 14 | 65 | No | 30 | 10.1 | 43 | 43 | 65 | 30 | 10.3 | 4.0 |
| `locked` | 52 | 14 | 65 | No | 39 | 10.1 | 52 | 52 | 65 | 41 | 10.3 | 6.0 |
| `pipeThrough` | 59 | 79 | 102 | No | 46 | 10.1 | 59 | 59 | 102 | 43 | 10.3 | 7.0 |
| `pipeTo` | 59 | 79 | 100 | No | 46 | 10.1 | 59 | 59 | 100 | 43 | 10.3 | 7.0 |
| `tee` | 52 | 79 | 65 | No | 39 | 10.1 | 52 | 52 | 65 | 41 | 10.3 | 6.0 |
| `transferable` | 87 | 87 | 103 | No | 73 | No | 87 | 87 | 103 | 62 | No | 14.0 |
| `values` | No | No | 110 | No | No | No | No | No | 110 | No | No | No |


See also
--------


* [WHATWG Stream Visualizer](https://whatwg-stream-visualizer.glitch.me/), for a basic visualization of readable, writable, and transform streams.
* [web-streams-polyfill](https://github.com/MattiasBuelens/web-streams-polyfill) or [sd-streams](https://github.com/stardazed/sd-streams) - polyfills


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream>

ReadableStreamBYOBRequest
=========================



The `ReadableStreamBYOBRequest` interface of the [Streams API](streams_api) represents a "pull request" for data from an underlying source that will made as a zero-copy transfer to a consumer (bypassing the stream's internal queues).

  `ReadableStreamBYOBRequest` objects are created in "BYOB mode" when a consumer makes a request for data and the stream's internal queue is *empty*. (The stream will resolve the consumer's request directly if it already has buffered data). An underlying byte source can access active BYOB requests through its controller's [`ReadableByteStreamController.byobRequest`](readablebytestreamcontroller/byobrequest) property, which will be set to `null` if there is no outstanding request. 

  An underlying source that supports "BYOB mode" should check for [`ReadableByteStreamController.byobRequest`](readablebytestreamcontroller/byobrequest) and must use it for transferring data, if present. If data arrives from the underlying source when [`ReadableByteStreamController.byobRequest`](readablebytestreamcontroller/byobrequest) is `null`, it can be queued using [`ReadableByteStreamController.enqueue()`](readablebytestreamcontroller/enqueue). This might happen when an underlying push source receives new data when the stream's internal buffers are not empty. 

  An underlying source uses the request by writing data to the BYOB request's [`view`](#readablestreambyobrequest.view) and then calling [`respond()`](#readablestreambyobrequest.respond), or by calling [`respondWithNewView()`](#readablestreambyobrequest.respondwithnewview) and passing a new view as an argument. Note that the "new view" must actually be a view over the *same* buffer as the original `view`, starting at the same offset. This might be used to return a shorter buffer if the underlying source is unable to fill the entire original view. 

  Note that a [`ReadableByteStreamController`](readablebytestreamcontroller) is only created for underlying sources when `type="bytes"` is specified for the source in the [`ReadableStream()` constructor](readablestream/readablestream#type). "BYOB mode" is enabled when either [`autoAllocateChunkSize`](readablestream/readablestream#autoallocatechunksize) is specified in the [`ReadableController()` constructor](readablestream/readablestream#autoallocatechunksize) or when using a [`ReadableStreamBYOBReader`](readablestreambyobreader) (typically constructed by calling [`ReadableStream.getReader()`](readablestream/getreader) with the argument `{ mode: 'byob' }`). 



Constructor
-----------


None. `ReadableStreamBYOBRequest` instance is created automatically by `ReadableByteStreamController` as needed.


Instance properties
-------------------


 
[`ReadableStreamBYOBRequest.view`](readablestreambyobrequest/view) Read only 
   Returns the current view. This is a view on a buffer that will be transferred to the consumer when `ReadableStreamBYOBRequest.respond()` is called. 

  
Instance methods
----------------


 [`ReadableStreamBYOBRequest.respond()`](readablestreambyobrequest/respond)   Signals the associated readable byte stream that the specified number of bytes were written into the current [`view`](#readablestreambyobrequest.view), which then causes the pending request from the consumer to be resolved. Note that after this method is called the `view` is transferred and no longer modifiable. 

  [`ReadableStreamBYOBRequest.respondWithNewView()`](readablestreambyobrequest/respondwithnewview)   Signals to the associated readable byte stream view passed as an argument should be transferred to the consumer of the readable byte stream. This new view must use the same buffer as the original [`view`](#readablestreambyobrequest.view), start at the same offset, and be the same length or shorter. Note that after this method is called the `view` is transferred and no longer modifiable. 

  
Examples
--------



The following code is taken from the live example in [Using readable byte streams > Creating a readable socket push byte stream](streams_api/using_readable_byte_streams#creating_a_readable_socket_push_byte_stream).

  A push underlying byte source with data to transfer should first check that [`controller.byobRequest`](readablebytestreamcontroller/byobrequest) is non-`null`. Pul A pull underlying byte source would only need this check if auto chunk allocation was not enabled and it was used with a default reader. 

 
```
if (controller.byobRequest) {
  /\* code to transfer data \*/
}

```
  There are two ways to read data into a `ReadableStreamBYOBRequest` and then transfer it. The first is to write the data into the [`ReadableStreamBYOBRequest.view`](readablestreambyobrequest/view) property and then call [`ReadableStreamBYOBRequest.respond()`](readablestreambyobrequest/respond) to indicate the amount of data to be transferred. After the operation the `byobRequest.view` is detached and the request should be discarded. 

 The code below shows this case using a hypothetical `readInto()` method to copy data into the view:

 
```
const v = controller.byobRequest.view;
bytesRead = socket.readInto(v.buffer, v.byteOffset, v.byteLength);
controller.byobRequest.respond(bytesRead);

```
  The other approach is to call [`ReadableStreamBYOBRequest.respondWithNewView()`](readablestreambyobrequest/respondwithnewview) passing your own view on the same underlying backing data. Note that this just another way of specifying the range of the underlying buffer/memory backing that is actually transferred. The `respondWithNewView` equivalent to the code above would be: 

 
```
const v = controller.byobRequest.view;
bytesRead = socket.readInto(v.buffer, v.byteOffset, v.byteLength);
const newView = new Uint8Array(v.buffer, v.byteOffset, bytesRead);
controller.byobRequest.respondWithNewView(newView);

```


Specifications
--------------




| Specification |
| --- |
| [Streams Standard # rs-byob-request-class](https://streams.spec.whatwg.org/#rs-byob-request-class) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ReadableStreamBYOBRequest` | 89 | 89 | 102 | No | 75 | No | 89 | 89 | 102 | 63 | No | 15.0 |
| `respond` | 89 | 89 | 102 | No | 75 | No | 89 | 89 | 102 | 63 | No | 15.0 |
| `respondWithNewView` | 89 | 89 | 102 | No | 75 | No | 89 | 89 | 102 | 63 | No | 15.0 |
| `view` | 89 | 89 | 102 | No | 75 | No | 89 | 89 | 102 | 63 | No | 15.0 |


See also
--------


* [Using readable byte stream](streams_api/using_readable_byte_streams)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamBYOBRequest>

ReadableStreamDefaultController
===============================


The `ReadableStreamDefaultController` interface of the [Streams API](streams_api) represents a controller allowing control of a [`ReadableStream`](readablestream)'s state and internal queue. Default controllers are for streams that are not byte streams.


Constructor
-----------


None. `ReadableStreamDefaultController` instances are created automatically during `ReadableStream` construction.


Instance properties
-------------------


 
[`ReadableStreamDefaultController.desiredSize`](readablestreamdefaultcontroller/desiredsize) Read only 
  Returns the desired size required to fill the stream's internal queue.

  
Instance methods
----------------


 [`ReadableStreamDefaultController.close()`](readablestreamdefaultcontroller/close)  Closes the associated stream.

  [`ReadableStreamDefaultController.enqueue()`](readablestreamdefaultcontroller/enqueue)  Enqueues a given chunk in the associated stream.

  [`ReadableStreamDefaultController.error()`](readablestreamdefaultcontroller/error)  Causes any future interactions with the associated stream to error.

  
Examples
--------



In the following simple example, a custom `ReadableStream` is created using a constructor (see our [Simple random stream example](https://mdn.github.io/dom-examples/streams/simple-random-stream/) for the full code). The `start()` function generates a random string of text every second and enqueues it into the stream. A `cancel()` function is also provided to stop the generation if [`ReadableStream.cancel()`](readablestream/cancel) is called for any reason.

 Note that a [`ReadableStreamDefaultController`](readablestreamdefaultcontroller) object is provided as the parameter of the `start()` and `pull()` functions.

 When a button is pressed, the generation is stopped, the stream is closed using [`ReadableStreamDefaultController.close()`](readablestreamdefaultcontroller/close), and another function is run, which reads the data back out of the stream.

 
```
let interval;
const stream = new ReadableStream({
  start(controller) {
    interval = setInterval(() => {
      let string = randomChars();

      // Add the string to the stream
      controller.enqueue(string);

      // show it on the screen
      let listItem = document.createElement("li");
      listItem.textContent = string;
      list1.appendChild(listItem);
    }, 1000);

    button.addEventListener("click", () => {
      clearInterval(interval);
      fetchStream();
      controller.close();
    });
  },
  pull(controller) {
    // We don't really need a pull in this example
  },
  cancel() {
    // This is called if the reader cancels,
    // so we should stop generating strings
    clearInterval(interval);
  },
});

```


Specifications
--------------




| Specification |
| --- |
| [Streams Standard # rs-default-controller-class](https://streams.spec.whatwg.org/#rs-default-controller-class) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ReadableStreamDefaultController` | 89 | 89 | 65 | No | 75 | 16.4 | 89 | 89 | 65 | 63 | 16.4 | 15.0 |
| `close` | 89 | 89 | 65 | No | 75 | 16.4 | 89 | 89 | 65 | 63 | 16.4 | 15.0 |
| `desiredSize` | 89 | 89 | 65 | No | 75 | 16.4 | 89 | 89 | 65 | 63 | 16.4 | 15.0 |
| `enqueue` | 89 | 89 | 65 | No | 75 | 16.4 | 89 | 89 | 65 | 63 | 16.4 | 15.0 |
| `error` | 89 | 89 | 65 | No | 75 | 16.4 | 89 | 89 | 65 | 63 | 16.4 | 15.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultController>

RelativeOrientationSensor
=========================



The `RelativeOrientationSensor` interface of the [Sensor APIs](sensor_apis) describes the device's physical orientation without regard to the Earth's reference coordinate system.

 To use this sensor, the user must grant permission to the `'accelerometer'`, and `'gyroscope'` device sensors through the [Permissions API](permissions_api). In addition, this feature may be blocked by a [Permissions Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Permissions_Policy) set on your server.


 EventTarget Sensor OrientationSensor RelativeOrientationSensor

Constructor
-----------


 [`RelativeOrientationSensor()`](relativeorientationsensor/relativeorientationsensor)  Creates a new `RelativeOrientationSensor` object.

  
Instance properties
-------------------


*No specific properties; inherits properties from its ancestors [`OrientationSensor`](orientationsensor) and [`Sensor`](sensor).*


Instance methods
----------------


*No specific methods; inherits methods from its ancestors [`OrientationSensor`](orientationsensor) and [`Sensor`](sensor).*


Events
------


*No specific events; inherits events from its ancestor, [`Sensor`](sensor).*


Examples
--------


### Basic Example



The following example, which is loosely based on [Intel's Orientation Phone demo](https://intel.github.io/generic-sensor-demos/orientation-phone/), instantiates an `RelativeOrientationSensor` with a frequency of 60 times a second.

  **Note:** The Intel demo this is based on uses the `AbsoluteOrientationSensor`. On each reading it uses [`OrientationSensor.quaternion`](orientationsensor/quaternion) to rotate a visual model of a phone.

  
```
const options = { frequency: 60, referenceFrame: "device" };
const sensor = new RelativeOrientationSensor(options);

sensor.addEventListener("reading", () => {
  // model is a Three.js object instantiated elsewhere.
  model.quaternion.fromArray(sensor.quaternion).inverse();
});
sensor.addEventListener("error", (error) => {
  if (event.error.name === "NotReadableError") {
    console.log("Sensor is not available.");
  }
});
sensor.start();

```


### Permissions Example



Using orientation sensors requires requesting permissions for multiple device sensors. Because the [`Permissions`](permissions) interface uses promises, a good way to request permissions is to use [`Promise.all`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all).

 
```
const sensor = new RelativeOrientationSensor();
Promise.all([
  navigator.permissions.query({ name: "accelerometer" }),
  navigator.permissions.query({ name: "gyroscope" }),
]).then((results) => {
  if (results.every((result) => result.state === "granted")) {
    sensor.start();
    // ...
  } else {
    console.log("No permissions to use RelativeOrientationSensor.");
  }
});

```


Specifications
--------------




| Specification |
| --- |
| [Orientation Sensor # relativeorientationsensor-interface](https://w3c.github.io/orientation-sensor/#relativeorientationsensor-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `RelativeOrientationSensor` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |
| `RelativeOrientationSensor` | 67 | 79 | No | No | 54 | No | 67 | 67 | No | 48 | No | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/RelativeOrientationSensor>

RemotePlayback
==============



The `RemotePlayback` interface of the [Remote Playback API](remote_playback_api) allows the page to detect availability of remote playback devices, then connect to and control playing on these devices.


 EventTarget RemotePlayback

Instance properties
-------------------


 
[`RemotePlayback.state`](remoteplayback/state) Read only 
  Represents the `RemotePlayback` connection's state. One of:

  `"connecting"`  The user agent is attempting to initiate remote playback with the selected device.

  `"connected"`  The transition from local to remote playback has happened, all commands will now take place on the remote device.

  `"disconnected"`  The remote playback has not been initiated, has failed to initiate, or has been stopped.

    
Instance methods
----------------


 [`RemotePlayback.watchAvailability()`](remoteplayback/watchavailability)  A [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with a `callbackId` of an available remote playback device.

  [`RemotePlayback.cancelWatchAvailability()`](remoteplayback/cancelwatchavailability)  Cancels the request to monitor the availability of remote playback devices.

  [`RemotePlayback.prompt()`](remoteplayback/prompt)  Prompts the user to select and give permission to connect to a remote playback device.

  
Events
------


 [`connecting`](remoteplayback/connecting_event)  Fired when the user agent initiates remote playback.

  [`connect`](remoteplayback/connect_event)  Fired when the user agent successfully connects to the remote device.

  [`disconnect`](remoteplayback/disconnect_event)  Fired when the user agent disconnects from the remote device.

  
Examples
--------



The following example demonstrates a player with custom controls that support remote playback. Initially the button used to select a device is hidden:

 
```
<video id="videoElement" src="https://example.org/media.ext">
  <button id="deviceBtn" style="display: none;">Pick device</button>
</video>

```
 The [`RemotePlayback.watchAvailability()`](remoteplayback/watchavailability) method is used to watch for available remote playback devices. If a device is available, use the callback to show the button.

 
```
const deviceBtn = document.getElementById("deviceBtn");
const videoElem = document.getElementById("videoElement");

function availabilityCallback(available) {
  // Show or hide the device picker button depending on device availability.
  deviceBtn.style.display = available ? "inline" : "none";
}

videoElem.remote.watchAvailability(availabilityCallback).catch(() => {
  /\* If the device cannot continuously watch available,
 show the button to allow the user to try to prompt for a connection.\*/
  deviceBtn.style.display = "inline";
});

```


Specifications
--------------




| Specification |
| --- |
| [Remote Playback API # remoteplayback-interface](https://w3c.github.io/remote-playback/#remoteplayback-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `RemotePlayback` | 56 | 79 | No | No | 43 | 13.1 | NoSee [bug 521319](https://crbug.com/521319). | 56 | No | 43 | 13.4 | 6.0 |
| `cancelWatchAvailability` | 56 | 79 | No | No | 43 | 13.1 | No | 56 | No | 43 | 13.4 | 6.0 |
| `connect_event` | 56 | 79 | No | No | 43 | 13.1 | No | 56 | No | 43 | 13.4 | 6.0 |
| `connecting_event` | 56 | 79 | No | No | 43 | 13.1 | No | 56 | No | 43 | 13.4 | 6.0 |
| `disconnect_event` | 56 | 79 | No | No | 43 | 13.1 | No | 56 | No | 43 | 13.4 | 6.0 |
| `prompt` | 56 | 79 | No | No | 43 | 13.1 | No | 56 | No | 43 | 13.4 | 6.0 |
| `state` | 56 | 79 | No | No | 43 | 13.1 | No | 56 | No | 43 | 13.4 | 6.0 |
| `watchAvailability` | 56 | 79 | No | No | 43 | 13.1 | No | 56 | No | 43 | 13.4 | 6.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/RemotePlayback>

Report
======



The `Report` interface of the [Reporting API](reporting_api) represents a single report.

 Reports can be accessed in a number of ways:

 * Via the [`ReportingObserver.takeRecords()`](reportingobserver/takerecords) method — this returns all reports in an observer's report queue, and then empties the queue.
* Via the `reports` parameter of the callback function passed into the [`ReportingObserver()`](reportingobserver/reportingobserver) constructor upon creation of a new observer instance. This contains the list of reports currently contained in the observer's report queue.
* By sending requests to the endpoints defined via the [`Report-To`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Report-To) HTTP header.



Instance properties
-------------------


 
[`Report.body`](report/body) Read only 
  The body of the report, which is a `ReportBody` object containing the detailed report information.

  
[`Report.type`](report/type) Read only 
  The type of report generated, e.g. `deprecation` or `intervention`.

  
[`Report.url`](report/url) Read only 
  The URL of the document that generated the report.

  
Instance methods
----------------


*This interface has no methods defined on it.*


Events
------


*This interface has no events that fire on it.*


Examples
--------



In our [deprecation\_report.html](https://mdn.github.io/dom-examples/reporting-api/deprecation_report.html) example, we create a simple reporting observer to observe usage of deprecated features on our web page:

 
```
const options = {
  types: ["deprecation"],
  buffered: true,
};

const observer = new ReportingObserver((reports, observer) => {
  reportBtn.onclick = () => displayReports(reports);
}, options);

```
 We then tell it to start observing reports using [`ReportingObserver.observe()`](reportingobserver/observe); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor:

 
```
observer.observe();

```
 Because of the event handler we set up inside the `ReportingObserver()` constructor, we can now click the button to display the report details.

  ![image of a jolly bearded man with various stats displayed below it about a deprecated feature] 

 The report details are displayed via the `displayReports()` function, which takes the observer callback's `reports` parameter as its parameter:

 
```
function displayReports(reports) {
  const outputElem = document.querySelector(".output");
  const list = document.createElement("ul");
  outputElem.appendChild(list);

  reports.forEach((report, i) => {
    let listItem = document.createElement("li");
    let textNode = document.createTextNode(
      `Report ${i + 1}, type: ${report.type}`
    );
    listItem.appendChild(textNode);
    let innerList = document.createElement("ul");
    listItem.appendChild(innerList);
    list.appendChild(listItem);

    for (const key in report.body) {
      const innerListItem = document.createElement("li");
      const keyValue = report.body[key];
      innerListItem.textContent = `${key}: ${keyValue}`;
      innerList.appendChild(innerListItem);
    }
  });
}

```
 The `reports` parameter contains an array of all the reports in the observer's report queue. We loop over each report using a [`forEach()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) loop, then iterate over each entry of in the report's body using a [`for...in`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) structure, displaying each key/value pair inside a list item.



Specifications
--------------




| Specification |
| --- |
| [Reporting API # dom-report](https://w3c.github.io/reporting/#dom-report) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Report` | 69 | 79 | No | No | 56 | 16.4 | 69 | 69 | No | 48 | 16.4 | 10.0 |
| `body` | 69 | 79 | No | No | 56 | 16.4 | 69 | 69 | No | 48 | 16.4 | 10.0 |
| `toJSON` | 69 | 79 | No | No | 56 | 16.4 | 69 | 69 | No | 48 | 16.4 | 10.0 |
| `type` | 69 | 79 | No | No | 56 | 16.4 | 69 | 69 | No | 48 | 16.4 | 10.0 |
| `url` | 69 | 79 | No | No | 56 | 16.4 | 69 | 69 | No | 48 | 16.4 | 10.0 |


See also
--------


* [Reporting API](reporting_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Report>

ReportBody
==========


The `ReportBody` interface of the [Reporting API](reporting_api) represents the body of a report. Individual report types inherit from this interface, adding specific attributes relevant to the particular report.


### Reports that inherit from `ReportBody`



* [`CSPViolationReportBody`](cspviolationreportbody)
* [`DeprecationReportBody`](deprecationreportbody)
* [`InterventionReportBody`](interventionreportbody)

 An instance of `ReportBody` is returned as the value of [`Report.body`](report/body). The interface has no constructor.



Instance methods
----------------


 [`ReportBody.toJSON()`](reportbody/tojson)  A *serializer* which returns a JSON representation of the `ReportBody` object.

  
Examples
--------



In this example we create a new [`ReportingObserver`](reportingobserver) to observe intervention reports. The [`InterventionReportBody`](interventionreportbody) interface inherits from `ReportBody`.

 
```
const options = {
  types: ["intervention"],
  buffered: true,
};

const observer = new ReportingObserver(([firstReport], observer) => {
  console.log(firstReport.type); // intervention
}, options);

```


Specifications
--------------




| Specification |
| --- |
| [Reporting API # reportbody](https://w3c.github.io/reporting/#reportbody) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ReportBody` | 69 | 79 | No | No | 56 | 16.4 | 69 | 69 | No | 48 | 16.4 | 10.0 |
| `toJSON` | 69 | 79 | No | No | 56 | 16.4 | 69 | 69 | No | 48 | 16.4 | 10.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ReportBody>

ReadableStreamDefaultReader
===========================



The `ReadableStreamDefaultReader` interface of the [Streams API](streams_api) represents a default reader that can be used to read stream data supplied from a network (such as a fetch request).

 A `ReadableStreamDefaultReader` can be used to read from a [`ReadableStream`](readablestream) that has an underlying source of any type (unlike a [`ReadableStreamBYOBReader`](readablestreambyobreader), which can only be used with readable streams that have an *underlying byte source*).

  Note however that zero-copy transfer from an underlying source is only supported for underlying byte sources that autoallocate buffers. In other words, the stream must have been [constructed](readablestream/readablestream) specifying both [`type="bytes"`](readablestream/readablestream#type) and [`autoAllocateChunkSize`](readablestream/readablestream#autoallocatechunksize). For any other underlying source, the stream will always satisfy read requests with data from internal queues. 



Constructor
-----------


 [`ReadableStreamDefaultReader()`](readablestreamdefaultreader/readablestreamdefaultreader)  Creates and returns a `ReadableStreamDefaultReader` object instance.

  
Instance properties
-------------------


 
[`ReadableStreamDefaultReader.closed`](readablestreamdefaultreader/closed) Read only 
  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that fulfills when the stream closes, or rejects if the stream throws an error or the reader's lock is released. This property enables you to write code that responds to an end to the streaming process.

  
Instance methods
----------------


 [`ReadableStreamDefaultReader.cancel()`](readablestreamdefaultreader/cancel)  Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. The supplied `reason` argument will be given to the underlying source, which may or may not use it.

  [`ReadableStreamDefaultReader.read()`](readablestreamdefaultreader/read)  Returns a promise providing access to the next chunk in the stream's internal queue.

  [`ReadableStreamDefaultReader.releaseLock()`](readablestreamdefaultreader/releaselock)  Releases the reader's lock on the stream.

  
Examples
--------



In the following example, an artificial [`Response`](response) is created to stream HTML fragments fetched from another resource to the browser.

 It demonstrates the usage of a [`ReadableStream`](readablestream) in combination with a [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array).

 
```
fetch("https://www.example.org/").then((response) => {
  const reader = response.body.getReader();
  const stream = new ReadableStream({
    start(controller) {
      // The following function handles each data chunk
      function push() {
        // "done" is a Boolean and value a "Uint8Array"
        return reader.read().then(({ done, value }) => {
          // Is there no more data to read?
          if (done) {
            // Tell the browser that we have finished sending data
            controller.close();
            return;
          }

          // Get the data and send it to the browser via the controller
          controller.enqueue(value);
          push();
        });
      }

      push();
    },
  });

  return new Response(stream, { headers: { "Content-Type": "text/html" } });
});

```


Specifications
--------------




| Specification |
| --- |
| [Streams Standard # default-reader-class](https://streams.spec.whatwg.org/#default-reader-class) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ReadableStreamDefaultReader` | 78 | 79 | 65 | No | 65 | No | 78 | 78 | 65 | 56 | No | 12.0 |
| `ReadableStreamDefaultReader` | 78 | 79 | 65 | No | 65 | 16.4 | 78 | 78 | 65 | 56 | 16.4 | 12.0 |
| `cancel` | 78 | 79 | 65 | No | 65 | 16.4 | 78 | 78 | 65 | 56 | 16.4 | 12.0 |
| `closed` | 78 | 79 | 65 | No | 65 | 16.4 | 78 | 78 | 65 | 56 | 16.4 | 12.0 |
| `read` | 78 | 79 | 65 | No | 65 | 16.4 | 78 | 78 | 65 | 56 | 16.4 | 12.0 |
| `releaseLock` | 78 | 79 | 65 | No | 65 | 16.4 | 78 | 78 | 65 | 56 | 16.4 | 12.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader>

ReportingObserver
=================


The `ReportingObserver` interface of the [Reporting API](reporting_api) allows you to collect and access reports.


Constructor
-----------


 [`ReportingObserver()`](reportingobserver/reportingobserver)  Creates a new `ReportingObserver` object instance, which can be used to collect and access reports.

  
Instance properties
-------------------


*This interface has no properties defined on it.*


Instance methods
----------------


 [`ReportingObserver.disconnect()`](reportingobserver/disconnect)  Stops a reporting observer that had previously started observing from collecting reports.

  [`ReportingObserver.observe()`](reportingobserver/observe)  Instructs a reporting observer to start collecting reports in its report queue.

  [`ReportingObserver.takeRecords()`](reportingobserver/takerecords)  Returns the current list of reports contained in the observer's report queue, and empties the queue.

  
Events
------


*This interface has no events that fire on it.*


Examples
--------



In our [deprecation\_report.html](https://mdn.github.io/dom-examples/reporting-api/deprecation_report.html) example, we create a simple reporting observer to observe usage of deprecated features on our web page:

 
```
const options = {
  types: ["deprecation"],
  buffered: true,
};

const observer = new ReportingObserver((reports, observer) => {
  reportBtn.onclick = () => displayReports(reports);
}, options);

```
 We then tell it to start observing reports using [`ReportingObserver.observe()`](reportingobserver/observe); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor:

 
```
observer.observe();

```
 Later on in the example we deliberately use the deprecated version of [`MediaDevices.getUserMedia()`](mediadevices/getusermedia):

 
```
if (navigator.mozGetUserMedia) {
  navigator.mozGetUserMedia(constraints, success, failure);
} else {
  navigator.getUserMedia(constraints, success, failure);
}

```
 This causes a deprecation report to be generated; because of the event handler we set up inside the `ReportingObserver()` constructor, we can now click the button to display the report details.

  ![image of a jolly bearded man with various stats displayed below it about a deprecated feature] 

  **Note:** If you look at the [complete source code](https://github.com/mdn/dom-examples/blob/main/reporting-api/deprecation_report.html), you'll notice that we actually call the deprecated `getUserMedia()` method twice. After the first time we call [`ReportingObserver.takeRecords()`](reportingobserver/takerecords), which returns the first generated report and empties the queue. Because of this, when the button is pressed only the second report is listed.

 

Specifications
--------------




| Specification |
| --- |
| [Reporting API # interface-reporting-observer](https://w3c.github.io/reporting/#interface-reporting-observer) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ReportingObserver` | 69 | 79 | No | No | 56 | 16.4 | 69 | 69 | No | 48 | 16.4 | 10.0 |
| `ReportingObserver` | 69 | 79 | No | No | 56 | 16.4 | 69 | 69 | No | 48 | 16.4 | 10.0 |
| `disconnect` | 69 | 79 | No | No | 56 | 16.4 | 69 | 69 | No | 48 | 16.4 | 10.0 |
| `observe` | 69 | 79 | No | No | 56 | 16.4 | 69 | 69 | No | 48 | 16.4 | 10.0 |
| `takeRecords` | 69 | 79 | No | No | 56 | 16.4 | 69 | 69 | No | 48 | 16.4 | 10.0 |
| `worker_support` | 84 | 84 | No | No | 70 | No | 84 | 84 | No | No | No | 14.0 |


See also
--------


* [Reporting API](reporting_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ReportingObserver>

Request
=======



The `Request` interface of the [Fetch API](fetch_api) represents a resource request.

 You can create a new `Request` object using the [`Request()`](request/request) constructor, but you are more likely to encounter a `Request` object being returned as the result of another API operation, such as a service worker [`FetchEvent.request`](fetchevent/request).



Constructor
-----------


 [`Request()`](request/request)  Creates a new `Request` object.

  
Instance properties
-------------------


 
[`Request.body`](request/body) Read only 
  A [`ReadableStream`](readablestream) of the body contents.

  
[`Request.bodyUsed`](request/bodyused) Read only 
  Stores `true` or `false` to indicate whether or not the body has been used in a request yet.

  
[`Request.cache`](request/cache) Read only 
  Contains the cache mode of the request (e.g., `default`, `reload`, `no-cache`).

  
[`Request.credentials`](request/credentials) Read only 
  Contains the credentials of the request (e.g., `omit`, `same-origin`, `include`). The default is `same-origin`.

  
[`Request.destination`](request/destination) Read only 
  Returns a string describing the request's destination. This is a string indicating the type of content being requested.

  
[`Request.headers`](request/headers) Read only 
  Contains the associated [`Headers`](headers) object of the request.

  
[`Request.integrity`](request/integrity) Read only 
  Contains the [subresource integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity) value of the request (e.g., `sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=`).

  
[`Request.method`](request/method) Read only 
  Contains the request's method (`GET`, `POST`, etc.)

  
[`Request.mode`](request/mode) Read only 
  Contains the mode of the request (e.g., `cors`, `no-cors`, `same-origin`, `navigate`.)

  
[`Request.redirect`](request/redirect) Read only 
  Contains the mode for how redirects are handled. It may be one of `follow`, `error`, or `manual`.

  
[`Request.referrer`](request/referrer) Read only 
  Contains the referrer of the request (e.g., `client`).

  
[`Request.referrerPolicy`](request/referrerpolicy) Read only 
  Contains the referrer policy of the request (e.g., `no-referrer`).

  
[`Request.signal`](request/signal) Read only 
  Returns the [`AbortSignal`](abortsignal) associated with the request

  
[`Request.url`](request/url) Read only 
  Contains the URL of the request.

  
Instance methods
----------------



 [`Request.arrayBuffer()`](request/arraybuffer)  Returns a promise that resolves with an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) representation of the request body.

  [`Request.blob()`](request/blob)  Returns a promise that resolves with a [`Blob`](blob) representation of the request body.

  [`Request.clone()`](request/clone)  Creates a copy of the current `Request` object.

  [`Request.formData()`](request/formdata)  Returns a promise that resolves with a [`FormData`](formdata) representation of the request body.

  [`Request.json()`](request/json)  Returns a promise that resolves with the result of parsing the request body as [`JSON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON).

  [`Request.text()`](request/text)  Returns a promise that resolves with a text representation of the request body.

    **Note:** The request body functions can be run only once; subsequent calls will resolve with empty strings/ArrayBuffers.

 

Examples
--------



In the following snippet, we create a new request using the `Request()` constructor (for an image file in the same directory as the script), then return some property values of the request:

 
```
const request = new Request("https://www.mozilla.org/favicon.ico");

const url = request.url;
const method = request.method;
const credentials = request.credentials;

```
 You could then fetch this request by passing the `Request` object in as a parameter to a [`fetch()`](fetch) call, for example:

 
```
fetch(request)
  .then((response) => response.blob())
  .then((blob) => {
    image.src = URL.createObjectURL(blob);
  });

```
 In the following snippet, we create a new request using the `Request()` constructor with some initial data and body content for an API request which need a body payload:

 
```
const request = new Request("https://example.com", {
  method: "POST",
  body: '{"foo": "bar"}',
});

const url = request.url;
const method = request.method;
const credentials = request.credentials;
const bodyUsed = request.bodyUsed;

```
  **Note:** The body can only be a [`Blob`](blob), an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), a [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), a [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView), a [`FormData`](formdata), a [`URLSearchParams`](urlsearchparams), a [`ReadableStream`](readablestream), or a [`String`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) object, as well as a string literal, so for adding a JSON object to the payload you need to stringify that object.

  You could then fetch this API request by passing the `Request` object in as a parameter to a [`fetch()`](fetch) call, for example and get the response:

 
```
fetch(request)
  .then((response) => {
    if (response.status === 200) {
      return response.json();
    } else {
      throw new Error("Something went wrong on API server!");
    }
  })
  .then((response) => {
    console.debug(response);
    // …
  })
  .catch((error) => {
    console.error(error);
  });

```


Specifications
--------------




| Specification |
| --- |
| [Fetch Standard # request-class](https://fetch.spec.whatwg.org/#request-class) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Request` | 40From Chrome 47, default values for the `init` argument's properties changed. `mode` defaults to `same-origin` (from `no-cors`). `credentials` defaults to `include` (from `same-origin`). `redirect` defaults to `follow` (from `manual`). | 14 | 39 | No | 27 | 10.1 | 40From Chrome 47, default values for the `init` argument's properties changed. `mode` defaults to `same-origin` (from `no-cors`). `credentials` defaults to `include` (from `same-origin`). `redirect` defaults to `follow` (from `manual`). | 40From Chrome 47, default values for the `init` argument's properties changed. `mode` defaults to `same-origin` (from `no-cors`). `credentials` defaults to `include` (from `same-origin`). `redirect` defaults to `follow` (from `manual`). | 39 | 27 | 10.3 | 4.0From Samsung Internet 5.0, default values for the `init` argument's properties changed. `mode` defaults to `same-origin` (from `no-cors`). `credentials` defaults to `include` (from `same-origin`). `redirect` defaults to `follow` (from `manual`). |
| `Request` | 4240–42Only available in service workers. | 14 | 39 | No | 2927–29Only available in service workers. | 10.1 | 4240–42Only available in service workers. | 4240–42Only available in service workers. | 39 | 2927–29Only available in service workers. | 10.3 | 4.0 |
| `arrayBuffer` | 42 | 14 | 39 | No | 29 | 10.1 | 42 | 42 | 39 | 29 | 10.3 | 4.0 |
| `blob` | 42 | 14 | 39 | No | 29 | 10.1 | 42 | 42 | 39 | 29 | 10.3 | 4.0 |
| `body` | 105 | 105 | NoSee [bug 1387483](https://bugzil.la/1387483). | No | 91 | 11.1 | 105 | 105 | NoSee [bug 1387483](https://bugzil.la/1387483). | 72 | 11.3 | 20.0 |
| `bodyUsed` | 42 | 14 | 39 | No | 29 | 10.1 | 42 | 42 | 39 | 29 | 10.3 | 4.0 |
| `cache` | 64 | 14 | 48 | No | 51 | 10.1 | 64 | 64 | 48 | 47 | 10.3 | 9.0 |
| `clone` | 40 | 14 | 39 | No | 27 | 10.1 | 40 | 40 | 39 | 27 | 10.3 | 4.0 |
| `credentials` | 40 | 14 | 39 | No | 27 | 10.1 | 40 | 40 | 39 | 27 | 10.3 | 4.0 |
| `destination` | 65 | 14 | 61 | No | 52 | 10.1 | 65 | 65 | 61 | 47 | 10.3 | 9.0 |
| `formData` | 60 | 79 | 39 | No | 47 | 14.111.1The method exists but always rejects with `NotSupportedError`. See [bug 215671](https://webkit.org/b/215671). | 60 | 60 | 39 | 44 | 14.511.3The method exists but always rejects with `NotSupportedError`. See [bug 215671](https://webkit.org/b/215671). | 8.0 |
| `headers` | 40 | 14 | 39 | No | 27 | 10.1 | 40 | 40 | 39 | 27 | 10.3 | 4.0 |
| `integrity` | 46 | 14 | 51 | No | 33 | 10.1 | 46 | 46 | 51 | 33 | 10.3 | 5.0 |
| `isHistoryNavigation` | 69 | 79 | No | No | 56 | No | 69 | 69 | No | 48 | No | 10.0 |
| `json` | 42 | 14 | 39 | No | 29 | 10.1 | 42 | 42 | 39 | 29 | 10.3 | 4.0 |
| `keepalive` | 66 | 15 | No | No | 43 | 13 | 66 | 66 | No | 43 | 13 | 9.0 |
| `method` | 40 | 14 | 39 | No | 27 | 10.1 | 40 | 40 | 39 | 27 | 10.3 | 4.0 |
| `mode` | 40 | 14 | 39 | No | 27 | 10.1 | 40 | 40 | 39 | 27 | 10.3 | 4.0 |
| `redirect` | 46 | 14 | 43 | No | 33 | 10.1 | 46 | 46 | 43 | 33 | 10.3 | 5.0 |
| `referrer` | 40 | 14 | 39 | No | 27 | 10.1 | 40 | 40 | 39 | 27 | 10.3 | 4.0 |
| `referrerPolicy` | 52 | 14 | 47 | No | 39 | 10.1 | 52 | 52 | 47 | 41 | 10.3 | 7.2 |
| `signal` | 66 | 16 | 57 | No | 53 | 12.1 | 66 | 66 | 57 | 47 | 12.2 | 9.0 |
| `text` | 42 | 14 | 39 | No | 29 | 10.1 | 42 | 42 | 39 | 29 | 10.3 | 4.0 |
| `url` | 40Fragment support added in Chrome 59. | 14 | 39 | No | 27Fragment support added in Opera 46. | 10.1 | 40Fragment support added in Chrome 59. | 40Fragment support added in Chrome 59. | 39 | 27Fragment support added in Opera 46. | 10.3 | 4.0Fragment support added in Samsung Internet 7.0. |


See also
--------


* [ServiceWorker API](service_worker_api)
* [HTTP access control (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)
* [HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Request>

ResizeObserver
==============



The `ResizeObserver` interface reports changes to the dimensions of an [`Element`](element)'s content or border box, or the bounding box of an [`SVGElement`](svgelement).

  **Note:** The content box is the box in which content can be placed, meaning the border box minus the padding and border width. The border box encompasses the content, padding, and border. See [The box model](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/The_box_model) for further explanation.

 

Constructor
-----------


 [`ResizeObserver()`](resizeobserver/resizeobserver)  Creates and returns a new `ResizeObserver` object.

  
Instance properties
-------------------


None.


Instance methods
----------------


 [`ResizeObserver.disconnect()`](resizeobserver/disconnect)  Unobserves all observed [`Element`](element) targets of a particular observer.

  [`ResizeObserver.observe()`](resizeobserver/observe)  Initiates the observing of a specified [`Element`](element).

  [`ResizeObserver.unobserve()`](resizeobserver/unobserve)  Ends the observing of a specified [`Element`](element).

  
Examples
--------



In the [resize-observer-text.html](https://mdn.github.io/dom-examples/resize-observer/resize-observer-text.html) ([see source](https://github.com/mdn/dom-examples/blob/main/resize-observer/resize-observer-text.html)) example, we use the resize observer to change the [`font-size`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-size) of a header and paragraph as a slider's value is changed causing the containing `<div>` to change width. This shows that you can respond to changes in an element's size, even if they have nothing to do with the viewport.

 We also provide a checkbox to turn the observer off and on. If it is turned off, the text will not change in response to the `<div>`'s width changing.

 The JavaScript looks like so:

 
```
const h1Elem = document.querySelector("h1");
const pElem = document.querySelector("p");
const divElem = document.querySelector("body > div");
const slider = document.querySelector('input[type="range"]');
const checkbox = document.querySelector('input[type="checkbox"]');

divElem.style.width = "600px";

slider.addEventListener("input", () => {
  divElem.style.width = `${slider.value}px`;
});

const resizeObserver = new ResizeObserver((entries) => {
  for (const entry of entries) {
    if (entry.contentBoxSize) {
      const contentBoxSize = entry.contentBoxSize[0];
      h1Elem.style.fontSize = `${Math.max(
 1.5,
 contentBoxSize.inlineSize / 200
 )}rem`;
      pElem.style.fontSize = `${Math.max(
 1,
 contentBoxSize.inlineSize / 600
 )}rem`;
    } else {
      h1Elem.style.fontSize = `${Math.max(
 1.5,
 entry.contentRect.width / 200
 )}rem`;
      pElem.style.fontSize = `${Math.max(1, entry.contentRect.width / 600)}rem`;
    }
  }

  console.log("Size changed");
});

resizeObserver.observe(divElem);

checkbox.addEventListener("change", () => {
  if (checkbox.checked) {
    resizeObserver.observe(divElem);
  } else {
    resizeObserver.unobserve(divElem);
  }
});

```


Observation Errors
------------------



Implementations following the specification invoke resize events before paint (that is, before the frame is presented to the user). If there was any resize event, style and layout are re-evaluated — which in turn may trigger more resize events. Infinite loops from cyclic dependencies are addressed by only processing elements deeper in the DOM during each iteration. Resize events that don't meet that condition are deferred to the next paint, and an error event is fired on the [`Window`](window) object, with the well-defined message string:

 **ResizeObserver loop completed with undelivered notifications.**

 Note that this only prevents user-agent lockup, not the infinite loop itself. For example, the following code will cause the width of `divElem` to grow indefinitely, with the above error message in the console repeating every frame:

 
```
const divElem = document.querySelector("body > div");

const resizeObserver = new ResizeObserver((entries) => {
  for (const entry of entries) {
    entry.target.style.width = entry.contentBoxSize[0].inlineSize + 10 + "px";
  }
});

window.addEventListener("error", function (e) {
  console.error(e.message);
});

```
 As long as the error event does not fire indefinitely, resize observer will settle and produce a stable, likely correct, layout. However, visitors may see a flash of broken layout, as a sequence of changes expected to happen in a single frame is instead happening over multiple frames.



Specifications
--------------




| Specification |
| --- |
| [Resize Observer # resize-observer-interface](https://w3c.github.io/csswg-drafts/resize-observer/#resize-observer-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ResizeObserver` | 64 | 79 | 69 | No | 51 | 13.1 | 64 | 64 | 79 | 47 | 13.4 | 9.0 |
| `ResizeObserver` | 64 | 79 | 69 | No | 51 | 13.1 | 64 | 64 | 79 | 47 | 13.4 | 9.0 |
| `disconnect` | 64 | 79 | 69 | No | 51 | 13.1 | 64 | 64 | 79 | 47 | 13.4 | 9.0 |
| `observe` | 64 | 79 | 69 | No | 51 | 13.1 | 64 | 64 | 79 | 47 | 13.4 | 9.0 |
| `unobserve` | 64 | 79 | 69 | No | 51 | 13.1 | 64 | 64 | 79 | 47 | 13.4 | 9.0 |


See also
--------


* [The box model](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/The_box_model)
* [`PerformanceObserver`](performanceobserver)
* [`IntersectionObserver`](intersectionobserver) (part of the [Intersection Observer API](intersection_observer_api))
* Upcoming [container queries](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Container_Queries) may be a viable alternative for implementing responsive design.


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver>

Response
========



The `Response` interface of the [Fetch API](fetch_api) represents the response to a request.

 You can create a new `Response` object using the [`Response()`](response/response) constructor, but you are more likely to encounter a `Response` object being returned as the result of another API operation—for example, a service worker [`FetchEvent.respondWith`](fetchevent/respondwith), or a simple [`fetch()`](fetch).



Constructor
-----------


 [`Response()`](response/response)  Creates a new `Response` object.

  
Instance properties
-------------------


 
[`Response.body`](response/body) Read only 
  A [`ReadableStream`](readablestream) of the body contents.

  
[`Response.bodyUsed`](response/bodyused) Read only 
  Stores a boolean value that declares whether the body has been used in a response yet.

  
[`Response.headers`](response/headers) Read only 
  The [`Headers`](headers) object associated with the response.

  
[`Response.ok`](response/ok) Read only 
  A boolean indicating whether the response was successful (status in the range `200` – `299`) or not.

  
[`Response.redirected`](response/redirected) Read only 
  Indicates whether or not the response is the result of a redirect (that is, its URL list has more than one entry).

  
[`Response.status`](response/status) Read only 
  The status code of the response. (This will be `200` for a success).

  
[`Response.statusText`](response/statustext) Read only 
  The status message corresponding to the status code. (e.g., `OK` for `200`).

  
[`Response.type`](response/type) Read only 
  The type of the response (e.g., `basic`, `cors`).

  
[`Response.url`](response/url) Read only 
  The URL of the response.

  
Static methods
--------------


 [`Response.error()`](response/error)  Returns a new `Response` object associated with a network error.

  [`Response.redirect()`](response/redirect)  Creates a new response with a different URL.

  
Instance methods
----------------


 [`Response.arrayBuffer()`](response/arraybuffer)  Returns a promise that resolves with an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) representation of the response body.

  [`Response.blob()`](response/blob)  Returns a promise that resolves with a [`Blob`](blob) representation of the response body.

  [`Response.clone()`](response/clone)  Creates a clone of a `Response` object.

  [`Response.formData()`](response/formdata)  Returns a promise that resolves with a [`FormData`](formdata) representation of the response body.

  [`Response.json()`](response/json)  Returns a promise that resolves with the result of parsing the response body text as [`JSON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON).

  [`Response.text()`](response/text)  Returns a promise that resolves with a text representation of the response body.

  
Examples
--------


### Fetching an image



 In our [basic fetch example](https://github.com/mdn/dom-examples/tree/main/fetch/basic-fetch) ([run example live](https://mdn.github.io/dom-examples/fetch/basic-fetch/)) we use a simple `fetch()` call to grab an image and display it in an [`<img>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img) element. The `fetch()` call returns a promise, which resolves to the `Response` object associated with the resource fetch operation. 

 You'll notice that since we are requesting an image, we need to run [`Response.blob`](response/blob) to give the response its correct MIME type.

 
```
const image = document.querySelector(".my-image");
fetch("flowers.jpg")
  .then((response) => response.blob())
  .then((blob) => {
    const objectURL = URL.createObjectURL(blob);
    image.src = objectURL;
  });

```
 You can also use the [`Response()`](response/response) constructor to create your own custom `Response` object:

 
```
const response = new Response();

```


### An Ajax Call



Here we call a PHP program file that generates a JSON string, displaying the result as a JSON value, including simple error handling.

 
```
// Function to do an Ajax call
const doAjax = async () => {
  const response = await fetch("Ajax.php"); // Generate the Response object
  if (response.ok) {
    const jsonValue = await response.json(); // Get JSON value from the response body
    return Promise.resolve(jsonValue);
  } else {
    return Promise.reject("\*\*\* PHP file not found");
  }
};

// Call the function and output value or error message to console
doAjax().then(console.log).catch(console.log);

```


Specifications
--------------




| Specification |
| --- |
| [Fetch Standard # response-class](https://fetch.spec.whatwg.org/#response-class) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `Response` | 40 | 14 | 39 | No | 27 | 10.1 | 40 | 40 | 39 | 27 | 10.3 | 4.0 |
| `Response` | 4240–42Only available in service workers. | 14 | 39 | No | 2927–29Only available in service workers. | 10.1 | 4240–42Only available in service workers. | 4240–42Only available in service workers. | 39 | 2927–29Only available in service workers. | 10.3 | 4.0 |
| `arrayBuffer` | 42 | 14 | 39 | No | 29 | 10.1 | 42 | 42 | 39 | 29 | 10.3 | 4.0 |
| `blob` | 42 | 14 | 39 | No | 29 | 10.1 | 42 | 42 | 39 | 29 | 10.3 | 4.0 |
| `body` | 43 | 14 | 65 | No | 30 | 10.1 | 43 | 43 | 65 | 30 | 10.3 | 4.0 |
| `bodyUsed` | 42 | 14 | 39 | No | 29 | 10.1 | 42 | 42 | 39 | 29 | 10.3 | 4.0 |
| `clone` | 40 | 14 | 39 | No | 27 | 10.1 | 40 | 40 | 39 | 27 | 10.3 | 4.0 |
| `error` | 43 | 16 | 39 | No | 30 | 10.1 | 43 | 43 | 39 | 30 | 10.3 | 4.0 |
| `formData` | 60 | 79 | 39 | No | 47 | 14.110.1The method exists but always rejects with `NotSupportedError`. See [bug 215671](https://webkit.org/b/215671). | 60 | 60 | 39 | 44 | 14.510.3The method exists but always rejects with `NotSupportedError`. See [bug 215671](https://webkit.org/b/215671). | 8.0 |
| `headers` | 40 | 14 | 39 | No | 27 | 10.1 | 40 | 40 | 39 | 27 | 10.3 | 4.0 |
| `json` | 42 | 14 | 39 | No | 29 | 10.1 | 42 | 42 | 39 | 29 | 10.3 | 4.0 |
| `ok` | 42 | 14 | 39 | No | 29 | 10.1 | 42 | 42 | 39 | 29 | 10.3 | 4.0 |
| `redirect` | 44 | 16 | 39 | No | 31 | 10.1 | 44 | 44 | 39 | 32 | 10.3 | 4.0 |
| `redirected` | 57 | 16 | 49 | No | 44 | 10.1 | 60 | 57 | 49 | 43 | 10.3 | 8.0 |
| `status` | 40 | 14 | 39 | No | 27 | 10.1 | 40 | 40 | 39 | 27 | 10.3 | 4.0 |
| `statusText` | 40 | 14 | 39 | No | 27 | 10.1 | 40 | 40 | 39 | 27 | 10.3 | 4.0 |
| `text` | 42 | 14 | 39 | No | 29 | 10.1 | 42 | 42 | 39 | 29 | 10.3 | 4.0 |
| `type` | 40 | 14 | 39 | No | 27 | 10.1 | 40 | 40 | 39 | 27 | 10.3 | 4.0 |
| `url` | 40 | 14 | 39 | No | 27 | 10.1 | 40 | 40 | 39 | 27 | 10.3 | 4.0 |


See also
--------


* [ServiceWorker API](service_worker_api)
* [HTTP access control (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)
* [HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/Response>

RsaHashedImportParams
=====================


The `RsaHashedImportParams` dictionary of the [Web Crypto API](web_crypto_api) represents the object that should be passed as the `algorithm` parameter into [`SubtleCrypto.importKey()`](subtlecrypto/importkey) or [`SubtleCrypto.unwrapKey()`](subtlecrypto/unwrapkey), when importing any RSA-based key pair: that is, when the algorithm is identified as any of [RSASSA-PKCS1-v1\_5](subtlecrypto/sign#rsassa-pkcs1-v1_5), [RSA-PSS](subtlecrypto/sign#rsa-pss), or [RSA-OAEP](subtlecrypto/encrypt#rsa-oaep).


Instance properties
-------------------


 `name`  A string. This should be set to `RSASSA-PKCS1-v1_5`, `RSA-PSS`, or `RSA-OAEP`, depending on the algorithm you want to use.

  `hash`  A string representing the name of the [digest function](subtlecrypto#supported_algorithms) to use. This can be one of `SHA-256`, `SHA-384`, or `SHA-512`.

  **Warning:** Although you can technically pass `SHA-1` here, this is strongly discouraged as it is considered vulnerable.

   
Examples
--------


See the examples for [`SubtleCrypto.importKey()`](subtlecrypto/importkey).


Specifications
--------------




| Specification |
| --- |
| [Web Cryptography API # dfn-RsaHashedImportParams](https://w3c.github.io/webcrypto/#dfn-RsaHashedImportParams) |


Browser compatibility
---------------------


See also
--------


* [`SubtleCrypto.importKey()`](subtlecrypto/importkey).
* [`SubtleCrypto.unwrapKey()`](subtlecrypto/unwrapkey).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/RsaHashedImportParams>

RsaHashedKeyGenParams
=====================


The `RsaHashedKeyGenParams` dictionary of the [Web Crypto API](web_crypto_api) represents the object that should be passed as the `algorithm` parameter into [`SubtleCrypto.generateKey()`](subtlecrypto/generatekey), when generating any RSA-based key pair: that is, when the algorithm is identified as any of [RSASSA-PKCS1-v1\_5](subtlecrypto/sign#rsassa-pkcs1-v1_5), [RSA-PSS](subtlecrypto/sign#rsa-pss), or [RSA-OAEP](subtlecrypto/encrypt#rsa-oaep).


Instance properties
-------------------


 `name`  A string. This should be set to `RSASSA-PKCS1-v1_5`, `RSA-PSS`, or `RSA-OAEP`, depending on the algorithm you want to use.

  `modulusLength`  A `Number`. The length in bits of the RSA modulus. This should be at least 2048: see for example see [SP 800-131A Rev. 2](https://csrc.nist.gov/publications/detail/sp/800-131a/rev-2/final). Some organizations are now recommending that it should be 4096.

  `publicExponent`  A [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array). The public exponent. Unless you have a good reason to use something else, specify 65537 here (`[0x01, 0x00, 0x01]`).

  `hash`  A string representing the name of the [digest function](subtlecrypto/digest) to use. You can pass any of `SHA-256`, `SHA-384`, or `SHA-512` here.

  **Warning:** Although you can technically pass `SHA-1` as a value here, this is strongly discouraged as SHA-1 is considered vulnerable.

   
Examples
--------


See the examples for [`SubtleCrypto.generateKey()`](subtlecrypto/generatekey).


Specifications
--------------




| Specification |
| --- |
| [Web Cryptography API # dfn-RsaHashedKeyGenParams](https://w3c.github.io/webcrypto/#dfn-RsaHashedKeyGenParams) |


Browser compatibility
---------------------


See also
--------


* [`SubtleCrypto.generateKey()`](subtlecrypto/generatekey).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/RsaHashedKeyGenParams>

RsaPssParams
============


The `RsaPssParams` dictionary of the [Web Crypto API](web_crypto_api) represents the object that should be passed as the `algorithm` parameter into [`SubtleCrypto.sign()`](subtlecrypto/sign) or [`SubtleCrypto.verify()`](subtlecrypto/verify), when using the [RSA-PSS](subtlecrypto/sign#rsa-pss) algorithm.


Instance properties
-------------------


 `name`  A string. This should be set to `RSA-PSS`.

  `saltLength`  A `long` integer representing the length of the random salt to use, in bytes.

 [RFC 3447](https://datatracker.ietf.org/doc/html/rfc3447) says that "Typical salt lengths" are either 0 or the length of the output of the [digest algorithm](subtlecrypto#supported_algorithms) that was selected when this key was [generated](subtlecrypto/generatekey). For example, if you use [SHA-256](subtlecrypto/digest#supported_algorithms) as the digest algorithm, this could be 32.

 The maximum size of `saltLength` is given by:

 
```
Math.ceil((keySizeInBits - 1) / 8) - digestSizeInBytes - 2;

```
 So for a key length of 2048 bits and a digest output size of 32 bytes, the maximum size would be 222.

  
Examples
--------


See the examples for [`SubtleCrypto.sign()`](subtlecrypto/sign) and [`SubtleCrypto.verify()`](subtlecrypto/verify).


Specifications
--------------




| Specification |
| --- |
| [Web Cryptography API # dfn-RsaPssParams](https://w3c.github.io/webcrypto/#dfn-RsaPssParams) |


Browser compatibility
---------------------


See also
--------


* [RFC 3447: RSASSA-PSS](https://datatracker.ietf.org/doc/html/rfc3447#section-8.1)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/RsaPssParams>

RTCCertificate
==============


The interface of the [WebRTC API](webrtc_api) provides an object represents a certificate that an [`RTCPeerConnection`](rtcpeerconnection) uses to authenticate.


Instance properties
-------------------


 
[`RTCCertificate.expires`](rtccertificate/expires) Read only 
  Returns the expiration date of the certificate.

  
Specifications
--------------




| Specification |
| --- |
| [WebRTC: Real-Time Communication in Browsers # dom-rtccertificate](https://w3c.github.io/webrtc-pc/#dom-rtccertificate) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `RTCCertificate` | 49 | 79 | 42 | No | 36 | 12.1 | 49 | 49 | 42 | 36 | 12.2 | 5.0 |
| `expires` | 49 | 79 | 42 | No | 36 | 12.1 | 49 | 49 | 42 | 36 | 12.2 | 5.0 |
| `getFingerprints` | 61 | 79 | No | No | 48 | 12.1 | 61 | 61 | No | 45 | 12.2 | 8.0 |


See also
--------


* [`RTCPeerConnection.generateCertificate()`](rtcpeerconnection/generatecertificate)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/RTCCertificate>

ResizeObserverEntry
===================


The `ResizeObserverEntry` interface represents the object passed to the [`ResizeObserver()`](resizeobserver/resizeobserver) constructor's callback function, which allows you to access the new dimensions of the [`Element`](element) or [`SVGElement`](svgelement) being observed.


Instance properties
-------------------



 
[`ResizeObserverEntry.borderBoxSize`](resizeobserverentry/borderboxsize) Read only 
  An object containing the new border box size of the observed element when the callback is run.

  
[`ResizeObserverEntry.contentBoxSize`](resizeobserverentry/contentboxsize) Read only 
  An object containing the new content box size of the observed element when the callback is run.

  
[`ResizeObserverEntry.devicePixelContentBoxSize`](resizeobserverentry/devicepixelcontentboxsize) Read only 
  An object containing the new content box size in device pixels of the observed element when the callback is run.

  
[`ResizeObserverEntry.contentRect`](resizeobserverentry/contentrect) Read only 
  A [`DOMRectReadOnly`](domrectreadonly) object containing the new size of the observed element when the callback is run. Note that this is better supported than the above two properties, but it is left over from an earlier implementation of the Resize Observer API, is still included in the spec for web compat reasons, and may be deprecated in future versions.

  
[`ResizeObserverEntry.target`](resizeobserverentry/target) Read only 
  A reference to the [`Element`](element) or [`SVGElement`](svgelement) being observed.

    **Note:** The content box is the box in which content can be placed, meaning the border box minus the padding and border width. The border box encompasses the content, padding, and border. See [The box model](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/The_box_model) for further explanation.

 

Instance methods
----------------


None.


Examples
--------



The following snippet is taken from the [resize-observer-text.html](https://mdn.github.io/dom-examples/resize-observer/resize-observer-text.html) ([see source](https://github.com/mdn/dom-examples/blob/main/resize-observer/resize-observer-text.html)) example. This uses a simple feature detection test to see if the browser supports the newer `contentBoxSize` property — if so, it uses that to get the sizing data it needs. If not, it uses the older `contentRect` property.

 
```
const resizeObserver = new ResizeObserver((entries) => {
  for (const entry of entries) {
    if (entry.contentBoxSize) {
      h1Elem.style.fontSize = `${Math.max(
 1.5,
 entry.contentBoxSize.inlineSize / 200
 )}rem`;
      pElem.style.fontSize = `${Math.max(
 1,
 entry.contentBoxSize.inlineSize / 600
 )}rem`;
    } else {
      h1Elem.style.fontSize = `${Math.max(
 1.5,
 entry.contentRect.width / 200
 )}rem`;
      pElem.style.fontSize = `${Math.max(1, entry.contentRect.width / 600)}rem`;
    }
  }
});

resizeObserver.observe(divElem);

```


Specifications
--------------




| Specification |
| --- |
| [Resize Observer # resize-observer-entry-interface](https://w3c.github.io/csswg-drafts/resize-observer/#resize-observer-entry-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ResizeObserverEntry` | 64 | 79 | 69 | No | 51 | 13.1 | 64 | 64 | 79 | 47 | 13.4 | 9.0 |
| `borderBoxSize` | 84 | 84 | 9269–92Implemented as a single object representing a content box size, rather than an array of content box size objects. | No | 70 | 15.4 | 84 | 84 | 9279–92Implemented as a single object representing a content box size, rather than an array of content box size objects. | 60 | 15.4 | 14.0 |
| `contentBoxSize` | 84 | 84 | 9269–92Implemented as a single object representing a content box size, rather than an array of content box size objects. | No | 70 | 15.4 | 84 | 84 | 9279–92Implemented as a single object representing a content box size, rather than an array of content box size objects. | 60 | 15.4 | 14.0 |
| `contentRect` | 64 | 79 | 69 | No | 51 | 13.1 | 64 | 64 | 79 | 47 | 13.4 | 9.0 |
| `devicePixelContentBoxSize` | 84 | 84 | 93 | No | 70 | No | 84 | 84 | 93 | 60 | No | 14.0 |
| `target` | 64 | 79 | 69 | No | 51 | 13.1 | 64 | 64 | 79 | 47 | 13.4 | 9.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry>

ResizeObserverSize
==================



The `ResizeObserverSize` interface of the [`Resize Observer API`](resize_observer_api) is used by the [`ResizeObserverEntry`](resizeobserverentry) interface to access the box sizing properties of the element being observed.

  **Note:** In [multi-column layout](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Columns), which is a fragmented context, the sizing returned by `ResizeObserverSize` will be the size of the first column.

 

Instance properties
-------------------



 
[`ResizeObserverSize.blockSize`](resizeobserversize/blocksize) Read only 
  The length of the observed element's border box in the block dimension. For boxes with a horizontal [`writing-mode`](https://developer.mozilla.org/en-US/docs/Web/CSS/writing-mode), this is the vertical dimension, or height; if the writing-mode is vertical, this is the horizontal dimension, or width.

  
[`ResizeObserverSize.inlineSize`](resizeobserversize/inlinesize) Read only 
  The length of the observed element's border box in the inline dimension. For boxes with a horizontal [`writing-mode`](https://developer.mozilla.org/en-US/docs/Web/CSS/writing-mode), this is the horizontal dimension, or width; if the writing-mode is vertical, this is the vertical dimension, or height.

    **Note:** For more explanation of writing modes and block and inline dimensions, read [Handling different text directions](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Handling_different_text_directions).

 

Examples
--------



In this example the [`ResizeObserverEntry.contentBoxSize`](resizeobserverentry/contentboxsize) property returns a `ResizeObserverSize` object. This is an array containing the sizing information for the content box of the observed element.

 
```
const resizeObserver = new ResizeObserver((entries) => {
  for (const entry of entries) {
    console.log(entry.contentBoxSize[0]); // a ResizeObserverSize
  }
});

resizeObserver.observe(divElem);

```


Specifications
--------------




| Specification |
| --- |
| [Resize Observer # resizeobserversize](https://w3c.github.io/csswg-drafts/resize-observer/#resizeobserversize) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `ResizeObserverSize` | 84 | 84 | 69 | No | 70 | 15.4 | 84 | 84 | 79 | 60 | 15.4 | 14.0 |
| `blockSize` | 84 | 84 | 69 | No | 70 | 15.4 | 84 | 84 | 79 | 60 | 15.4 | 14.0 |
| `inlineSize` | 84 | 84 | 69 | No | 70 | 15.4 | 84 | 84 | 79 | 60 | 15.4 | 14.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverSize>

RsaOaepParams
=============


The `RsaOaepParams` dictionary of the [Web Crypto API](web_crypto_api) represents the object that should be passed as the `algorithm` parameter into [`SubtleCrypto.encrypt()`](subtlecrypto/encrypt), [`SubtleCrypto.decrypt()`](subtlecrypto/decrypt), [`SubtleCrypto.wrapKey()`](subtlecrypto/wrapkey), or [`SubtleCrypto.unwrapKey()`](subtlecrypto/unwrapkey), when using the [RSA\_OAEP](subtlecrypto/encrypt#rsa-oaep) algorithm.


Instance properties
-------------------


 `name`  A string. This should be set to `RSA-OAEP`.

  
`label` Optional
  An [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), a [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), or a [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) — an array of bytes that does not itself need to be encrypted but which should be bound to the ciphertext. A digest of the label is part of the input to the encryption operation.

 Unless your application calls for a label, you can just omit this argument and it will not affect the security of the encryption operation.

  
Examples
--------


See the examples for [`SubtleCrypto.encrypt()`](subtlecrypto/encrypt) and [`SubtleCrypto.decrypt()`](subtlecrypto/decrypt).


Specifications
--------------




| Specification |
| --- |
| [Web Cryptography API # dfn-RsaOaepParams](https://w3c.github.io/webcrypto/#dfn-RsaOaepParams) |


Browser compatibility
---------------------


See also
--------


* [`SubtleCrypto.encrypt()`](subtlecrypto/encrypt).
* [`SubtleCrypto.decrypt()`](subtlecrypto/decrypt).
* [`SubtleCrypto.wrapKey()`](subtlecrypto/wrapkey).
* [`SubtleCrypto.unwrapKey()`](subtlecrypto/unwrapkey).


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/RsaOaepParams>

RTCDataChannelEvent
===================



 The `RTCDataChannelEvent` interface represents an event related to a specific [`RTCDataChannel`](rtcdatachannel). 


 Event RTCDataChannelEvent

Constructor
-----------


 [`RTCDataChannelEvent()`](rtcdatachannelevent/rtcdatachannelevent)  Creates a new `RTCDataChannelEvent`.

  
Instance properties
-------------------



*Also inherits properties from [`Event`](event).*

  
[`channel`](rtcdatachannelevent/channel) Read only 
  Returns the [`RTCDataChannel`](rtcdatachannel) associated with the event.

  

Examples
--------



In this example, the `datachannel` event handler is set up to save the data channel reference and set up handlers for the events which need to be monitored. The [`channel`](rtcdatachannelevent/channel) property provides the [`RTCDataChannel`](rtcdatachannel) representing the connection to the other peer.

 
```
pc.ondatachannel = (event) => {
  inboundDataChannel = event.channel;
  inboundDataChannel.onmessage = handleIncomingMessage;
  inboundDataChannel.onopen = handleChannelOpen;
  inboundDataChannel.onclose = handleChannelClose;
};

```
 See [A simple RTCDataChannel sample](webrtc_api/simple_rtcdatachannel_sample) for another, more complete, example of how to use data channels.



Specifications
--------------




| Specification |
| --- |
| [WebRTC: Real-Time Communication in Browsers # rtcdatachannelevent](https://w3c.github.io/webrtc-pc/#rtcdatachannelevent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `RTCDataChannelEvent` | 56 | 79 | 22 | No | 43 | 11 | 56 | 56 | 24 | 43 | 11 | 7.0 |
| `RTCDataChannelEvent` | 24 | 79 | 22 | No | ≤15 | 11 | 4.4 | 25 | 24 | ≤14 | 11 | 1.5 |
| `channel` | 24 | 79 | 22 | No | ≤15 | 11 | 4.4 | 25 | 24 | ≤14 | 11 | 1.5 |


See also
--------


* [WebRTC](webrtc_api)
* [`RTCDataChannel`](rtcdatachannel)
* [A simple RTCDataChannel sample](webrtc_api/simple_rtcdatachannel_sample)
* [`RTCPeerConnection`](rtcpeerconnection) (the target interface for [`datachannel`](rtcpeerconnection/datachannel_event) events)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannelEvent>

RTCError
========



The `RTCError` interface describes an error which has occurred while handling [WebRTC](webrtc_api) operations. It's based upon the standard [`DOMException`](domexception) interface that describes general DOM errors.


 DOMException RTCError

Constructor
-----------


 `RTCError()`  Creates and returns a new `RTCError` object initialized with the different parameters and, optionally, a string to use as the value of the error's [`message`](domexception/message) property.

  
Instance properties
-------------------



*In addition to the properties defined by the parent interface, [`DOMException`](domexception), `RTCError` includes the following properties:*

  
[`errorDetail`](rtcerror/errordetail) Read only 
  A string specifying the WebRTC-specific error code identifying the type of error that occurred.

  
[`receivedAlert`](rtcerror/receivedalert) Read only 
  An unsigned long integer value indicating the fatal [DTLS](https://developer.mozilla.org/en-US/docs/Glossary/DTLS) error which was received from the network. Only valid if the `errorDetail` string is `dtls-failure`. If `null`, no DTLS error was received.

  
[`sctpCauseCode`](rtcerror/sctpcausecode) Read only 
  If `errorDetail` is `sctp-failure`, this property is a long integer specifying the [SCTP](https://developer.mozilla.org/en-US/docs/Glossary/SCTP) cause code indicating the cause of the failed SCTP negotiation. `null` if the error isn't an SCTP error.

  
[`sdpLineNumber`](rtcerror/sdplinenumber) Read only 
  If `errorDetail` is `sdp-syntax-error`, this property is a long integer identifying the line number of the [SDP](https://developer.mozilla.org/en-US/docs/Glossary/SDP) on which the syntax error occurred. `null` if the error isn't an SDP syntax error.

  
[`sentAlert`](rtcerror/sentalert) Read only 
  If `errorDetail` is `dtls-failure`, this property is an unsigned long integer indicating the fatal DTLS error that was sent out by this device. If `null`, no DTLS error was transmitted.

    **Note:** All `RTCError` objects have their [`name`](domexception/name) set to `OperationError`.

 

Examples
--------



 In this example, a handler is established for an [`RTCDataChannel`](rtcdatachannel)'s [`error`](rtcdatachannel/error_event) event. 

 
```
dataChannel.addEventListener("error", (event) => {
  let error = event.error; // event.error is an RTCError

  if (error.errorDetail === "sdp-syntax-error") {
    let errLine = error.sdpLineNumber;
    let errMessage = error.message;

    let alertMessage = `A syntax error occurred interpreting line ${errLine} of the SDP: ${errMessage}`;
    showMyAlertMessage("Data Channel Error", alertMessage);
  } else {
    terminateMyConnection();
  }
});

```
  If the error is an SDP syntax error—indicated by its [`errorDetail`](rtcerror/errordetail) property being `sdp-syntax-error`—, a message string is constructed to present the error message and the line number within the SDP at which the error occurred. This message is then displayed using a function called `showMyAlertMessage()`, which stands in for whatever output mechanism this code might use. 

  Any other error is treated as terminal, causing a `terminateMyConnection()` function to be called. 

  The above example uses [`addEventListener()`](eventtarget/addeventlistener) to add the handler for `error` events. You can also use the `RTCDataChannel` object's [`onerror`](rtcdatachannel/error_event) event handler property, like this: 

 
```
dataChannel.onerror = (event) => {
  let error = event.error;

  /\* and so forth \*/
};

```


Specifications
--------------




| Specification |
| --- |
| [WebRTC: Real-Time Communication in Browsers # dom-rtcerror](https://w3c.github.io/webrtc-pc/#dom-rtcerror) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `RTCError` | 74 | 79 | No | No | 60 | 15.4 | 74 | 74 | No | 53 | 15.4 | 11.0 |
| `RTCError` | 74 | 79 | No | No | 60 | 15.4 | 74 | 74 | No | 53 | 15.4 | 11.0 |
| `errorDetail` | 74 | 79 | No | No | 60 | 15.4 | 74 | 74 | No | 53 | 15.4 | 11.0 |
| `httpRequestStatusCode` | 74 | 79 | No | No | 62 | No | 74 | 74 | No | 53 | No | 11.0 |
| `receivedAlert` | 74 | 79 | No | No | 60 | 15.4 | 74 | 74 | No | 53 | 15.4 | 11.0 |
| `sctpCauseCode` | 74 | 79 | No | No | 60 | 15.4 | 74 | 74 | No | 53 | 15.4 | 11.0 |
| `sdpLineNumber` | 74 | 79 | No | No | 60 | 15.4 | 74 | 74 | No | 53 | 15.4 | 11.0 |
| `sentAlert` | 74 | 79 | No | No | 60 | 15.4 | 74 | 74 | No | 53 | 15.4 | 11.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/RTCError>

RTCErrorEvent
=============



The WebRTC API's `RTCErrorEvent` interface represents an error sent to a WebRTC object. It's based on the standard [`Event`](event) interface, but adds RTC-specific information describing the error, as shown below.


 Event RTCErrorEvent

Constructor
-----------


 `RTCErrorEvent()`  Creates and returns a new `RTCErrorEvent` object.

  
Instance properties
-------------------



*In addition to the standard properties available on the [`Event`](event) interface, `RTCErrorEvent` also includes the following:*

  
[`error`](rtcerrorevent/error) Read only 
  An [`RTCError`](rtcerror) object specifying the error which occurred; this object includes the type of error that occurred, information about where the error occurred (such as which line number in the [SDP](https://developer.mozilla.org/en-US/docs/Glossary/SDP) or what [SCTP](https://developer.mozilla.org/en-US/docs/Glossary/SCTP) cause code was at issue).

  

Instance methods
----------------


*No additional methods are provided beyond any found on the parent interface, [`Event`](event).*


Description
-----------


There are other data types used for error events in WebRTC, as needed for errors with special information sharing requirements. The most common of these is probably [`RTCPeerConnectionIceErrorEvent`](rtcpeerconnectioniceerrorevent), used by the [`icecandidateerror`](rtcpeerconnection/icecandidateerror_event) event, which signals an error that has occurred while gathering ICE candidates during connection negotiation.


Specifications
--------------




| Specification |
| --- |
| [WebRTC: Real-Time Communication in Browsers # dom-rtcerrorevent](https://w3c.github.io/webrtc-pc/#dom-rtcerrorevent) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `RTCErrorEvent` | 74 | 79 | No | No | 62 | 15.4 | 74 | 74 | No | 53 | 15.4 | 11.0 |
| `RTCErrorEvent` | 74 | 79 | No | No | 60 | 15.4 | 74 | 74 | No | 53 | 15.4 | 11.0 |
| `error` | 74 | 79 | No | No | 60 | 15.4 | 74 | 74 | No | 53 | 15.4 | 11.0 |


See also
--------


* WebRTC API
* [`RTCError`](rtcerror)
* The `error` event occurs on the following interfaces: [`RTCDataChannel`](rtcdatachannel) and [`RTCDtlsTransport`](rtcdtlstransport)
* [`RTCPeerConnectionIceErrorEvent`](rtcpeerconnectioniceerrorevent)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/RTCErrorEvent>

RTCIceCandidate
===============



The `RTCIceCandidate` interface—part of the [WebRTC API](webrtc_api)—represents a candidate Interactive Connectivity Establishment ([ICE](https://developer.mozilla.org/en-US/docs/Glossary/ICE)) configuration which may be used to establish an [`RTCPeerConnection`](rtcpeerconnection).

 An ICE candidate describes the protocols and routing needed for WebRTC to be able to communicate with a remote device. When starting a WebRTC peer connection, typically a number of candidates are proposed by each end of the connection, until they mutually agree upon one which describes the connection they decide will be best. WebRTC then uses that candidate's details to initiate the connection.

 For details on how the ICE process works, see [Lifetime of a WebRTC session](webrtc_api/session_lifetime). The article [WebRTC connectivity](webrtc_api/connectivity) provides additional useful details.



Constructor
-----------


 [`RTCIceCandidate()`](rtcicecandidate/rtcicecandidate)  Creates an `RTCIceCandidate` object to represent a single ICE candidate, optionally configured based on a configuration object.

  **Note:** For backwards compatibility, the constructor also accepts as input a string containing the value of the [`candidate`](rtcicecandidate/candidate) property instead of the configuration object.

   
Instance properties
-------------------


 
[`address`](rtcicecandidate/address) Read only 
  A string containing the IP address of the candidate.

  
[`candidate`](rtcicecandidate/candidate) Read only 
  A string representing the transport address for the candidate that can be used for connectivity checks. The format of this address is a `candidate-attribute` as defined in [RFC 5245](https://datatracker.ietf.org/doc/html/rfc5245). This string is empty (`""`) if the `RTCIceCandidate` is an "end of candidates" indicator.

  
[`component`](rtcicecandidate/component) Read only 
  A string which indicates whether the candidate is an RTP or an RTCP candidate; its value is either `rtp` or `rtcp`, and is derived from the `"component-id"` field in the `candidate` a-line string.

  
[`foundation`](rtcicecandidate/foundation) Read only 
  Returns a string containing a unique identifier that is the same for any candidates of the same type, share the same base (the address from which the ICE agent sent the candidate), and come from the same [STUN](https://developer.mozilla.org/en-US/docs/Glossary/STUN) server. This is used to help optimize ICE performance while prioritizing and correlating candidates that appear on multiple [`RTCIceTransport`](rtcicetransport) objects.

  
[`port`](rtcicecandidate/port) Read only 
  An integer value indicating the candidate's port number.

  
[`priority`](rtcicecandidate/priority) Read only 
  A long integer value indicating the candidate's priority.

  
[`protocol`](rtcicecandidate/protocol) Read only 
  A string indicating whether the candidate's protocol is `"tcp"` or `"udp"`.

  
[`relatedAddress`](rtcicecandidate/relatedaddress) Read only 
  If the candidate is derived from another candidate, `relatedAddress` is a string containing that host candidate's IP address. For host candidates, this value is `null`.

  
[`relatedPort`](rtcicecandidate/relatedport) Read only 
  For a candidate that is derived from another, such as a relay or reflexive candidate, the `relatedPort` is a number indicating the port number of the candidate from which this candidate is derived. For host candidates, the `relatedPort` property is `null`.

  
[`sdpMid`](rtcicecandidate/sdpmid) Read only 
  A string specifying the candidate's media stream identification tag which uniquely identifies the media stream within the component with which the candidate is associated, or `null` if no such association exists.

  
[`sdpMLineIndex`](rtcicecandidate/sdpmlineindex) Read only 
  If not `null`, `sdpMLineIndex` indicates the zero-based index number of the media description (as defined in [RFC 4566](https://datatracker.ietf.org/doc/html/rfc4566)) in the [SDP](https://developer.mozilla.org/en-US/docs/Glossary/SDP) with which the candidate is associated.

  
[`tcpType`](rtcicecandidate/tcptype) Read only 
  If `protocol` is `"tcp"`, `tcpType` represents the type of TCP candidate. Otherwise, `tcpType` is `null`.

  
[`type`](rtcicecandidate/type) Read only 
  A string indicating the type of candidate as one of the strings listed on [`RTCIceCandidate.type`](rtcicecandidate/type#values).

  
[`usernameFragment`](rtcicecandidate/usernamefragment) Read only 
  A string containing a randomly-generated username fragment ("ice-ufrag") which ICE uses for message integrity along with a randomly-generated password ("ice-pwd"). You can use this string to verify generations of ICE generation; each generation of the same ICE process will use the same `usernameFragment`, even across ICE restarts.

  
Instance methods
----------------


 [`toJSON()`](rtcicecandidate/tojson)   Returns a [JSON](https://developer.mozilla.org/en-US/docs/Glossary/JSON) representation of the `RTCIceCandidate`'s current configuration. The format of the representation is the same as the `candidateInfo` object that can optionally be passed to the [`RTCIceCandidate() constructor`](rtcicecandidate/rtcicecandidate) to configure a candidate. 

  
Examples
--------


For examples, see the article [Signaling and video calling](webrtc_api/signaling_and_video_calling), which demonstrates the entire process.


Specifications
--------------




| Specification |
| --- |
| [WebRTC: Real-Time Communication in Browsers # rtcicecandidate-interface](https://w3c.github.io/webrtc-pc/#rtcicecandidate-interface) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `RTCIceCandidate` | 23 | 15 | 44Before Firefox 68, the constructor's `candidateInfo` parameter is required and the `candidateInfo` object must have a `candidate` property.22Before Firefox 68, the constructor's `candidateInfo` parameter is required and the `candidateInfo` object must have a `candidate` property. | No | 15 | 11 | 4.4 | 25 | 44Before Firefox 68, the constructor's `candidateInfo` parameter is required and the `candidateInfo` object must have a `candidate` property.24Before Firefox 68, the constructor's `candidateInfo` parameter is required and the `candidateInfo` object must have a `candidate` property. | 14 | 11 | 1.5 |
| `RTCIceCandidate` | 23 | 15 | 4422 | No | 15 | 11 | 4.4 | 25 | 4424 | 14 | 11 | 1.5 |
| `address` | 74 | 79 | No | No | 62 | 14.1 | 74 | 74 | No | 53 | 14.5 | 11.0 |
| `candidate` | 23 | 15 | 22 | No | 15 | 11 | 4.4 | 25 | 24 | 14 | 11 | 1.5 |
| `component` | 74 | 79 | No | No | 62 | 14.1 | 74 | 74 | No | 53 | 14.5 | 11.0 |
| `foundation` | 74 | 79 | No | No | 62 | 14.1 | 74 | 74 | No | 53 | 14.5 | 11.0 |
| `port` | 74 | 79 | No | No | 62 | 14.1 | 74 | 74 | No | 53 | 14.5 | 11.0 |
| `priority` | 74 | 79 | No | No | 62 | 14.1 | 74 | 74 | No | 53 | 14.5 | 11.0 |
| `protocol` | 74 | 79 | No | No | 62 | 14.1 | 74 | 74 | No | 53 | 14.5 | 11.0 |
| `relatedAddress` | 74 | 79 | No | No | 62 | 14.1 | 74 | 74 | No | 53 | 14.5 | 11.0 |
| `relatedPort` | 74 | 79 | No | No | 62 | 14.1 | 74 | 74 | No | 53 | 14.5 | 11.0 |
| `sdpMLineIndex` | 23 | 15 | 22 | No | 15 | 11 | 4.4 | 25 | 24 | 14 | 11 | 1.5 |
| `sdpMid` | 23 | 15 | 22 | No | 15 | 11 | 4.4 | 25 | 24 | 14 | 11 | 1.5 |
| `tcpType` | 74 | 79 | No | No | 62 | 14.1 | 74 | 74 | No | 53 | 14.5 | 11.0 |
| `toJSON` | 43 | 15 | 27 | No | 30 | 11 | 43 | 43 | 27 | 30 | 11 | 4.0 |
| `type` | 74 | 79 | No | No | 62 | 14.1 | 74 | 74 | No | 53 | 14.5 | 11.0 |
| `usernameFragment` | 74 | 79 | 67 | No | 62 | 14.1 | 74 | 74 | 67 | 53 | 14.5 | 11.0 |



 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/RTCIceCandidate>

RTCDataChannel
==============



The `RTCDataChannel` interface represents a network channel which can be used for bidirectional peer-to-peer transfers of arbitrary data. Every data channel is associated with an [`RTCPeerConnection`](rtcpeerconnection), and each peer connection can have up to a theoretical maximum of 65,534 data channels (the actual limit may vary from browser to browser).

 To create a data channel and ask a remote peer to join you, call the [`RTCPeerConnection`](rtcpeerconnection)'s [`createDataChannel()`](rtcpeerconnection/createdatachannel) method. The peer being invited to exchange data receives a [`datachannel`](rtcpeerconnection/datachannel_event) event (which has type [`RTCDataChannelEvent`](rtcdatachannelevent)) to let it know the data channel has been added to the connection.

 `RTCDataChannel` is a [transferable object](web_workers_api/transferable_objects).


 EventTarget RTCDataChannel

Instance properties
-------------------



*Also inherits properties from [`EventTarget`](eventtarget).*

  [`binaryType`](rtcdatachannel/binarytype)   A string specifying the type of object that should be used to represent binary data received on the `RTCDataChannel`. Values are the same as allowed on the [`WebSocket.binaryType`](websocket/binarytype) property: `blob` if [`Blob`](blob) objects are being used, or `arraybuffer` if [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) objects are being used. The default is `blob`. 

  
[`bufferedAmount`](rtcdatachannel/bufferedamount) Read only 
   Returns the number of bytes of data currently queued to be sent over the data channel. 

  [`bufferedAmountLowThreshold`](rtcdatachannel/bufferedamountlowthreshold)   Specifies the number of bytes of buffered outgoing data that is considered "low". The default value is 0. 

  
[`id`](rtcdatachannel/id) Read only 
   Returns an ID number (between 0 and 65,534) which uniquely identifies the `RTCDataChannel`. 

  
[`label`](rtcdatachannel/label) Read only 
   Returns a string that contains a name describing the data channel. These labels are not required to be unique. 

  
[`maxPacketLifeTime`](rtcdatachannel/maxpacketlifetime) Read only 
   Returns the amount of time, in milliseconds, the browser is allowed to take to attempt to transmit a message, as set when the data channel was created, or `null`. 

  
[`maxRetransmits`](rtcdatachannel/maxretransmits) Read only 
   Returns the maximum number of times the browser should try to retransmit a message before giving up, as set when the data channel was created, or `null`, which indicates that there is no maximum. 

  
[`negotiated`](rtcdatachannel/negotiated) Read only 
   Indicates whether the `RTCDataChannel`'s connection was negotiated by the Web app (`true`) or by the WebRTC layer (`false`). The default is `false`. 

  
[`ordered`](rtcdatachannel/ordered) Read only 
   Indicates whether or not the data channel guarantees in-order delivery of messages; the default is `true`, which indicates that the data channel is indeed ordered. 

  
[`protocol`](rtcdatachannel/protocol) Read only 
   Returns a string containing the name of the subprotocol in use. If no protocol was specified when the data channel was created, then this property's value is the empty string (`""`). 

  
[`readyState`](rtcdatachannel/readystate) Read only 
   Returns a string which indicates the state of the data channel's underlying data connection. It can have one of the following values: `connecting`, `open`, `closing`, or `closed`. 

  

### Obsolete properties


 
[`reliable`](rtcdatachannel/reliable) Read only   Deprecated   Non-standard 
  Indicates whether or not the data channel is *reliable*.

  
Instance methods
----------------



*Also inherits methods from [`EventTarget`](eventtarget).*

  [`close()`](rtcdatachannel/close)   Closes the [`RTCDataChannel`](rtcdatachannel). Either peer is permitted to call this method to initiate closure of the channel. 

  [`send()`](rtcdatachannel/send)  Sends data across the data channel to the remote peer.

  

Events
------


 [`bufferedamountlow`](rtcdatachannel/bufferedamountlow_event)   Sent when the number of bytes of data in the outgoing data buffer falls below the value specified by [`bufferedAmountLowThreshold`](rtcdatachannel/bufferedamountlowthreshold). 

  [`close`](rtcdatachannel/close_event)  Sent when the underlying data transport closes.

  [`closing`](rtcdatachannel/closing_event)  Sent when the underlying data transport is about to start closing.

  [`error`](rtcdatachannel/error_event)  Sent when an error occurs on the data channel.

  [`message`](rtcdatachannel/message_event)   Sent when a message has been received from the remote peer. The message contents can be found in the event's [`data`](messageevent/data) property. 

  [`open`](rtcdatachannel/open_event)   Sent when the data channel is first opened, or when an existing data channel's underlying connection re-opens. 

  
Data format
-----------


The underlying data format is defined by the IEEE specification [SDP Offer/Answer Procedures for SCTP over DTLS Transport(RFC 8841)](https://datatracker.ietf.org/doc/rfc8841/). The current format specifies its protocol as either `"UDP/DTLS/SCTP"` (UDP carrying DTLS carrying SCTP) or `"TCP/DTLS/SCTP"` (TCP carrying DTLS carrying SCTP). Older browsers may only specify `"DTLS/SCTP"`.


Example
-------



```
const pc = new RTCPeerConnection();
const dc = pc.createDataChannel("my channel");

dc.onmessage = (event) => {
  console.log(`received: ${event.data}`);
};

dc.onopen = () => {
  console.log("datachannel open");
};

dc.onclose = () => {
  console.log("datachannel close");
};

```

Specifications
--------------




| Specification |
| --- |
| [WebRTC: Real-Time Communication in Browsers # rtcdatachannel](https://w3c.github.io/webrtc-pc/#rtcdatachannel) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `RTCDataChannel` | 24 | 79 | 22 | No | 15 | 11 | 4.4 | 25 | 24 | 14 | 11 | 1.5 |
| `binaryType` | 24 | 79 | 22 | No | 15 | 11 | 4.4 | 25 | 24 | 14 | 11 | 1.5 |
| `bufferedAmount` | 24 | 79 | 22 | No | 15 | 11 | 4.4 | 25 | 24 | 14 | 11 | 1.5 |
| `bufferedAmountLowThreshold` | 46 | 79 | 44 | No | 33 | 11 | 46 | 46 | 44 | 33 | 11 | 5.0 |
| `bufferedamountlow_event` | 57The default for `rtcpMuxPolicy` is `require`. | 79The default for `rtcpMuxPolicy` is `require`. | 44 | No | 44The default for `rtcpMuxPolicy` is `require`. | 11 | 57The default for `rtcpMuxPolicy` is `require`. | 57The default for `rtcpMuxPolicy` is `require`. | 44 | 43The default for `rtcpMuxPolicy` is `require`. | 11 | 7.0The default for `rtcpMuxPolicy` is `require`. |
| `close` | 24 | 79 | 22 | No | 15 | 11 | 4.4 | 25 | 24 | 14 | 11 | 1.5 |
| `close_event` | 24 | 79 | 22 | No | 15 | 11 | 4.4 | 25 | 24 | 14 | 11 | 1.5 |
| `closing_event` | 81 | 81 | No | No | 68 | 15.4 | 81 | 81 | No | 58 | 15.4 | 13.0 |
| `error_event` | 24 | 79 | 22 | No | 15 | 11 | 4.4 | 25 | 24 | 14 | 11 | 1.5 |
| `id` | 30 | 79 | 22 | No | 17 | 11 | 4.4 | 30 | 24 | 18 | 11 | 2.0 |
| `label` | 24 | 79 | 22 | No | 15 | 11 | 4.4 | 25 | 24 | 14 | 11 | 1.5 |
| `maxPacketLifeTime` | 56 | 79 | 62 | No | 43 | 11 | 56 | 56 | 62 | 43 | 11 | 6.0 |
| `maxRetransmits` | 30 | 79 | 62 | No | 17 | 11 | 4.4 | 30 | 62 | 18 | 11 | 2.0 |
| `message_event` | 24 | 79 | 22 | No | 15 | 11 | 4.4 | 25 | 24 | 14 | 11 | 1.5 |
| `negotiated` | 30 | 79 | 68 | No | 17 | 11 | 4.4 | 30 | 68 | 18 | 11 | 2.0 |
| `open_event` | 24 | 79 | 22 | No | 15 | 11 | 4.4 | 25 | 24 | 14 | 11 | 1.5 |
| `ordered` | 30 | 79 | 22 | No | 17 | 11 | 4.4 | 30 | 24 | 18 | 11 | 2.0 |
| `priority` | No | No | No | No | No | 15 | No | No | No | No | 15 | No |
| `protocol` | 30 | 79 | 22 | No | 17 | 11 | 4.4 | 30 | 24 | 18 | 11 | 2.0 |
| `readyState` | 24 | 79 | 22 | No | 15 | 11 | 4.4 | 25 | 24 | 14 | 11 | 1.5 |
| `reliable` | 24 | 79 | 22 | No | 15 | No | 4.4 | 25 | 24 | 14 | No | 1.5 |
| `sctp_sdp_21` | 58 | 79 | 63 | No | 45 | No | 58 | 58 | 63 | 43 | No | 7.0 |
| `send` | 24 | 79 | 22 | No | 15 | 11 | 4.4 | 25 | 24 | 14 | 11 | 1.5 |
| `transferable` | NoSee [bug 1244165](https://crbug.com/1244165) | NoSee [bug 1244165](https://crbug.com/1244165) | NoSee [bug 1209163](https://bugzil.la/1209163) | No | NoSee [bug 1244165](https://crbug.com/1244165) | 15 | NoSee [bug 1244165](https://crbug.com/1244165) | NoSee [bug 1244165](https://crbug.com/1244165) | NoSee [bug 1209163](https://bugzil.la/1209163) | NoSee [bug 1244165](https://crbug.com/1244165) | No | NoSee [bug 1244165](https://crbug.com/1244165) |


See also
--------


* [WebRTC API](webrtc_api)


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel>

RTCDtlsTransport
================



The `RTCDtlsTransport` interface provides access to information about the Datagram Transport Layer Security (**[DTLS](https://developer.mozilla.org/en-US/docs/Glossary/DTLS)**) transport over which a [`RTCPeerConnection`](rtcpeerconnection)'s [RTP](https://developer.mozilla.org/en-US/docs/Glossary/RTP) and [RTCP](https://developer.mozilla.org/en-US/docs/Glossary/RTCP) packets are sent and received by its [`RTCRtpSender`](rtcrtpsender) and [`RTCRtpReceiver`](rtcrtpreceiver) objects.

 A `RTCDtlsTransport` object is also used to provide information about [SCTP](https://developer.mozilla.org/en-US/docs/Glossary/SCTP) packets transmitted and received by an connection's [data channels](rtcdatachannel).

 Features of the DTLS transport include the addition of security to the underlying transport; the `RTCDtlsTransport` interface can be used to obtain information about the underlying transport and the security added to it by the DTLS layer.


 EventTarget RTCDtlsTransport

Instance properties
-------------------



*Also inherits properties from [`EventTarget`](eventtarget).*

  
[`iceTransport`](rtcdtlstransport/icetransport) Read only 
  Returns a reference to the underlying [`RTCIceTransport`](rtcicetransport) object.

  
[`state`](rtcdtlstransport/state) Read only 
   Returns a string which describes the underlying Datagram Transport Layer Security (**[DTLS](https://developer.mozilla.org/en-US/docs/Glossary/DTLS)**) transport state. It can be one of the following values: `new`, `connecting`, `connected`, `closed`, or `failed`. 

  

### Event handlers


 `onerror`   An [event handler](https://developer.mozilla.org/en-US/docs/Web/Events/Event_handlers) which specifies a function the browser calls when the [`error`](rtcdtlstransport/error_event) event is received. 

  `onstatechange`   An [event handler](https://developer.mozilla.org/en-US/docs/Web/Events/Event_handlers) which specifies a function the browser calls when the `statechange` event is received. 

  
Instance methods
----------------



*Also inherits methods from [`EventTarget`](eventtarget).*

  `getRemoteCertificates()`  Returns an array of [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing the certificates of the remote peer of the connection.

  

Events
------


 [`error`](rtcdtlstransport/error_event)  Sent when a transport-level error occurs on the [`RTCPeerConnection`](rtcpeerconnection).

  `statechange`  Sent when the [`state`](rtcdtlstransport/state) of the DTLS transport changes.

  
Description
-----------


### Allocation of DTLS transports



`RTCDtlsTransport` objects are created when an app calls either [`setLocalDescription()`](rtcpeerconnection/setlocaldescription) or [`setRemoteDescription()`](rtcpeerconnection/setremotedescription). The number of DTLS transports created and how they're used depends on the bundling mode used when creating the [`RTCPeerConnection`](rtcpeerconnection).

 Whether bundling is used depends on what the other endpoint is able to negotiate. All browsers support bundling, so when both endpoints are browsers, you can rest assured that bundling will be used.

 Some non-browser legacy endpoints, however, may not support bundle. To be able to negotiate with such endpoints (or to exclude them entirely), the `bundlePolicy` property may be provided when creating the connection. The `bundlePolicy` [lets you control](rtcpeerconnection#rtcbundlepolicy_enum) how to negotiate with these legacy endpoints. The default policy is `"balanced"`, which provides a balance between performance and compatibility.

 For example, to create the connection using the highest level of bundling:

 
```
const rtcConfig = {
  bundlePolicy: "max-bundle",
};

const pc = new RTCPeerConnection(rtcConfig);

```
 [Bundling](https://webrtcstandards.info/sdp-bundle/) lets you use one `RTCDtlsTransport` to carry the data for multiple higher-level transports, such as multiple [`RTCRtpTransceiver`](rtcrtptransceiver)s.

 #### When not using BUNDLE

 When the connection is created without using BUNDLE, each RTP or RTCP component of each [`RTCRtpTransceiver`](rtcrtptransceiver) has its own `RTCDtlsTransport`; that is, every [`RTCRtpSender`](rtcrtpsender) and [`RTCRtpReceiver`](rtcrtpreceiver), has its own transport, and all [`RTCDataChannel`](rtcdatachannel) objects share a transport dedicated to SCTP.

 #### When using BUNDLE

 When the connection is using BUNDLE, each `RTCDtlsTransport` object represents a group of [`RTCRtpTransceiver`](rtcrtptransceiver) objects. If the connection was created using `max-compat` mode, each transport is responsible for handling all of the communications for a given type of media (audio, video, or data channel). Thus, a connection that has any number of audio and video channels will always have exactly one DTLS transport for audio and one for video communications.

 Because transports are established early in the negotiation process, it's likely that it won't be known until after they're created whether or not the remote peer supports bundling or not. For this reason, you'll sometimes see separate transports created at first, one for each track, then see them get bundled up once it's known that bundling is possible. If your code accesses [`RTCRtpSender`](rtcrtpsender)s and/or [`RTCRtpReceiver`](rtcrtpreceiver)s directly, you may encounter situations where they're initially separate, then half or more of them get closed and the senders and receivers updated to refer to the appropriate remaining `RTCDtlsTransport` objects.



### Data channels



[`RTCDataChannel`](rtcdatachannel)s use [SCTP](https://developer.mozilla.org/en-US/docs/Glossary/SCTP) to communicate. All of a peer connection's data channels share a single [`RTCSctpTransport`](rtcsctptransport), found in the connection's [`sctp`](rtcpeerconnection/sctp) property.

 You can, in turn, identify the `RTCDtlsTransport` used to securely encapsulate the data channels' SCTP communications by looking at the `RTCSctpTransport` object's `transport` property.



Examples
--------



This example presents a function, `tallySenders()`, which iterates over an `RTCPeerConnection`'s [`RTCRtpSender`](rtcrtpsender)s, tallying up how many of them are in various states. The function returns an object containing properties whose values indicate how many of the senders are in each state.

 
```
let pc = new RTCPeerConnection({ bundlePolicy: "max-bundle" });

// …

function tallySenders(pc) {
  let results = {
    transportMissing: 0,
    connectionPending: 0,
    connected: 0,
    closed: 0,
    failed: 0,
    unknown: 0,
  };

  let senderList = pc.getSenders();
  senderList.forEach((sender) => {
    let transport = sender.transport;

    if (!transport) {
      results.transportMissing++;
    } else {
      switch (transport.state) {
        case "new":
        case "connecting":
          results.connectionPending++;
          break;
        case "connected":
          results.connected++;
          break;
        case "closed":
          results.closed++;
          break;
        case "failed":
          results.failed++;
          break;
        default:
          results.unknown++;
          break;
      }
    }
  });
  return results;
}

```
 Note that in this code, the `new` and `connecting` states are being treated as a single `connectionPending` status in the returned object.



Specifications
--------------




| Specification |
| --- |
| [WebRTC: Real-Time Communication in Browsers # dom-rtcdtlstransport](https://w3c.github.io/webrtc-pc/#dom-rtcdtlstransport) |


Browser compatibility
---------------------




|  | Desktop | Mobile |
| --- | --- | --- |
|  | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet |
| `RTCDtlsTransport` | 72 | 12 | NoSee [bug 1307996](https://bugzil.la/1307996). | No | 60 | 15.4 | 72 | 72 | NoSee [bug 1307996](https://bugzil.la/1307996). | 50 | 15.4 | 11.0 |
| `error_event` | 72 | 12 | NoSee [bug 1307996](https://bugzil.la/1307996). | No | 60 | 15.4 | 72 | 72 | NoSee [bug 1307996](https://bugzil.la/1307996). | 50 | 15.4 | 11.0 |
| `getRemoteCertificates` | 72 | 12 | NoSee [bug 1307996](https://bugzil.la/1307996). | No | 60 | 15.4 | 72 | 72 | NoSee [bug 1307996](https://bugzil.la/1307996). | 50 | 15.4 | 11.0 |
| `iceTransport` | 72 | 7915–79 | NoSee [bug 1307996](https://bugzil.la/1307996). | No | 60 | 15.4 | 72 | 72 | NoSee [bug 1307996](https://bugzil.la/1307996). | 50 | 15.4 | 11.0 |
| `state` | 72 | 12 | NoSee [bug 1307996](https://bugzil.la/1307996). | No | 60 | 15.4 | 72 | 72 | NoSee [bug 1307996](https://bugzil.la/1307996). | 50 | 15.4 | 11.0 |
| `statechange_event` | 72 | 7912–79 | NoSee [bug 1307996](https://bugzil.la/1307996). | No | 60 | 15.4 | 72 | 72 | NoSee [bug 1307996](https://bugzil.la/1307996). | 50 | 15.4 | 11.0 |


See also
--------


* [`RTCRtpSender.transport`](rtcrtpsender/transport) and [`RTCRtpReceiver.transport`](rtcrtpreceiver/transport)
* `RTCSctpTransport.transport`


 © 2005–2023 MDN contributors.  
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.  

<https://developer.mozilla.org/en-US/docs/Web/API/RTCDtlsTransport>

RTCDTMFSender
=============



The `RTCDTMFSender` interface provides a mechanism for transmitting [DTMF](https://developer.mozilla.org/en-US/docs/Glossary/DTMF) codes on a [WebRTC](webrtc_api) [`RTCPeerConnection`](rtcpeerconnection). You gain access 
[cell cut: 21,743,394 characters, first 4,193,889 kept]