repo_id
stringlengths
22
103
file_path
stringlengths
41
147
content
stringlengths
181
193k
__index_level_0__
int64
0
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/location/index.md
--- title: "Window: location property" short-title: location slug: Web/API/Window/location page-type: web-api-instance-property browser-compat: api.Window.location --- {{APIRef}} The **`Window.location`** read-only property returns a {{domxref("Location")}} object with information about the current location of the document. Though `Window.location` is a _read-only_ `Location` object, you can also assign a string to it. This means that you can work with `location` as if it were a string in most cases: `location = 'http://www.example.com'` is a synonym of `location.href = 'http://www.example.com'`. See {{domxref("Location")}} for all available properties. ## Value A {{domxref("Location")}} object. ## Examples ### Basic Example ```js alert(location); // alerts "https://developer.mozilla.org/en-US/docs/Web/API/Window/location" ``` ### Example 1: Navigate to a new page Whenever a new value is assigned to the location object, a document will be loaded using the URL as if `location.assign()` had been called with the modified URL. Note that [navigation-related sandbox flags](https://html.spec.whatwg.org/multipage/browsers.html#allowed-to-navigate) may result in an exception being thrown and the navigation failing. ```js location.assign("https://www.mozilla.org"); // or location = "https://www.mozilla.org"; ``` ### Example 2: Reloading the current page ```js location.reload(); ``` ### Example 3 Consider the following example, which will reload the page by using the [`replace()`](/en-US/docs/Web/API/Location/replace) method to insert the value of `location.pathname` into the hash: ```js function reloadPageWithHash() { location.replace(`https://example.com/#${location.pathname}`); } ``` ### Example 4: Display the properties of the current URL in an alert dialog ```js function showLoc() { const logLines = [ "Property (Typeof): Value", `location (${typeof location}): ${location}`, ]; for (const prop in location) { logLines.push( `${prop} (${typeof location[prop]}): ${location[prop] || "n/a"}`, ); } alert(logLines.join("\n")); } // in html: <button onclick="showLoc();">Show location properties</button> ``` ### Example 5: Send a string of data to the server by modifying the `search` property ```js function sendData(data) { location.search = data; } // in html: <button onclick="sendData('Some data');">Send data</button> ``` The current URL with "?Some%20data" appended is sent to the server (if no action is taken by the server, the current document is reloaded with the modified search string). ### Example 6: Using bookmarks without changing the `hash` property ```html <!doctype html> <html lang="en-US"> <head> <meta charset="UTF-8" /> <title>MDN Example</title> <script> function showNode(node) { document.documentElement.scrollTop = node.offsetTop; document.documentElement.scrollLeft = node.offsetLeft; } function showBookmark(bookmark, useHash) { if (arguments.length === 1 || useHash) { location.hash = bookmark; return; } const bookmarkElement = document.querySelector(bookmark); if (bookmarkElement) { showNode(bookmarkElement); } } </script> <style> span.intLink { cursor: pointer; color: #0000ff; text-decoration: underline; } </style> </head> <body> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ultrices dolor ac dolor imperdiet ullamcorper. Suspendisse quam libero, luctus auctor mollis sed, malesuada condimentum magna. Quisque in ante tellus, in placerat est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec a mi magna, quis mattis dolor. Etiam sit amet ligula quis urna auctor imperdiet nec faucibus ante. Mauris vel consectetur dolor. Nunc eget elit eget velit pulvinar fringilla consectetur aliquam purus. Curabitur convallis, justo posuere porta egestas, velit erat ornare tortor, non viverra justo diam eget arcu. Phasellus adipiscing fermentum nibh ac commodo. Nam turpis nunc, suscipit a hendrerit vitae, volutpat non ipsum. </p> <p> Duis lobortis sapien quis nisl luctus porttitor. In tempor semper libero, eu tincidunt dolor eleifend sit amet. Ut nec velit in dolor tincidunt rhoncus non non diam. Morbi auctor ornare orci, non euismod felis gravida nec. Curabitur elementum nisi a eros rutrum nec blandit diam placerat. Aenean tincidunt risus ut nisi consectetur cursus. Ut vitae quam elit. Donec dignissim est in quam tempor consequat. Aliquam aliquam diam non felis convallis suscipit. Nulla facilisi. Donec lacus risus, dignissim et fringilla et, egestas vel eros. Duis malesuada accumsan dui, at fringilla mauris bibendum quis. Cras adipiscing ultricies fermentum. Praesent bibendum condimentum feugiat. </p> <p id="myBookmark1"> [&nbsp;<span class="intLink" onclick="showBookmark('#myBookmark2');" >Go to bookmark #2</span >&nbsp;] </p> <p> Vivamus blandit massa ut metus mattis in fringilla lectus imperdiet. Proin ac ante a felis ornare vehicula. Fusce pellentesque lacus vitae eros convallis ut mollis magna pellentesque. Pellentesque placerat enim at lacus ultricies vitae facilisis nisi fringilla. In tincidunt tincidunt tincidunt. Nulla vitae tempor nisl. Etiam congue, elit vitae egestas mollis, ipsum nisi malesuada turpis, a volutpat arcu arcu id risus. </p> <p> Nam faucibus, ligula eu fringilla pulvinar, lectus tellus iaculis nunc, vitae scelerisque metus leo non metus. Proin mattis lobortis lobortis. Quisque accumsan faucibus erat, vel varius tortor ultricies ac. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec libero nunc. Nullam tortor nunc, elementum a consectetur et, ultrices eu orci. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a nisl eu sem vehicula egestas. </p> <p> Aenean viverra varius mauris, sed elementum lacus interdum non. Phasellus sit amet lectus vitae eros egestas pellentesque fermentum eget magna. Quisque mauris nisl, gravida vitae placerat et, condimentum id metus. Nulla eu est dictum dolor pulvinar volutpat. Pellentesque vitae sollicitudin nunc. Donec neque magna, lobortis id egestas nec, sodales quis lectus. Fusce cursus sollicitudin porta. Suspendisse ut tortor in mauris tincidunt rhoncus. Maecenas tincidunt fermentum facilisis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. </p> <p> Suspendisse turpis nisl, consectetur in lacinia ut, ornare vel mi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin non lectus eu turpis vulputate cursus. Mauris interdum tincidunt erat id pharetra. Nullam in libero elit, sed consequat lectus. Morbi odio nisi, porta vitae molestie ut, gravida ut nunc. Ut non est dui, id ullamcorper orci. Praesent vel elementum felis. Maecenas ornare, dui quis auctor hendrerit, turpis sem ullamcorper odio, in auctor magna metus quis leo. Morbi at odio ante. </p> <p> Curabitur est ipsum, porta ac viverra faucibus, eleifend sed eros. In sit amet vehicula tortor. Vestibulum viverra pellentesque erat a elementum. Integer commodo ultricies lorem, eget tincidunt risus viverra et. In enim turpis, porttitor ac ornare et, suscipit sit amet nisl. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Pellentesque vel ultrices nibh. Sed commodo aliquam aliquam. Nulla euismod, odio ut eleifend mollis, nisi dui gravida nibh, vitae laoreet turpis purus id ipsum. Donec convallis, velit non scelerisque bibendum, diam nulla auctor nunc, vel dictum risus ipsum sit amet est. Praesent ut nibh sit amet nibh congue pulvinar. Suspendisse dictum porttitor tempor. </p> <p> Vestibulum dignissim erat vitae lectus auctor ac bibendum eros semper. Integer aliquet, leo non ornare faucibus, risus arcu tristique dolor, a aliquet massa mauris quis arcu. In porttitor, lectus ac semper egestas, ligula magna laoreet libero, eu commodo mauris odio id ante. In hac habitasse platea dictumst. In pretium erat diam, nec consequat eros. Praesent augue mi, consequat sed porttitor at, volutpat vitae eros. Sed pretium pharetra dapibus. Donec auctor interdum erat, lacinia molestie nibh commodo ut. Maecenas vestibulum vulputate felis, ut ullamcorper arcu faucibus in. Curabitur id arcu est. In semper mollis lorem at pellentesque. Sed lectus nisl, vestibulum id scelerisque eu, feugiat et tortor. Pellentesque porttitor facilisis ultricies. </p> <p id="myBookmark2"> [&nbsp;<span class="intLink" onclick="showBookmark('#myBookmark1');" >Go to bookmark #1</span > | <span class="intLink" onclick="showBookmark('#myBookmark1', false);" >Go to bookmark #1 without using location.hash</span > | <span class="intLink" onclick="showBookmark('#myBookmark3');" >Go to bookmark #3</span >&nbsp;] </p> <p> Phasellus tempus fringilla nunc, eget sagittis orci molestie vel. Nulla sollicitudin diam non quam iaculis ac porta justo venenatis. Quisque tellus urna, molestie vitae egestas sit amet, suscipit sed sem. Quisque nec lorem eu velit faucibus tristique ut ut dolor. Cras eu tortor ut libero placerat venenatis ut ut massa. Sed quis libero augue, et consequat libero. Morbi rutrum augue sed turpis elementum sed luctus nisl molestie. Aenean vitae purus risus, a semper nisl. Pellentesque malesuada, est id sagittis consequat, libero mauris tincidunt tellus, eu sagittis arcu purus rutrum eros. Quisque eget eleifend mi. Duis pharetra mi ac eros mattis lacinia rutrum ipsum varius. </p> <p> Fusce cursus pulvinar aliquam. Duis justo enim, ornare vitae elementum sed, porta a quam. Aliquam eu enim eu libero mollis tempus. Morbi ornare aliquam posuere. Proin faucibus luctus libero, sed ultrices lorem sagittis et. Vestibulum malesuada, ante nec molestie vehicula, quam diam mollis ipsum, rhoncus posuere mauris lectus in eros. Nullam feugiat ultrices augue, ac sodales sem mollis in. </p> <p id="myBookmark3"><em>Here is the bookmark #3</em></p> <p> Proin vitae sem non lorem pellentesque molestie. Nam tempus massa et turpis placerat sit amet sollicitudin orci sodales. Pellentesque enim enim, sagittis a lobortis ut, tempus sed arcu. Aliquam augue turpis, varius vel bibendum ut, aliquam at diam. Nam lobortis, dui eu hendrerit pellentesque, sem neque porttitor erat, non dapibus velit lectus in metus. Vestibulum sit amet felis enim. In quis est vitae nunc malesuada consequat nec nec sapien. Suspendisse aliquam massa placerat dui lacinia luctus sed vitae risus. Fusce tempus, neque id ultrices volutpat, mi urna auctor arcu, viverra semper libero sem vel enim. Mauris dictum, elit non placerat malesuada, libero elit euismod nibh, nec posuere massa arcu eu risus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer urna velit, dapibus eget varius feugiat, pellentesque sit amet ligula. Maecenas nulla nisl, facilisis eu egestas scelerisque, mollis eget metus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi sed congue mi. </p> <p> Fusce metus velit, pharetra at vestibulum nec, facilisis porttitor mi. Curabitur ligula sapien, fermentum vel porttitor id, rutrum sit amet magna. Sed sit amet sollicitudin turpis. Aenean luctus rhoncus dolor, et pulvinar ante egestas et. Donec ac massa orci, quis dapibus augue. Vivamus consectetur auctor pellentesque. Praesent vestibulum tincidunt ante sed consectetur. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Fusce purus metus, imperdiet vitae iaculis convallis, bibendum vitae turpis. </p> <p> Fusce aliquet molestie dolor, in ornare dui sodales nec. In molestie sollicitudin felis a porta. Mauris nec orci sit amet orci blandit tristique congue nec nunc. Praesent et tellus sollicitudin mauris accumsan fringilla. Morbi sodales, justo eu sollicitudin lacinia, lectus sapien ullamcorper eros, quis molestie urna elit bibendum risus. Proin eget tincidunt quam. Nam luctus commodo mauris, eu posuere nunc luctus non. Nulla facilisi. Vivamus eget leo rhoncus quam accumsan fringilla. Aliquam sit amet lorem est. Nullam vel tellus nibh, id imperdiet orci. Integer egestas leo eu turpis blandit scelerisque. </p> <p> Etiam in blandit tellus. Integer sed varius quam. Vestibulum dapibus mi gravida arcu viverra blandit. Praesent tristique augue id sem adipiscing pellentesque. Sed sollicitudin, leo sed interdum elementum, nisi ante condimentum leo, eget ornare libero diam semper quam. Vivamus augue urna, porta eget ultrices et, dapibus ut ligula. Ut laoreet consequat faucibus. Praesent at lectus ut lectus malesuada mollis. Nam interdum adipiscing eros, nec sodales mi porta nec. Proin et quam vitae sem interdum aliquet. Proin vel odio at lacus vehicula aliquet. </p> <p> Etiam placerat dui ut sem ornare vel vestibulum augue mattis. Sed semper malesuada mi, eu bibendum lacus lobortis nec. Etiam fringilla elementum risus, eget consequat urna laoreet nec. Etiam mollis quam non sem convallis vel consectetur lectus ullamcorper. Aenean mattis lacus quis ligula mattis eget vestibulum diam hendrerit. In non placerat mauris. Praesent faucibus nunc quis eros sagittis viverra. In hac habitasse platea dictumst. Suspendisse eget nisl erat, ac molestie massa. Praesent mollis vestibulum tincidunt. Fusce suscipit laoreet malesuada. Aliquam erat volutpat. Aliquam dictum elementum rhoncus. Praesent in est massa, pulvinar sodales nunc. Pellentesque gravida euismod mi ac convallis. </p> <p> Mauris vel odio vel nulla facilisis lacinia. Aliquam ultrices est at leo blandit tincidunt. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse porttitor adipiscing facilisis. Duis cursus quam iaculis augue interdum porttitor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Duis vulputate magna ac metus pretium condimentum. In tempus, est eget vestibulum blandit, velit massa dignissim nisl, ut scelerisque lorem neque vel velit. Maecenas fermentum commodo viverra. Curabitur a nibh non velit aliquam cursus. Integer semper condimentum tortor a pellentesque. Pellentesque semper, nisl id porttitor vehicula, sem dui feugiat lacus, vitae consequat augue urna vel odio. </p> <p> Vestibulum id neque nec turpis iaculis pulvinar et a massa. Vestibulum sed nibh vitae arcu eleifend egestas. Mauris fermentum ultrices blandit. Suspendisse vitae lorem libero. Aenean et pellentesque tellus. Morbi quis neque orci, eu dignissim dui. Fusce sollicitudin mauris ac arcu vestibulum imperdiet. Proin ultricies nisl sit amet enim imperdiet eu ornare dui tempus. Maecenas lobortis nisi a tortor vestibulum vel eleifend tellus vestibulum. Donec metus sapien, hendrerit a fermentum id, dictum quis libero. </p> <p> Pellentesque a lorem nulla, in tempor justo. Duis odio nisl, dignissim sed consequat sit amet, hendrerit ac neque. Nunc ac augue nec massa tempor rhoncus. Nam feugiat, tellus a varius euismod, justo nisl faucibus velit, ut vulputate justo massa eu nibh. Sed bibendum urna quis magna facilisis in accumsan dolor malesuada. Morbi sit amet nunc risus, in faucibus sem. Nullam sollicitudin magna sed sem mollis id commodo libero condimentum. Duis eu massa et lacus semper molestie ut adipiscing sem. </p> <p> Sed id nulla mi, eget suscipit eros. Aliquam tempus molestie rutrum. In quis varius elit. Nullam dignissim neque nec velit vulputate porttitor. Mauris ac ligula sit amet elit fermentum rhoncus. In tellus urna, pulvinar quis condimentum ut, porta nec justo. In hac habitasse platea dictumst. Proin volutpat elit id quam molestie ac commodo lacus sagittis. Quisque placerat, augue tempor placerat pulvinar, nisi nisi venenatis urna, eget convallis eros velit quis magna. Suspendisse volutpat iaculis quam, ut tristique lacus luctus quis. </p> <p> Nullam commodo suscipit lacus non aliquet. Phasellus ac nisl lorem, sed facilisis ligula. Nam cursus lobortis placerat. Sed dui nisi, elementum eu sodales ac, placerat sit amet mauris. Pellentesque dapibus tellus ut ipsum aliquam eu auctor dui vehicula. Quisque ultrices laoreet erat, at ultrices tortor sodales non. Sed venenatis luctus magna, ultricies ultricies nunc fringilla eget. Praesent scelerisque urna vitae nibh tristique varius consequat neque luctus. Integer ornare, erat a porta tempus, velit justo fermentum elit, a fermentum metus nisi eu ipsum. Vivamus eget augue vel dui viverra adipiscing congue ut massa. Praesent vitae eros erat, pulvinar laoreet magna. Maecenas vestibulum mollis nunc in posuere. Pellentesque sit amet metus a turpis lobortis tempor eu vel tortor. Cras sodales eleifend interdum. </p> </body> </html> ``` …the same thing but with an animated page scroll: ```js const showBookmark = (() => { let _useHash; let _scrollX; let _scrollY; let _nodeX; let _nodeY; let _itFrame; let _scrollId = -1; let _bookMark; // duration: the duration in milliseconds of each frame // frames: number of frames for each scroll let duration = 200; let frames = 10; function _next() { if (_itFrame > frames) { clearInterval(_scrollId); _scrollId = -1; return; } _isBot = true; document.documentElement.scrollTop = Math.round( _scrollY + ((_nodeY - _scrollY) * _itFrame) / frames, ); document.documentElement.scrollLeft = Math.round( _scrollX + ((_nodeX - _scrollX) * _itFrame) / frames, ); if (_useHash && _itFrame === frames) { location.hash = _bookMark; } _itFrame++; } function _chkOwner() { if (_isBot) { _isBot = false; return; } if (_scrollId > -1) { clearInterval(_scrollId); _scrollId = -1; } } window.addEventListener("scroll", _chkOwner, false); return (bookmark, useHash) => { const node = document.querySelector(bookmark); _scrollY = document.documentElement.scrollTop; _scrollX = document.documentElement.scrollLeft; _bookMark = bookmark; _useHash = useHash === true; _nodeX = node.offsetLeft; _nodeY = node.offsetTop; _itFrame = 1; if (_scrollId === -1) { _scrollId = setInterval(_next, Math.round(duration / frames)); } }; })(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface of the returned value, {{domxref("Location")}} - A similar information, but attached to the document, {{domxref("Document.location")}} - [Manipulating the browser history](/en-US/docs/Web/API/History_API) - {{domxref("Window/hashchange_event", "hashchange")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/innerheight/index.md
--- title: "Window: innerHeight property" short-title: innerHeight slug: Web/API/Window/innerHeight page-type: web-api-instance-property browser-compat: api.Window.innerHeight --- {{APIRef}} The read-only **`innerHeight`** property of the {{domxref("Window")}} interface returns the interior height of the window in pixels, including the height of the horizontal scroll bar, if present. The value of `innerHeight` is taken from the height of the window's {{Glossary("layout viewport")}}. The width can be obtained using the {{domxref("Window.innerWidth", "innerWidth")}} property. ## Value An integer value indicating the window's layout viewport height in pixels. The property is read only and has no default value. To change the width of the window, call one of its resize methods, such as {{domxref("Window.resizeTo", "resizeTo()")}} or {{domxref("Window.resizeBy", "resizeBy()")}}. ## Usage notes To obtain the height of the window minus its horizontal scroll bar and any borders, use the root {{HTMLElement("html")}} element's {{domxref("Element.clientHeight", "clientHeight")}} property instead. Both `innerHeight` and `innerWidth` are available on any window or any object that behaves like a window, such as a tab or frame. ## Examples ### Assuming a frameset ```js console.log(window.innerHeight); // or console.log(self.innerHeight); // will log the height of the frame viewport within the frameset console.log(parent.innerHeight); // will log the height of the viewport of the closest frameset console.log(top.innerHeight); // will log the height of the viewport of the outermost frameset ``` To change the size of a window, see {{domxref("window.resizeBy()")}} and {{domxref("window.resizeTo()")}}. To get the outer height of a window, i.e. the height of the whole browser window, see {{domxref("window.outerHeight")}}. ### Graphical example The following figure shows the difference between `outerHeight` and `innerHeight`. ![innerHeight vs. outerHeight illustration](firefoxinnervsouterheight2.png) ## Demo ### HTML ```html <p>Resize the browser window to fire the <code>resize</code> event.</p> <p>Window height: <span id="height"></span></p> <p>Window width: <span id="width"></span></p> ``` ### JavaScript ```js const heightOutput = document.querySelector("#height"); const widthOutput = document.querySelector("#width"); function updateSize() { heightOutput.textContent = window.innerHeight; widthOutput.textContent = window.innerWidth; } updateSize(); window.addEventListener("resize", updateSize); ``` ### Result {{EmbedLiveSample('Demo')}} You can also {{LiveSampleLink('Demo', 'view the results of the demo code in a separate page')}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("window.innerWidth")}} - {{domxref("window.outerHeight")}} - {{domxref("window.outerWidth")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/forward/index.md
--- title: "Window: forward() method" short-title: forward() slug: Web/API/Window/forward page-type: web-api-instance-method status: - deprecated - non-standard --- {{APIRef}}{{Non-standard_header}} {{deprecated_header}} Moves the window one document forward in history. This was a Firefox-specific method and was removed in Firefox 31. > **Note:** Use the standard {{domxref("History.forward", "history.forward()")}} method instead. ## Syntax ```js-nolint forward() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js function goForward() { if (canGoForward) { window.forward(); } } ``` ## Specifications This is not part of any specification. ## Browser compatibility This non-standard method was only implemented in Firefox, and was removed in Firefox 31. ## See also - {{domxref("History.back()")}} - {{domxref("History.forward()")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/screenleft/index.md
--- title: "Window: screenLeft property" short-title: screenLeft slug: Web/API/Window/screenLeft page-type: web-api-instance-property browser-compat: api.Window.screenLeft --- {{APIRef}} The **`Window.screenLeft`** read-only property returns the horizontal distance, in CSS pixels, from the left border of the user's browser viewport to the left side of the screen. > **Note:** `screenLeft` is an alias of the older > {{domxref("Window.screenX")}} property. `screenLeft` was originally > supported only in IE but was introduced everywhere due to popularity. ## Value A number equal to the number of CSS pixels from the left edge of the browser viewport to the left edge of the screen. ## Examples In our [screenleft-screentop](https://mdn.github.io/dom-examples/screenleft-screentop/) example, you'll see a canvas onto which has been drawn a circle. In this example we are using `screenLeft`/`screenTop` plus {{domxref("Window.requestAnimationFrame()")}} to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ```js initialLeft = window.screenLeft + canvasElem.offsetLeft; initialTop = window.screenTop + canvasElem.offsetTop; function positionElem() { let newLeft = window.screenLeft + canvasElem.offsetLeft; let newTop = window.screenTop + canvasElem.offsetTop; let leftUpdate = initialLeft - newLeft; let topUpdate = initialTop - newTop; ctx.fillStyle = "rgb(0 0 0)"; ctx.fillRect(0, 0, width, height); ctx.fillStyle = "rgb(0 0 255)"; ctx.beginPath(); ctx.arc( leftUpdate + width / 2, topUpdate + height / 2 + 35, 50, degToRad(0), degToRad(360), false, ); ctx.fill(); pElem.textContent = `Window.screenLeft: ${window.screenLeft}, Window.screenTop: ${window.screenTop}`; window.requestAnimationFrame(positionElem); } window.requestAnimationFrame(positionElem); ``` Also in the code we include a snippet that detects whether `screenLeft` is supported, and if not, polyfills in `screenLeft`/`screenTop` using {{domxref("Window.screenX")}}/{{domxref("Window.screenY")}}. ```js if (!window.screenLeft) { window.screenLeft = window.screenX; window.screenTop = window.screenY; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("window.screenTop")}} - {{domxref("Window.screenX")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/cancelidlecallback/index.md
--- title: "Window: cancelIdleCallback() method" short-title: cancelIdleCallback() slug: Web/API/Window/cancelIdleCallback page-type: web-api-instance-method browser-compat: api.Window.cancelIdleCallback --- {{APIRef}} The **`window.cancelIdleCallback()`** method cancels a callback previously scheduled with {{domxref("window.requestIdleCallback()")}}. ## Syntax ```js-nolint cancelIdleCallback(handle) ``` ### Parameters - `handle` - : The ID value returned by {{domxref("window.requestIdleCallback()")}} when the callback was established. ### Return value None ({{jsxref("undefined")}}). ## Examples See our [complete example](/en-US/docs/Web/API/Background_Tasks_API#example) in the article [Cooperative Scheduling of Background Tasks API](/en-US/docs/Web/API/Background_Tasks_API). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/scroll/index.md
--- title: "Window: scroll() method" short-title: scroll() slug: Web/API/Window/scroll page-type: web-api-instance-method browser-compat: api.Window.scroll --- {{APIRef}} The **`Window.scroll()`** method scrolls the window to a particular place in the document. ## Syntax ```js-nolint scroll(x-coord, y-coord) scroll(options) ``` ### Parameters - `x-coord` is the pixel along the horizontal axis of the document that you want displayed in the upper left. - `y-coord` is the pixel along the vertical axis of the document that you want displayed in the upper left. \- or - - `options` - : A dictionary containing the following parameters: - `top` - : Specifies the number of pixels along the Y axis to scroll the window or element. - `left` - : Specifies the number of pixels along the X axis to scroll the window or element. - `behavior` - : Determines whether scrolling is instant or animates smoothly. This option is a string which must take one of the following values: - `smooth`: scrolling should animate smoothly - `instant`: scrolling should happen instantly in a single jump - `auto`: scroll behavior is determined by the computed value of {{cssxref("scroll-behavior")}} ### Return value None ({{jsxref("undefined")}}). ## Examples ```html <!-- put the 100th vertical pixel at the top of the window --> <button onclick="scroll(0, 100);">click to scroll to the 100th pixel</button> ``` Using `options`: ```js window.scroll({ top: 100, left: 100, behavior: "smooth", }); ``` ## Notes {{domxref("Window.scrollTo()")}} is effectively the same as this method. For relative scrolling, see {{domxref("Window.scrollBy()")}}, {{domxref("Window.scrollByLines()")}}, and {{domxref("Window.scrollByPages()")}}. For scrolling elements, see {{domxref("Element.scrollTop")}} and {{domxref("Element.scrollLeft")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Window.scrollByLines()")}} - {{domxref("Window.scrollByPages()")}} - {{domxref("Element.scrollIntoView()")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/locationbar/index.md
--- title: "Window: locationbar property" short-title: locationbar slug: Web/API/Window/locationbar page-type: web-api-instance-property browser-compat: api.Window.locationbar --- {{APIRef}} Returns the `locationbar` object. This is one of a group of `Window` properties that contain a boolean `visible` property, that used to represent whether or not a particular part of a web browser's user interface was visible. For privacy and interoperability reasons, the value of the `visible` property is now `false` if this `Window` is a popup, and `true` otherwise. ## Value An object containing a single property: - `visible` {{ReadOnlyInline}} - : A boolean property, `false` if this `Window` is a popup, and `true` otherwise. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("window.menubar")}} - {{domxref("window.personalbar")}} - {{domxref("window.scrollbars")}} - {{domxref("window.statusbar")}} - {{domxref("window.toolbar")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/paste_event/index.md
--- title: "Window: paste event" short-title: paste slug: Web/API/Window/paste_event page-type: web-api-event browser-compat: api.Element.paste_event --- {{APIRef}} The **`paste`** event is fired when the user has initiated a "paste" action through the browser's user interface. The original target for this event is the {{domxref("Element")}} that was the intended target of the paste action. You can listen for this event on the {{domxref("Window")}} interface to handle it in the capture or bubbling phases. For full details on this event please see the page on the [Element: paste event](/en-US/docs/Web/API/Element/paste_event). ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("paste", (event) => {}); onpaste = (event) => {}; ``` ## Event type A {{domxref("ClipboardEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("ClipboardEvent")}} ## Examples ```js window.addEventListener("paste", (event) => { console.log("paste action initiated"); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: {{domxref("Window/cut_event", "cut")}}, {{domxref("Window/copy_event", "copy")}} - This event on {{domxref("Element")}} targets: {{domxref("Element/paste_event", "paste")}} - This event on {{domxref("Document")}} targets: {{domxref("Document/paste_event", "paste")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/webkitconvertpointfrompagetonode/index.md
--- title: "Window: webkitConvertPointFromPageToNode() method" short-title: webkitConvertPointFromPageToNode() slug: Web/API/Window/webkitConvertPointFromPageToNode page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.Window.webkitConvertPointFromPageToNode --- {{APIRef}}{{Deprecated_Header}}{{Non-standard_header}} Given a {{domxref("WebKitPoint")}} specified in the page's coordinate system, the {{domxref("Window")}} method **`webkitConvertPointFromPageToNode()`** returns a `Point` object specifying the same location in the coordinate system of the specified DOM {{domxref("Node")}}. > **Warning:** Please review the [Browser compatibility](#browser_compatibility) section before using this method, > as it's not widely supported (nor is the {{domxref("WebKitPoint")}} object it uses). ## Syntax ```js-nolint convertPointFromPageToNode(node, pagePoint) ``` ### Parameters - `node` - : The {{domxref("Node")}} into whose coordinate system the point is to be converted. - `pagePoint` - : A {{domxref("WebKitPoint")}} object specifying a point in the coordinate system of the page, which is to be converted into the node's coordinate system. ### Return value A `Point` object describing the specified location in the node's coordinate system. ## Specifications This method 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 the current CSS Transforms Module Level 1 Working Draft. ## Browser compatibility {{Compat}} ## See also - {{domxref("Window.webkitConvertPointFromNodeToPage")}} - Mozilla implementation bug: [Firefox bug 850808](https://bugzil.la/850808) - [`webkitConvertPointFromPageToNode` documentation at IE Dev Center](<https://msdn.microsoft.com/library/ie/dn760735(v=vs.85).aspx>)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/opener/index.md
--- title: "Window: opener property" short-title: opener slug: Web/API/Window/opener page-type: web-api-instance-property browser-compat: api.Window.opener --- {{APIRef("HTML DOM")}} The {{domxref("Window")}} interface's **`opener`** property returns a reference to the window that opened the window, either with {{domxref("Window.open", "open()")}}, or by navigating a link with a [`target`](/en-US/docs/Web/HTML/Element/a#target) attribute. In other words, if window `A` opens window `B`, `B.opener` returns `A`. ## Value A {{domxref("Window")}}-like object referring to the window that opened the current window (using {{domxref("window.open()")}}, or by a link with [`target`](/en-US/docs/Web/HTML/Element/a#target) attribute set). If this window was not opened by being linked to or created by another, returns [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null). If the opener is not on the same origin as the current page, functionality of the opener object is limited. For example, variables and functions on the window object are not accessible. However, navigation of the opener window is possible, which means that the opened page can open a URL in the original tab or window. In some cases, this makes phishing attacks possible, where a trusted page that is opened in the original window is replaced by a phishing page by the newly opened page. In the following cases, the browser does not populate `window.opener`, but leaves it [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null): - The opener can be omitted by specifying [`rel=noopener`](/en-US/docs/Web/HTML/Attributes/rel#noopener) on a link, or passing `noopener` in the {{domxref("Window.open", "windowFeatures")}} parameter. - Windows opened because of links with a [`target`](/en-US/docs/Web/HTML/Element/a#target) of `_blank` don't get an `opener`, unless explicitly requested with [`rel=opener`](/en-US/docs/Web/HTML/Attributes/rel#opener). - Having a {{HTTPHeader("Cross-Origin-Opener-Policy")}} header with a value of `same-origin` prevents setting `opener`. Since the new window is loaded in a different browsing context, it won't have a reference to the opening window. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/window/index.md
--- title: "Window: window property" short-title: window slug: Web/API/Window/window page-type: web-api-instance-property browser-compat: api.Window.window --- {{APIRef}} The **`window`** property of a {{domxref("Window")}} object points to the window object itself. Thus, the following expressions all return the same window object: ```js window.window; window.window.window; window.window.window.window; // … ``` In web pages, the window object is also a _global object_. This means: 1. Global variables of your script are, in fact, properties of `window`: ```js var global = { data: 0 }; alert(global === window.global); // displays "true" ``` 2. You can access the built-in properties of the window object without having to prefix them with `window.`: ```js setTimeout("alert('Hi!')", 50); // equivalent to using window.setTimeout(). alert(window === window.window); // displays "true" ``` The point of having the `window` property refer to the object itself, was likely to make it easy to refer to the global object. Otherwise, you'd have to do a manual `let window = this;` assignment at the top of your script. Another reason, is that without this property you wouldn't be able to write, for example, "{{domxref("window.open","window.open('https://google.com/')")}}". You'd have to use `open('https://google.com/')` instead. Yet another reason to use this property, is for libraries which wish to offer OOP-versions, and non-OOP versions (especially JavaScript modules). For example, if we refer to "this.window\.location.href", a [JavaScript module](/en-US/docs/Web/JavaScript/Guide/Modules) could define a property called "window" inside of a class it defined (since no global "window" variable exists for it by default) which could be created after passing in a window object to the module class' constructor. Thus, "this.window" inside of its functions would refer to that window object. In the non-namespaced version, "this.window" would refer back to "window", and also be able to readily get the document location. Another advantage, is that the objects of such a class (even if the class were defined outside of a module) could change their reference to the window at will, they would not be able to do this if they had hard-coded a reference to "window". The default in the class could still be set as the current window object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/navigation/index.md
--- title: "Window: navigation property" short-title: navigation slug: Web/API/Window/navigation page-type: web-api-instance-property status: - experimental browser-compat: api.Window.navigation --- {{APIRef("Navigation API")}}{{SeeCompatTable}} The **`navigation`** read-only property of the {{domxref("Window")}} interface returns the current `window`'s associated {{domxref("Navigation")}} object. This is the entry point for the {{domxref("Navigation API", "", "", "nocode")}}. ## Value A {{domxref("Navigation")}} object instance. ## Examples ```js let currentNavEntries = window.navigation.entries(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## 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/)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/history/index.md
--- title: "Window: history property" short-title: history slug: Web/API/Window/history page-type: web-api-instance-property browser-compat: api.Window.history --- {{APIRef}} The `Window.history` read-only property returns a reference to the {{domxref("History")}} object, which provides an interface for manipulating the browser _session history_ (pages visited in the tab or frame that the current page is loaded in). See [Manipulating the browser history](/en-US/docs/Web/API/History_API) for examples and details. In particular, that article explains security features of the {{domxref("History.pushState", "pushState()")}} and {{domxref("History.replaceState", "replaceState()")}} methods that you should be aware of before using them. ## Value A reference to the {{domxref("History")}} object. ## Examples ```js history.back(); // equivalent to clicking back button history.go(-1); // equivalent to history.back(); ``` ## Notes For top-level pages you can see the list of pages in the session history, accessible via the `History` object, in the browser's dropdowns next to the back and forward buttons. For security reasons the `History` object doesn't allow the non-privileged code to access the {{glossary("URL", "URLs")}} of other pages in the session history, but it does allow it to navigate the session history. There is no way to clear the session history or to disable the back/forward navigation from unprivileged code. The closest available solution is the {{domxref("Location.replace", "location.replace()")}} method, which replaces the current item of the session history with the provided URL. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/pagehide_event/index.md
--- title: "Window: pagehide event" short-title: pagehide slug: Web/API/Window/pagehide_event page-type: web-api-event browser-compat: api.Window.pagehide_event --- {{APIRef("HTML DOM")}} The **`pagehide`** event is sent to a {{domxref("Window")}} when the browser hides the current page in the process of presenting a different page from the session's history. For example, when the user clicks the browser's Back button, the current page receives a `pagehide` event before the previous page is shown. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("pagehide", (event) => {}); onpagehide = (event) => {}; ``` ## Event type A {{domxref("PageTransitionEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("PageTransitionEvent")}} ## Event properties - {{domxref("PageTransitionEvent.persisted")}} {{ReadOnlyInline}} - : Indicates if the document is loading from a cache. ## Event handler aliases In addition to the `Window` interface, the event handler property `onpagehide` is also available on the following targets: - {{domxref("HTMLBodyElement")}} - {{domxref("HTMLFrameSetElement")}} - {{domxref("SVGSVGElement")}} ## Usage notes Like the [`unload`](/en-US/docs/Web/API/Window/unload_event) and [`beforeunload`](/en-US/docs/Web/API/Window/beforeunload_event) events, this event is not reliably fired by browsers, especially on mobile. For example, the `pagehide` event is not fired at all in the following scenario: 1. A mobile user visits your page. 2. The user then switches to a different app. 3. Later, the user closes the browser from the app manager. However, unlike the `unload` and `beforeunload` events, this event is compatible with the [back/forward cache](https://web.dev/articles/bfcache) (bfcache), so adding a listener to this event will not prevent the page from being included in the bfcache. The best event to use to signal the end of a user's session is the [`visibilitychange`](/en-US/docs/Web/API/Document/visibilitychange_event) event. In browsers that don't support `visibilitychange` the `pagehide` event is the next-best alternative. If you're specifically trying to detect page unload events, the `pagehide` event is the best option. See the [Page Lifecycle API](https://developer.chrome.com/blog/page-lifecycle-api/) guide for more information about how this event relates to other events in the page lifecycle. ## Examples In this example, an event handler is established to watch for `pagehide` events and to perform special handling if the page is being persisted for possible reuse. ```js window.addEventListener( "pagehide", (event) => { if (event.persisted) { /* the page isn't being discarded, so it can be reused later */ } }, false, ); ``` This can also be written using the `onpagehide` event handler property on the {{domxref("Window")}}: ```js window.onpagehide = (event) => { if (event.persisted) { /* the page isn't being discarded, so it can be reused later */ } }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{domxref("Window.pageshow_event", "pageshow")}} event. - [Page Lifecycle API](https://developer.chrome.com/blog/page-lifecycle-api/#developer-recommendations-for-each-state) gives best-practices guidance on handling page lifecycle behavior in your web applications. - [PageLifecycle.js](https://github.com/GoogleChromeLabs/page-lifecycle): a JavaScript library that deals with cross-browser inconsistencies in page lifecycle behavior. - [Back/forward cache](https://web.dev/articles/bfcache) explains what the back/forward cache is, and its implications for various page lifecycle events.
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/showdirectorypicker/index.md
--- title: "Window: showDirectoryPicker() method" short-title: showDirectoryPicker() slug: Web/API/Window/showDirectoryPicker page-type: web-api-instance-method status: - experimental browser-compat: api.Window.showDirectoryPicker --- {{APIRef("File System API")}}{{Securecontext_Header}}{{SeeCompatTable}} The **`showDirectoryPicker()`** method of the {{domxref("Window")}} interface displays a directory picker which allows the user to select a directory. ## Syntax ```js-nolint showDirectoryPicker() ``` ### Parameters - `options` {{optional_inline}} - : An object containing options, which are as follows: - `id` {{optional_inline}} - : By specifying an ID, the browser can remember different directories for different IDs. If the same ID is used for another picker, the picker opens in the same directory. - `mode` {{optional_inline}} - : A string that defaults to `"read"` for read-only access or `"readwrite"` for read and write access to the directory. - `startIn` {{optional_inline}} - : A `FileSystemHandle` or a well known directory (`"desktop"`, `"documents"`, `"downloads"`, `"music"`, `"pictures"`, or `"videos"`) to open the dialog in. ### Return value A {{jsxref("Promise")}} whose fulfillment handler receives a {{domxref('FileSystemDirectoryHandle')}} object. ### Exceptions - `AbortError` {{domxref("DOMException")}} - : Thrown if the user dismisses the prompt without making a selection, or if the user agent deems the selected directory to be too sensitive or dangerous, or if the {{domxref('PermissionStatus.state')}} for the selected directory is not `"granted"` in the specified `mode`. - `SecurityError` {{domxref("DOMException")}} - : Thrown if the call was blocked by the [same-origin policy](/en-US/docs/Web/Security/Same-origin_policy) or it was not called via a user interaction such as a button press. ## Security [Transient user activation](/en-US/docs/Web/Security/User_activation) is required. The user has to interact with the page or a UI element in order for this feature to work. ## Examples This asynchronous function shows a directory picker and returns a {{domxref('FileSystemDirectoryHandle')}} once selected. ```js async function getDir() { const dirHandle = await window.showDirectoryPicker(); // run code for dirHandle } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [File System API](/en-US/docs/Web/API/File_System_API) - [The File System Access API: simplifying access to local files](https://developer.chrome.com/docs/capabilities/web-apis/file-system-access)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/webkitconvertpointfromnodetopage/index.md
--- title: "Window: webkitConvertPointFromNodeToPage() method" short-title: webkitConvertPointFromNodeToPage() slug: Web/API/Window/webkitConvertPointFromNodeToPage page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.Window.webkitConvertPointFromNodeToPage --- {{APIRef}}{{Non-standard_header}}{{Deprecated_Header}} Given a {{domxref("WebKitPoint")}} specified in a particular DOM {{domxref("Node")}}'s coordinate system, the {{domxref("Window")}} method **`webkitConvertPointFromNodeToPage()`** returns a `Point` which specifies the same position in the page's coordinate system. This method is non-standard and _should not be used_. > **Warning:** Please review the [Browser compatibility](#browser_compatibility) section before using this method, as it's not widely supported (nor is the {{domxref("WebKitPoint")}} object it uses). ## Syntax ```js-nolint webkitConvertPointFromNodeToPage(node, nodePoint) ``` ### Parameters - `node` - : The {{domxref("Node")}} in whose coordinate system the `Point` specified by `nodePoint` is described. - `nodePoint` - : A {{domxref("WebKitPoint")}} object describing a point in `node`'s coordinate system; this point will be converted to the page's coordinate system. ### Return value A {{domxref("WebKitPoint")}} object specifying a point in the page's coordinate system. ## Specifications This method 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 the current CSS Transforms Module Level 1 Working Draft. ## Browser compatibility {{Compat}} ## See also - {{domxref("Window.webkitConvertPointFromPageToNode")}} - Mozilla implementation bug: [Firefox bug 850806](https://bugzil.la/850806)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/showsavefilepicker/index.md
--- title: "Window: showSaveFilePicker() method" short-title: showSaveFilePicker() slug: Web/API/Window/showSaveFilePicker page-type: web-api-instance-method status: - experimental browser-compat: api.Window.showSaveFilePicker --- {{APIRef("File System API")}}{{SecureContext_Header}}{{SeeCompatTable}} The **`showSaveFilePicker()`** method of the {{domxref("Window")}} interface shows a file picker that allows a user to save a file. Either by selecting an existing file, or entering a name for a new file. ## Syntax ```js-nolint showSaveFilePicker() ``` ### Parameters - `options` {{Optional_Inline}} - : An object containing options, which are as follows: - `excludeAcceptAllOption` {{Optional_Inline}} - : A boolean value that defaults to `false`. By default, the picker should include an option to not apply any file type filters (instigated with the type option below). Setting this option to `true` means that option is _not_ available. - `id` {{Optional_Inline}} - : By specifying an ID, the browser can remember different directories for different IDs. If the same ID is used for another picker, the picker opens in the same directory. - `startIn` {{Optional_Inline}} - : A `FileSystemHandle` or a well known directory (`"desktop"`, `"documents"`, `"downloads"`, `"music"`, `"pictures"`, or `"videos"`) to open the dialog in. - `suggestedName` {{Optional_Inline}} - : A {{jsxref('String')}}. The suggested file name. - `types` {{Optional_Inline}} - : An {{jsxref('Array')}} of allowed file types to save. Each item is an object with the following options: - `description` {{Optional_Inline}} - : An optional description of the category of files types allowed. Default to be an empty string. - `accept` - : An {{jsxref('Object')}} with the keys set to the [MIME type](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types) and the values an {{jsxref('Array')}} of file extensions (see below for an example). ### Return value A {{jsxref("Promise")}} whose fulfillment handler receives a {{domxref('FileSystemFileHandle')}} object. ### Exceptions - `AbortError` {{domxref("DOMException")}} - : Thrown if the user dismisses the file picker without selecting or inputting a file, or if the user agent deems any selected files too sensitive or dangerous. - `SecurityError` {{domxref("DOMException")}} - : Thrown if the call was blocked by the [same-origin policy](/en-US/docs/Web/Security/Same-origin_policy) or it was not called via a user interaction such as a button press. - {{jsxref("TypeError")}} - : Thrown if accept types can't be processed, which may happen if: - Any key string of the `accept` options of any item in `types` options can't parse a valid MIME type. - Any value string(s) of the `accept` options of any item in `types` options is invalid, for example, if it does not start with `.` and if end with `.`, or if it contains any invalid code points and its length is more than 16. - The `types` options is empty and the `excludeAcceptAllOption` options is `true`. ## Security [Transient user activation](/en-US/docs/Web/Security/User_activation) is required. The user has to interact with the page or a UI element in order for this feature to work. ## Examples The following function shows a file picker, with text files highlighted for selection. ```js async function getNewFileHandle() { const opts = { types: [ { description: "Text file", accept: { "text/plain": [".txt"] }, }, ], }; return await window.showSaveFilePicker(opts); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [File System API](/en-US/docs/Web/API/File_System_API) - [The File System Access API: simplifying access to local files](https://developer.chrome.com/docs/capabilities/web-apis/file-system-access)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/resizeto/index.md
--- title: "Window: resizeTo() method" short-title: resizeTo() slug: Web/API/Window/resizeTo page-type: web-api-instance-method browser-compat: api.Window.resizeTo --- {{APIRef}} The **`Window.resizeTo()`** method dynamically resizes the window. ## Syntax ```js-nolint resizeTo(width, height) ``` ### Parameters - `width` - : An integer representing the new {{domxref("window.outerWidth","outerWidth")}} in pixels (including scroll bars, title bars, etc.). - `height` - : An integer value representing the new {{domxref("window.outerHeight","outerHeight")}} in pixels (including scroll bars, title bars, etc.). ### Return value None ({{jsxref("undefined")}}). ## Examples This function resizes the window so that it takes up one quarter of the available screen. See the {{domxref("Screen.availWidth")}} and {{domxref("Screen.availHeight")}} properties. ```js function quarter() { window.resizeTo(window.screen.availWidth / 2, window.screen.availHeight / 2); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} Note: It's not possible to resize a window or tab that wasn't created by **`window.open()`**. It's also not possible to resize when the window has multiple tabs. ## See also - {{domxref("window.resizeBy()")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/sharedstorage/index.md
--- title: "Window: sharedStorage property" short-title: sharedStorage slug: Web/API/Window/sharedStorage page-type: web-api-instance-property status: - experimental browser-compat: api.Window.sharedStorage --- {{APIRef("Shared Storage API")}}{{SeeCompatTable}}{{SecureContext_Header}} The global read-only **`sharedStorage`** property returns the {{domxref("WindowSharedStorage")}} object for the current origin. This is the main entry point for writing data to shared storage using the [Shared Storage API](/en-US/docs/Web/API/Shared_Storage_API). > **Note:** `sharedStorage` is not available inside workers. It is implemented by [`Window`](/en-US/docs/Web/API/Window#scheduler) and is also available in shared storage worklets (see {{domxref("SharedStorageWorkletGlobalScope.sharedStorage")}}, which returns {{domxref("WorkletSharedStorage")}}). ## Value A {{domxref("WindowSharedStorage")}} object instance. ## Examples ```js window.sharedStorage .set("ab-testing-group", "0") .then(console.log("Value saved to shared storage")); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("WindowSharedStorage")}} - [Shared Storage API](/en-US/docs/Web/API/Shared_Storage_API)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/confirm/index.md
--- title: "Window: confirm() method" short-title: confirm() slug: Web/API/Window/confirm page-type: web-api-instance-method browser-compat: api.Window.confirm --- {{ApiRef("Window")}} `window.confirm()` instructs the browser to display a dialog with an optional message, and to wait until the user either confirms or cancels the dialog. Under some conditions — for example, when the user switches tabs — the browser may not actually display a dialog, or may not wait for the user to confirm or cancel the dialog. ## Syntax ```js-nolint confirm(message) ``` ### Parameters - `message` - : A string you want to display in the confirmation dialog. ### Return value A boolean indicating whether OK (`true`) or Cancel (`false`) was selected. If a browser is ignoring in-page dialogs, then the returned value is always `false`. ## Examples ```js if (window.confirm("Do you really want to leave?")) { window.open("exit.html", "Thanks for Visiting!"); } ``` Produces: ![Firefox confirm](firefox_confirm_dialog.png) ## Notes Dialog boxes are modal windows — they prevent the user from accessing the rest of the program's interface until the dialog box is closed. For this reason, you should not overuse any function that creates a dialog box (or modal window). Regardless, there are good reasons to [avoid using dialog boxes for confirmation](https://alistapart.com/article/neveruseawarning/). Alternatively {{HTMLElement("dialog")}} element can be used for confirmations. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("dialog")}} element - {{domxref("window.alert()")}} - {{domxref("window.prompt()")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/close/index.md
--- title: "Window: close() method" short-title: close() slug: Web/API/Window/close page-type: web-api-instance-method browser-compat: api.Window.close --- {{APIRef}} The **`Window.close()`** method closes the current window, or the window on which it was called. This method can only be called on windows that were opened by a script using the {{domxref("Window.open()")}} method, or on top-level windows that have a single history entry. If the window doesn't match these requirements, an error similar to this one appears in the console: `Scripts may not close windows that were not opened by script.` Note also that `close()` has no effect when called on {{domxref("Window")}} objects returned by [`HTMLIFrameElement.contentWindow`](/en-US/docs/Web/API/HTMLIFrameElement/contentWindow). ## Syntax ```js-nolint close() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Closing a window opened with `window.open()` This example shows a method which opens a window and a second one which closes the window; this demonstrates how to use `Window.close()` to close a window opened by calling {{domxref("window.open()")}}. ```js //Global variable to store a reference to the opened window let openedWindow; function openWindow() { openedWindow = window.open("moreinfo.htm"); } function closeOpenedWindow() { openedWindow.close(); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/error_event/index.md
--- title: "Window: error event" short-title: error slug: Web/API/Window/error_event page-type: web-api-event browser-compat: api.Window.error_event --- {{APIRef}} The `error` event is fired on a {{domxref("Window")}} object when a resource failed to load or couldn't be used — for example if a script has an execution error. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("error", (event) => {}); onerror = (event, source, lineno, colno, error) => {}; ``` > **Note:** Due to historical reasons, `onerror` on `window` is the only event handler property that receives more than one argument. ## Event type The event object is a {{domxref("ErrorEvent")}} instance if it was generated from a user interface element, or an {{domxref("Event")}} instance otherwise. {{InheritanceDiagram("ErrorEvent")}} ## Usage notes ### Event handler property For historical reasons, the `onerror` event handler property, on `Window` objects only, has different behavior from other event handler properties. Note that this only applies to handlers assigned to `onerror`, not to handlers added using `addEventListener()`. #### Cancellation Most event handlers assigned to event handler properties can cancel the event's default behavior by returning `false` from the handler: ```js textarea.onkeydown = () => false; ``` However, for an event handler property to cancel the default behavior of the `error` event of `Window`, it must instead return `true`: ```js window.onerror = () => true; ``` When canceled, the error won't appear in the console, but the current script will still stop executing. #### Arguments The event handler's signature is asymmetric between `addEventListener()` and `onerror`. The event handler passed to `Window.addEventListener()` receives a single {{domxref("ErrorEvent")}} object, while the `onerror` handler receives five arguments, matching the {{domxref("ErrorEvent")}} object's properties: - `event` - : A string containing a human-readable error message describing the problem. Same as {{domxref("ErrorEvent.message")}}. - `source` - : A string containing the URL of the script that generated the error. - `lineno` - : An integer containing the line number of the script file on which the error occurred. - `colno` - : An integer containing the column number of the script file on which the error occurred. - `error` - : The error being thrown. Usually an {{jsxref("Error")}} object. ```js window.onerror = (a, b, c, d, e) => { console.log(`message: ${a}`); console.log(`source: ${b}`); console.log(`lineno: ${c}`); console.log(`colno: ${d}`); console.log(`error: ${e}`); return true; }; ``` > **Note:** These parameter names are observable with an [HTML event handler attribute](/en-US/docs/Web/HTML/Attributes#event_handler_attributes), where the first parameter is called `event` instead of `message`. This special behavior only happens for the `onerror` event handler on `window`. The [`Element.onerror`](/en-US/docs/Web/API/HTMLElement/error_event) handler still receives a single {{domxref("ErrorEvent")}} object. ## Examples ### Live example #### HTML ```html <div class="controls"> <button id="script-error" type="button">Generate script error</button> <img class="bad-img" /> </div> <div class="event-log"> <label for="eventLog">Event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="30" id="eventLog"></textarea> </div> ``` ```css hidden body { display: grid; grid-template-areas: "control log"; } .controls { grid-area: control; display: flex; align-items: center; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } button { height: 2rem; margin: 0.5rem; } img { width: 0; height: 0; } ``` #### JavaScript ```js const log = document.querySelector(".event-log-contents"); window.addEventListener("error", (event) => { log.textContent = `${log.textContent}${event.type}: ${event.message}\n`; console.log(event); }); const scriptError = document.querySelector("#script-error"); scriptError.addEventListener("click", () => { const badCode = "const s;"; eval(badCode); }); ``` #### Result {{ EmbedLiveSample('Live_example', '100%', '150px') }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - This event on `Element` targets: {{domxref("HTMLElement/error_event", "error")}} event
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/sizetocontent/index.md
--- title: "Window: sizeToContent() method" short-title: sizeToContent() slug: Web/API/Window/sizeToContent page-type: web-api-instance-method status: - non-standard browser-compat: api.Window.sizeToContent --- {{APIRef}}{{Non-standard_Header}} The **`Window.sizeToContent()`** method sizes the window according to its content. In order for it to work, the DOM content should be loaded when this function is called—for example, once the {{domxref("Document/DOMContentLoaded_event", "DOMContentLoaded")}} event has been thrown. Since Firefox 20, the minimal size of the window is clamped to prevent the window from being too small for the user to interact with. ## Syntax ```js-nolint sizeToContent() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js window.sizeToContent(); ``` ## Specifications This feature is not part of any specification. ## Browser compatibility {{Compat}} ## See also - {{domxref("Window")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/storage_event/index.md
--- title: "Window: storage event" short-title: storage slug: Web/API/Window/storage_event page-type: web-api-event browser-compat: api.Window.storage_event --- {{APIRef}} The **`storage`** event of the {{domxref("Window")}} interface fires when a storage area (`localStorage` or `sessionStorage`) has been modified in the context of another document. This event is not cancelable and does not bubble. > **Note:** This won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made. Pages on other domains can't access the same storage objects. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("storage", (event) => {}); onstorage = (event) => {}; ``` ## Event type A {{domxref("StorageEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("StorageEvent")}} ## Event properties - {{domxref("StorageEvent.key", "key")}} {{ReadOnlyInline}} - : Returns a string with the key for the storage item that was changed. The `key` attribute is `null` when the change is caused by the storage `clear()` method. - {{domxref("StorageEvent.newValue", "newValue")}} {{ReadOnlyInline}} - : Returns a string with the new value of the storage item that was changed. This value is `null` when the change has been invoked by storage `clear()` method, or the storage item has been removed from the storage. - {{domxref("StorageEvent.oldValue", "oldValue")}} {{ReadOnlyInline}} - : Returns a string with the original value of the storage item that was changed. This value is `null` when the storage item has been newly added and therefore doesn't have any previous value. - {{domxref("StorageEvent.storageArea", "storageArea")}} {{ReadOnlyInline}} - : Returns a {{DOMxRef("Storage")}} object that represents the storage object that was affected. - {{domxref("StorageEvent.url", "url")}} {{ReadOnlyInline}} - : Returns string with the URL of the document whose storage changed. ## Event handler aliases In addition to the `Window` interface, the event handler property `onstorage` is also available on the following targets: - {{domxref("HTMLBodyElement")}} - {{domxref("HTMLFrameSetElement")}} - {{domxref("SVGSVGElement")}} ## Examples Log the `sampleList` item to the console when the `storage` event fires: ```js window.addEventListener("storage", () => { // When local storage changes, dump the list to // the console. console.log(JSON.parse(window.localStorage.getItem("sampleList"))); }); ``` The same action can be achieved using the `onstorage` event handler property: ```js window.onstorage = () => { // When local storage changes, dump the list to // the console. console.log(JSON.parse(window.localStorage.getItem("sampleList"))); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Web Storage API", "", "", "nocode")}} - [Using the Web Storage API](/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API) - [Responding to storage changes with the StorageEvent](/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#responding_to_storage_changes_with_the_storageevent)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/hashchange_event/index.md
--- title: "Window: hashchange event" short-title: hashchange slug: Web/API/Window/hashchange_event page-type: web-api-event browser-compat: api.Window.hashchange_event --- {{APIRef}} The **`hashchange`** event is fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the `#` symbol). ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("hashchange", (event) => {}); onhashchange = (event) => {}; ``` ## Event type A {{domxref("HashChangeEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("HashChangeEvent")}} ## Event properties - {{domxref("HashChangeEvent.newURL")}} {{ReadOnlyInline}} - : A string representing the new URL the window is navigating to. - {{domxref("HashChangeEvent.oldURL")}} {{ReadOnlyInline}} - : A string representing the previous URL from which the window was navigated. ## Event handler aliases In addition to the `Window` interface, the event handler property `onhashchange` is also available on the following targets: - {{domxref("HTMLBodyElement")}} - {{domxref("HTMLFrameSetElement")}} - {{domxref("SVGSVGElement")}} ## Examples You can use the `hashchange` event in an {{domxref("EventTarget/addEventListener", "addEventListener")}} method: ```js window.addEventListener( "hashchange", () => { console.log("The hash has changed!"); }, false, ); ``` Or use the `onhashchange` event handler property: ```js function locationHashChanged() { if (location.hash === "#cool-feature") { console.log("You're visiting a cool feature!"); } } window.onhashchange = locationHashChanged; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Window/popstate_event", "popstate")}} event
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/scrollx/index.md
--- title: "Window: scrollX property" short-title: scrollX slug: Web/API/Window/scrollX page-type: web-api-instance-property browser-compat: api.Window.scrollX --- {{ APIRef("CSSOM View") }} The read-only **`scrollX`** property of the {{domxref("Window")}} interface returns the number of pixels that the document is currently scrolled horizontally. This value is subpixel precise in modern browsers, meaning that it isn't necessarily a whole number. You can get the number of pixels the document is scrolled vertically from the {{domxref("Window.scrollY", "scrollY")}} property. ## Value In practice, the returned value is a double-precision floating-point value with the range of E(min)=-1022 to E(max)=1023 indicating the number of pixels the document is currently scrolled horizontally from the origin, where a positive value means the content is scrolled to the left. If the document is rendered on a subpixel-precise device, then the returned value is also subpixel-precise and may contain a decimal component. If the document isn't scrolled at all left or right, then `scrollX` is 0. > **Note:** If you need an integer value, you can use {{jsxref("Math.round()")}} to round it off. In more technical terms, `scrollX` returns the X coordinate of the left edge of the current {{Glossary("viewport")}}. If there is no viewport, the returned value is 0\. ## Examples This example checks the current horizontal scroll position of the document. If it's greater than 400 pixels, the window is scrolled back to the beginning. ```js if (window.scrollX > 400) { window.scroll(0, 0); } ``` ## Notes The `pageXOffset` property is an alias for the `scrollX` property: ```js window.pageXOffset === window.scrollX; // always true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Window.scrollY")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/captureevents/index.md
--- title: "Window: captureEvents() method" short-title: captureEvents() slug: Web/API/Window/captureEvents page-type: web-api-instance-method status: - deprecated browser-compat: api.Window.captureEvents --- {{ ApiRef() }} {{Deprecated_Header}} The **`Window.captureEvents()`** method does nothing. > **Note:** This is an method long removed from the specification. It is kept in browsers to prevent code breakage but does nothing. ## Syntax ```js-nolint captureEvents() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/originagentcluster/index.md
--- title: "Window: originAgentCluster property" short-title: originAgentCluster slug: Web/API/Window/originAgentCluster page-type: web-api-instance-property status: - experimental browser-compat: api.Window.originAgentCluster --- {{APIRef}}{{SeeCompatTable}} The **`originAgentCluster`** read-only property of the {{domxref("Window")}} interface returns `true` if this window belongs to an _origin-keyed [agent cluster](https://tc39.es/ecma262/#sec-agent-clusters)_: this means that the operating system has provided dedicated resources (for example an operating system process) to this window's origin that are not shared with windows from other origins. Otherwise this property returns `false`. Windows that are part of an origin-keyed agent cluster are subjects to some additional restrictions, compared with windows that are not. In particular, they cannot: - Set {{domxref("Document.domain")}}, which is a legacy feature that normally allows same-site cross-origin pages to synchronously access each other's DOM. - Send [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) objects to other same-site cross-origin pages via {{domxref("Window.postMessage()")}}. - Send {{jsxref("SharedArrayBuffer")}} or [`WebAssembly.Memory`](/en-US/docs/WebAssembly/JavaScript_interface/Memory) objects to other same-site cross-origin pages. To request that the browser assign this window to an origin-keyed agent cluster, the server must send the {{httpheader("Origin-Agent-Cluster")}} response header. Note that the origin-keyed agent cluster feature is only supported in {{glossary("Secure Context", "secure contexts")}}. If a site is not a secure context, the `window.originAgentCluster` will always return `false`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{httpheader("Origin-Agent-Cluster")}} HTTP response header - [Requesting performance isolation with the Origin-Agent-Cluster header](https://web.dev/articles/origin-agent-cluster)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/appinstalled_event/index.md
--- title: "Window: appinstalled event" short-title: appinstalled slug: Web/API/Window/appinstalled_event page-type: web-api-event browser-compat: api.Window.appinstalled_event --- {{APIRef}} The **`appinstalled`** event of the [Web Manifest API](/en-US/docs/Web/Manifest) is fired when the browser has successfully installed a page as an application. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("appinstalled", (event) => {}); onappinstalled = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples You can use the `appinstalled` event in an {{domxref("EventTarget/addEventListener", "addEventListener")}} method: ```js window.addEventListener("appinstalled", () => { console.log("Thank you for installing our app!"); }); ``` Or use the `onappinstalled` event handler property: ```js window.onappinstalled = () => { console.log("Thank you for installing our app!"); }; ``` ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/scrollmaxy/index.md
--- title: "Window: scrollMaxY property" short-title: scrollMaxY slug: Web/API/Window/scrollMaxY page-type: web-api-instance-property status: - non-standard browser-compat: api.Window.scrollMaxY --- {{APIRef}} {{Non-standard_header}} The **`Window.scrollMaxY`** read-only property returns the maximum number of pixels that the document can be scrolled vertically. ## Value A number. ## Examples ```js // Scroll to the bottom of the page let maxY = window.scrollMaxY; window.scrollTo(0, maxY); ``` ## Notes Do not use this property to get the total document height, which is not equivalent to {{domxref("window.innerHeight")}} + window\.scrollMaxY, because {{domxref("window.innerHeight")}} includes the width of any visible horizontal scrollbar, thus the result would exceed the total document height by the width of any visible horizontal scrollbar. Instead use {{domxref("element.scrollHeight","document.body.scrollHeight")}}. See also {{domxref("window.scrollMaxX")}} and {{domxref("window.scrollTo")}}. ## Specifications This is not part of any specification. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/open/index.md
--- title: "Window: open() method" short-title: open() slug: Web/API/Window/open page-type: web-api-instance-method browser-compat: api.Window.open --- {{APIRef}} The **`open()`** method of the [`Window`](/en-US/docs/Web/API/Window) interface loads a specified resource into a new or existing browsing context (that is, a tab, a window, or an [iframe](/en-US/docs/Web/HTML/Element/iframe)) under a specified name. ## Syntax ```js-nolint open() open(url) open(url, target) open(url, target, windowFeatures) ``` ### Parameters - `url` {{optional_inline}} - : A string indicating the URL or path of the resource to be loaded. If an empty string (`""`) is specified or this parameter is omitted, a blank page is opened into the targeted browsing context. - `target` {{optional_inline}} - : A string, without whitespace, specifying the [name](/en-US/docs/Web/API/Window/name) of the browsing context the resource is being loaded into. If the name doesn't identify an existing context, a new context is created and given the specified name. The special [`target` keywords](/en-US/docs/Web/HTML/Element/a#target), `_self`, `_blank`, `_parent`, and `_top`, can also be used. This name can be used as the `target` attribute of [`<a>`](/en-US/docs/Web/HTML/Element/a#target) or [`<form>`](/en-US/docs/Web/HTML/Element/form#target) elements. - `windowFeatures` {{optional_inline}} - : A string containing a comma-separated list of window features in the form `name=value` — or for boolean features, just `name`. These features include options such as the window's default size and position, whether or not to open a minimal popup window, and so forth. The following options are supported: - `popup` - : If this feature is enabled, it requests that a minimal popup window be used. The UI features included in the popup window will be automatically decided by the browser, generally including an address bar only. If `popup` is not enabled, and there are no window features declared, the new browsing context will be a tab. > **Note:** Specifying any features in the `windowFeatures` parameter, other than `noopener` or `noreferrer`, also has the effect of requesting a popup. To enable the feature, specify `popup` either with no value at all, or else set it to `yes`, `1`, or `true`. Example: `popup=yes`, `popup=1`, `popup=true`, and `popup` all have identical results. - `width` or `innerWidth` - : Specifies the width of the content area, including scrollbars. The minimum required value is 100. - `height` or `innerHeight` - : Specifies the height of the content area, including scrollbars. The minimum required value is 100. - `left` or `screenX` - : Specifies the distance in pixels from the left side of the work area as defined by the user's operating system where the new window will be generated. - `top` or `screenY` - : Specifies the distance in pixels from the top side of the work area as defined by the user's operating system where the new window will be generated. - `noopener` - : If this feature is set, the new window will not have access to the originating window via [`Window.opener`](/en-US/docs/Web/API/Window/opener) and returns `null`. When `noopener` is used, non-empty target names, other than `_top`, `_self`, and `_parent`, are treated like `_blank` in terms of deciding whether to open a new browsing context. - `noreferrer` - : If this feature is set, the browser will omit the [`Referer`](/en-US/docs/Web/HTTP/Headers/Referer) header, as well as set `noopener` to true. See [`rel="noreferrer"`](/en-US/docs/Web/HTML/Attributes/rel/noreferrer) for more information. > **Note:** Requested position (`top`, `left`), and requested dimension (`width`, `height`) values in `windowFeatures` **will be corrected** if any of such requested value does not allow the entire browser popup to be rendered within the work area for applications of the user's operating system. In other words, no part of the new popup can be initially positioned offscreen. ### Return value If the browser successfully opens the new browsing context, a [`WindowProxy`](/en-US/docs/Glossary/WindowProxy) object is returned. The returned reference can be used to access properties and methods of the new context as long as it complies with [the same-origin policy](/en-US/docs/Web/Security/Same-origin_policy) security requirements. `null` is returned if the browser fails to open the new browsing context, for example because it was blocked by a browser popup blocker. ## Description The [`Window`](/en-US/docs/Web/API/Window) interface's `open()` method takes a URL as a parameter, and loads the resource it identifies into a new or existing tab or window. The `target` parameter determines which window or tab to load the resource into, and the `windowFeatures` parameter can be used to control to open a new popup with minimal UI features and control its size and position. Remote URLs won't load immediately. When `window.open()` returns, the window always contains `about:blank`. The actual fetching of the URL is deferred and starts after the current script block finishes executing. The window creation and the loading of the referenced resource are done asynchronously. Modern browsers have strict popup blocker policies. Popup windows must be opened in direct response to user input, and a separate user gesture event is required for each `Window.open()` call. This prevents sites from spamming users with lots of windows. However, this poses an issue for multi-window applications. To work around this limitation, you can design your applications to: - Open no more than one new window at once. - Reuse existing windows to display different pages. - Advise users on how to update their browser settings to allow multiple windows. ## Examples ### Opening a new tab ```js window.open("https://www.mozilla.org/", "mozillaTab"); ``` ### Opening a popup Alternatively, the following example demonstrates how to open a popup, using the `popup` feature. ```js window.open("https://www.mozilla.org/", "mozillaWindow", "popup"); ``` It is possible to control the size and position of the new popup: ```js const windowFeatures = "left=100,top=100,width=320,height=320"; const handle = window.open( "https://www.mozilla.org/", "mozillaWindow", windowFeatures, ); if (!handle) { // The window wasn't allowed to open // This is likely caused by built-in popup blockers. // … } ``` ## Progressive enhancement In some cases, JavaScript is disabled or unavailable and `window.open()` will not work. Instead of solely relying on the presence of this feature, we can provide an alternative solution so that the site or application still functions. ### Provide alternative ways when JavaScript is disabled If JavaScript support is disabled or non-existent, then the user agent will create a secondary window accordingly or will render the referenced resource according to its handling of the `target` attribute. The goal and the idea are to provide (and _not impose_) to the user a way to open the referenced resource. #### HTML ```html <a href="https://www.wikipedia.org/" target="OpenWikipediaWindow"> Wikipedia, a free encyclopedia (opens in another, possibly already existing, tab) </a> ``` #### JavaScript ```js let windowObjectReference = null; // global variable function openRequestedTab(url, windowName) { if (windowObjectReference === null || windowObjectReference.closed) { windowObjectReference = window.open(url, windowName); } else { windowObjectReference.focus(); } } const link = document.querySelector("a[target='OpenWikipediaWindow']"); link.addEventListener( "click", (event) => { openRequestedTab(link.href); event.preventDefault(); }, false, ); ``` The above code solves a few usability problems related to links opening popups. The purpose of the `event.preventDefault()` in the code is to cancel the default action of the link: if the event listener for `click` is executed, then there is no need to execute the default action of the link. But if JavaScript support is disabled or non-existent on the user's browser, then the event listener for `click` is ignored, and the browser loads the referenced resource in the target frame or window that has the name `"WikipediaWindowName"`. If no frame nor window has the name `"WikipediaWindowName"`, then the browser will create a new window and name it `"WikipediaWindowName"`. > **Note:** For more details about the `target` attribute, see [`<a>`](/en-US/docs/Web/HTML/Element/a#target) or [`<form>`](/en-US/docs/Web/HTML/Element/form#target). ### Reuse existing windows and avoid `target="_blank"` Using `"_blank"` as the target attribute value will create several new and unnamed windows on the user's desktop that cannot be recycled or reused. Try to provide a meaningful name to your `target` attribute and reuse such `target` attribute on your page so that a click on another link may load the referenced resource in an already created and rendered window (therefore speeding up the process for the user) and therefore justifying the reason (and user system resources, time spent) for creating a secondary window in the first place. Using a single `target` attribute value and reusing it in links is much more user resources friendly as it only creates one single secondary window, which is recycled. Here is an example where a secondary window can be opened and reused for other links: #### HTML ```html <p> <a href="https://www.wikipedia.org/" target="SingleSecondaryWindowName"> Wikipedia, a free encyclopedia (opens in another, possibly already existing, tab) </a> </p> <p> <a href="https://support.mozilla.org/products/firefox" target="SingleSecondaryWindowName"> Firefox FAQ (opens in another, possibly already existing, tab) </a> </p> ``` #### JavaScript ```js let windowObjectReference = null; // global variable let previousURL; /* global variable that will store the url currently in the secondary window */ function openRequestedSingleTab(url) { if (windowObjectReference === null || windowObjectReference.closed) { windowObjectReference = window.open(url, "SingleSecondaryWindowName"); } else if (previousURL !== url) { windowObjectReference = window.open(url, "SingleSecondaryWindowName"); /* if the resource to load is different, then we load it in the already opened secondary window and then we bring such window back on top/in front of its parent window. */ windowObjectReference.focus(); } else { windowObjectReference.focus(); } previousURL = url; /* explanation: we store the current url in order to compare url in the event of another call of this function. */ } const links = document.querySelectorAll( "a[target='SingleSecondaryWindowName']", ); for (const link of links) { link.addEventListener( "click", (event) => { openRequestedSingleTab(link.href); event.preventDefault(); }, false, ); } ``` ## Same-origin policy If the newly opened browsing context does not share the same [origin](/en-US/docs/Glossary/Origin), the opening script will not be able to interact (reading or writing) with the browsing context's content. ```js example-bad // Script from example.com const otherOriginContext = window.open("https://example.org"); // example.com and example.org are not the same origin console.log(otherOriginContext.origin); // DOMException: Permission denied to access property "origin" on cross-origin object ``` ```js example-good // Script from example.com const sameOriginContext = window.open("https://example.com"); // This time, the new browsing context has the same origin console.log(sameOriginContext.origin); // https://example.com ``` For more information, refer to the [Same-origin policy](/en-US/docs/Web/Security/Same-origin_policy) article. ## Accessibility concerns ### Avoid resorting to window.open() It is preferable to avoid resorting to `window.open()`, for several reasons: - Modern browsers offer a popup-blocking feature. - Modern browsers offer tab-browsing, and tab-capable browser users prefer opening new tabs to opening new windows in most situations. - Users may use browser built-in features or extensions to choose whether to open a link in a new window, in the same window, in a new tab, the same tab, or in the background. Forcing the opening to happen in a specific way, using `window.open()`, will confuse them and disregard their habits. - Popups don't have a menu toolbar, whereas new tabs use the user interface of the browser window; therefore, many users prefer tab-browsing because the interface remains stable. ### Never use window.open() inline in HTML Avoid `<a href="#" onclick="window.open(…);">` or `<a href="javascript:window\.open(…)" …>`. These bogus `href` values cause unexpected behavior when copying/dragging links, opening links in a new tab/window, bookmarking, or when JavaScript is loading, errors, or is disabled. They also convey incorrect semantics to assistive technologies, like screen readers. If necessary, use a [`<button>`](/en-US/docs/Web/HTML/Element/button) element instead. In general, _you should only use a link for navigation to a real URL_. ### Always identify links leading to a secondary window Identify links that will open new windows in a way that helps navigation for users. ```html <a target="WikipediaWindow" href="https://www.wikipedia.org"> Wikipedia (opens in new tab) </a> ``` The purpose is to warn users of context changes to minimize confusion on the user's part: changing the current window or popping up new windows can be very disorienting to users (in the case of a popup, no toolbar provides a "Previous" button to get back to the previous window). When extreme changes in context are explicitly identified before they occur, then the users can determine if they wish to proceed or so they can be prepared for the change: not only they will not be confused or feel disoriented, but more experienced users can better decide how to open such links (in a new window or not, in the same window, in a new tab or not, in "background" or not). - [WebAIM: Links and Hypertext - Hypertext Links](https://webaim.org/techniques/hypertext/hypertext_links) - [MDN / Understanding WCAG, Guideline 3.2](/en-US/docs/Web/Accessibility/Understanding_WCAG/Understandable#guideline_3.2_—_predictable_make_web_pages_appear_and_operate_in_predictable_ways) - [G200: Opening new windows and tabs from a link only when necessary](https://www.w3.org/TR/WCAG20-TECHS/G200.html) - [G201: Giving users advanced warning when opening a new window](https://www.w3.org/TR/WCAG20-TECHS/G201.html) ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - `target` attribute documentation: - [`<a>`](/en-US/docs/Web/HTML/Element/a#target) - [`<form>`](/en-US/docs/Web/HTML/Element/form#target) - [`window.close()`](/en-US/docs/Web/API/Window/close) - [`window.closed`](/en-US/docs/Web/API/Window/closed) - [`window.focus()`](/en-US/docs/Web/API/Window/focus) - [`window.opener`](/en-US/docs/Web/API/Window/opener) - [`rel="opener"`](/en-US/docs/Web/HTML/Attributes/rel#opener) and [`rel="noopener"`](/en-US/docs/Web/HTML/Attributes/rel#noopener) - [Same-origin policy](/en-US/docs/Web/Security/Same-origin_policy)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/showopenfilepicker/index.md
--- title: "Window: showOpenFilePicker() method" short-title: showOpenFilePicker() slug: Web/API/Window/showOpenFilePicker page-type: web-api-instance-method status: - experimental browser-compat: api.Window.showOpenFilePicker --- {{APIRef("File System API")}}{{SecureContext_Header}}{{SeeCompatTable}} The **`showOpenFilePicker()`** method of the {{domxref("Window")}} interface shows a file picker that allows a user to select a file or multiple files and returns a handle for the file(s). ## Syntax ```js-nolint showOpenFilePicker() ``` ### Parameters - `options` {{Optional_Inline}} - : An object containing options, which are as follows: - `excludeAcceptAllOption` {{Optional_Inline}} - : A boolean value that defaults to `false`. By default the picker should include an option to not apply any file type filters (instigated with the type option below). Setting this option to `true` means that option is _not_ available. - `id` {{Optional_Inline}} - : By specifying an ID, the browser can remember different directories for different IDs. If the same ID is used for another picker, the picker opens in the same directory. - `multiple` {{Optional_Inline}} - : A boolean value that defaults to `false`. When set to `true` multiple files may be selected. - `startIn` {{Optional_Inline}} - : A `FileSystemHandle` or a well known directory (`"desktop"`, `"documents"`, `"downloads"`, `"music"`, `"pictures"`, or `"videos"`) to open the dialog in. - `types` {{Optional_Inline}} - : An {{jsxref('Array')}} of allowed file types to pick. Each item is an object with the following options: - `description` {{Optional_Inline}} - : An optional description of the category of files types allowed. Defaults to an empty string. - `accept` - : An {{jsxref('Object')}} with the keys set to the [MIME type](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types) and the values an {{jsxref('Array')}} of file extensions (see below for an example). ### Return value A {{jsxref("Promise")}} whose fulfillment handler receives an {{jsxref('Array')}} of {{domxref('FileSystemFileHandle')}} objects. ### Exceptions - `AbortError` {{domxref("DOMException")}} - : Thrown if the user dismisses the prompt without making a selection, or if the user agent deems any selected files too sensitive or dangerous. - `SecurityError` {{domxref("DOMException")}} - : Thrown if the call was blocked by the [same-origin policy](/en-US/docs/Web/Security/Same-origin_policy) or it was not called via a user interaction such as a button press. - {{jsxref("TypeError")}} - : Thrown if accept types can't be processed, which may happen if: - Any key string of the `accept` options of any item in `types` options can't parse a valid MIME type. - Any value string(s) of the `accept` options of any item in `types` options is invalid, for example, if it does not start with `.` and if end with `.`, or if it contains any invalid code points and its length is more than 16. - The `types` options is empty and the `excludeAcceptAllOption` options is `true`. ## Security [Transient user activation](/en-US/docs/Web/Security/User_activation) is required. The user has to interact with the page or a UI element in order for this feature to work. ## Examples Here we set the options object for passing into the method. We'll allow a selection of image file types, with no option to allow for all files types, or multiple file selection. ```js const pickerOpts = { types: [ { description: "Images", accept: { "image/*": [".png", ".gif", ".jpeg", ".jpg"], }, }, ], excludeAcceptAllOption: true, multiple: false, }; ``` Next we can create an asynchronous function which show the file picker and return the selected file. ```js // create a reference for our file handle let fileHandle; async function getFile() { // open file picker, destructure the one element returned array [fileHandle] = await window.showOpenFilePicker(pickerOpts); // run code with our fileHandle } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [File System API](/en-US/docs/Web/API/File_System_API) - [The File System Access API: simplifying access to local files](https://developer.chrome.com/docs/capabilities/web-apis/file-system-access)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/requestidlecallback/index.md
--- title: "Window: requestIdleCallback() method" short-title: requestIdleCallback() slug: Web/API/Window/requestIdleCallback page-type: web-api-instance-method browser-compat: api.Window.requestIdleCallback --- {{APIRef("HTML DOM")}} The **`window.requestIdleCallback()`** method queues a function to be called during a browser's idle periods. This enables developers to perform background and low priority work on the main event loop, without impacting latency-critical events such as animation and input response. Functions are generally called in first-in-first-out order; however, callbacks which have a `timeout` specified may be called out-of-order if necessary in order to run them before the timeout elapses. You can call `requestIdleCallback()` within an idle callback function to schedule another callback to take place no sooner than the next pass through the event loop. > **Note:** A `timeout` option is strongly recommended for required work, > as otherwise it's possible multiple seconds will elapse before the callback is fired. ## Syntax ```js-nolint requestIdleCallback(callback) requestIdleCallback(callback, options) ``` ### Parameters - `callback` - : A reference to a function that should be called in the near future, when the event loop is idle. The callback function is passed an {{domxref("IdleDeadline")}} object describing the amount of time available and whether or not the callback has been run because the timeout period expired. - `options` {{optional_inline}} - : Contains optional configuration parameters. Currently only one property is defined: - `timeout` - : If the number of milliseconds represented by this parameter has elapsed and the callback has not already been called, then a task to execute the callback is queued in the event loop (even if doing so risks causing a negative performance impact). `timeout` must be a positive value or it is ignored. ### Return value An ID which can be used to cancel the callback by passing it into the {{domxref("window.cancelIdleCallback()")}} method. ## Examples See our [complete example](/en-US/docs/Web/API/Background_Tasks_API#example) in the article [Cooperative Scheduling of Background Tasks API](/en-US/docs/Web/API/Background_Tasks_API). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("window.cancelIdleCallback()")}} - {{domxref("IdleDeadline")}} - {{domxref("setTimeout()")}} - {{domxref("setInterval()")}} - {{domxref("window.requestAnimationFrame")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/mediastreamtrackaudiosourcenode/index.md
--- title: MediaStreamTrackAudioSourceNode slug: Web/API/MediaStreamTrackAudioSourceNode page-type: web-api-interface browser-compat: api.MediaStreamTrackAudioSourceNode --- {{APIRef("Web Audio API")}} The **`MediaStreamTrackAudioSourceNode`** interface is a type of {{domxref("AudioNode")}} which represents a source of audio data taken from a specific {{domxref("MediaStreamTrack")}} obtained through the [WebRTC](/en-US/docs/Web/API/WebRTC_API) or [Media Capture and Streams](/en-US/docs/Web/API/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 {{domxref("RTCPeerConnection")}}, among other possible options. A `MediaStreamTrackAudioSourceNode` has no inputs and exactly one output, and is created using the {{domxref("AudioContext.createMediaStreamTrackSource()")}} method. This interface is similar to {{domxref("MediaStreamAudioSourceNode")}}, except it lets you specifically state the track to use, rather than assuming the first audio track on a stream. {{InheritanceDiagram}} <table class="properties"> <tbody> <tr> <th scope="row">Number of inputs</th> <td><code>0</code></td> </tr> <tr> <th scope="row">Number of outputs</th> <td><code>1</code></td> </tr> <tr> <th scope="row">Channel count</th> <td> defined by the first audio {{domxref("MediaStreamTrack")}} passed to the {{domxref("AudioContext.createMediaStreamTrackSource()")}} method that created it. </td> </tr> </tbody> </table> ## Constructor - {{domxref("MediaStreamTrackAudioSourceNode.MediaStreamTrackAudioSourceNode", "new 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, {{domxref("AudioNode")}}._ ## Instance methods _Inherits methods from its parent, {{domxref("AudioNode")}}_. ## Example See [`AudioContext.createMediaStreamSource()`](/en-US/docs/Web/API/AudioContext/createMediaStreamSource#examples) for example code that uses this object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API) - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - [Media Capture and Streams API (Media Streams)](/en-US/docs/Web/API/Media_Capture_and_Streams_API) - {{domxref("MediaStreamAudioSourceNode")}}
0
data/mdn-content/files/en-us/web/api/mediastreamtrackaudiosourcenode
data/mdn-content/files/en-us/web/api/mediastreamtrackaudiosourcenode/mediastreamtrackaudiosourcenode/index.md
--- title: "MediaStreamTrackAudioSourceNode: MediaStreamTrackAudioSourceNode() constructor" short-title: MediaStreamTrackAudioSourceNode() slug: Web/API/MediaStreamTrackAudioSourceNode/MediaStreamTrackAudioSourceNode page-type: web-api-constructor browser-compat: api.MediaStreamTrackAudioSourceNode.MediaStreamTrackAudioSourceNode --- {{APIRef("Web Audio API")}} The [Web Audio API](/en-US/docs/Web/API/Web_Audio_API)'s **`MediaStreamTrackAudioSourceNode()`** constructor creates and returns a new {{domxref("MediaStreamTrackAudioSourceNode")}} object whose audio is taken from the {{domxref("MediaStreamTrack")}} specified in the given options object. Another way to create a `MediaStreamTrackAudioSourceNode` is to call the {{domxref("AudioContext.createMediaStreamTrackSource()")}} method, specifying the {{domxref("MediaStreamTrack")}} from which you want to obtain audio. ## Syntax ```js-nolint new MediaStreamTrackAudioSourceNode(context, options) ``` ### Parameters - `context` - : An {{domxref("AudioContext")}} representing the audio context you want the node to be associated with. - `options` - : An object defining the properties you want the `MediaStreamTrackAudioSourceNode` to have: - `mediaStreamTrack` - : The {{domxref("MediaStreamTrack")}} from which to take audio data for this node's output. ### Return value A new {{domxref("MediaStreamTrackAudioSourceNode")}} object representing the audio node whose media is obtained from the specified media track. ### Exceptions - `NotSupportedError` {{domxref("DOMException")}} - : Thrown if the specified `context` is not an {{domxref("AudioContext")}}. - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the specified {{domxref("MediaStreamTrack")}} isn't an audio track (that is, its {{domxref("MediaStreamTrack.kind", "kind")}} property isn't `audio`. ## Example This example uses {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}} to obtain access to the user's camera, then creates a new {{domxref("MediaStreamAudioSourceNode")}} from the first audio track provided by the device. ```js const audioCtx = new AudioContext(); if (navigator.mediaDevices.getUserMedia) { navigator.mediaDevices .getUserMedia({ audio: true, video: false, }) .then((stream) => { const options = { mediaStreamTrack: stream.getAudioTracks()[0], }; const source = new MediaStreamTrackAudioSourceNode(audioCtx, options); source.connect(audioCtx.destination); }) .catch((err) => { console.error(`The following gUM error occurred: ${err}`); }); } else { console.log("new getUserMedia not supported on your browser!"); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/aesgcmparams/index.md
--- title: AesGcmParams slug: Web/API/AesGcmParams page-type: web-api-interface spec-urls: https://w3c.github.io/webcrypto/#dfn-AesGcmParams --- {{ APIRef("Web Crypto API") }} The **`AesGcmParams`** dictionary of the [Web Crypto API](/en-US/docs/Web/API/Web_Crypto_API) represents the object that should be passed as the `algorithm` parameter into {{domxref("SubtleCrypto.encrypt()")}}, {{domxref("SubtleCrypto.decrypt()")}}, {{domxref("SubtleCrypto.wrapKey()")}}, or {{domxref("SubtleCrypto.unwrapKey()")}}, when using the [AES-GCM](/en-US/docs/Web/API/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 {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}}, or a {{jsxref("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_inline}} - : An {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}}, or a {{jsxref("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()`](/en-US/docs/Web/API/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_inline}} - : 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 {{domxref("SubtleCrypto.encrypt()")}} and {{domxref("SubtleCrypto.decrypt()")}}. ## Specifications {{Specifications}} ## Browser compatibility Browsers that support the "AES-GCM" algorithm for the {{domxref("SubtleCrypto.encrypt()")}}, {{domxref("SubtleCrypto.decrypt()")}}, {{domxref("SubtleCrypto.wrapKey()")}}, or {{domxref("SubtleCrypto.unwrapKey()")}} methods will support this type. ## See also - {{domxref("SubtleCrypto.encrypt()")}}. - {{domxref("SubtleCrypto.decrypt()")}}. - {{domxref("SubtleCrypto.wrapKey()")}}. - {{domxref("SubtleCrypto.unwrapKey()")}}.
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/speechrecognitionerrorevent/index.md
--- title: SpeechRecognitionErrorEvent slug: Web/API/SpeechRecognitionErrorEvent page-type: web-api-interface browser-compat: api.SpeechRecognitionErrorEvent --- {{APIRef("Web Speech API")}} The **`SpeechRecognitionErrorEvent`** interface of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) represents error messages from the recognition service. {{InheritanceDiagram}} ## Instance properties _`SpeechRecognitionErrorEvent` also inherits properties from its parent interface, {{domxref("Event")}}._ - {{domxref("SpeechRecognitionErrorEvent.error")}} {{ReadOnlyInline}} - : Returns the type of error raised. - {{domxref("SpeechRecognitionErrorEvent.message")}} {{ReadOnlyInline}} - : Returns a message describing the error in more detail. ## Examples ```js const recognition = new SpeechRecognition(); recognition.onerror = (event) => { console.log(`Speech recognition error detected: ${event.error}`); console.log(`Additional information: ${event.message}`); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognitionerrorevent
data/mdn-content/files/en-us/web/api/speechrecognitionerrorevent/error/index.md
--- title: "SpeechRecognitionErrorEvent: error property" short-title: error slug: Web/API/SpeechRecognitionErrorEvent/error page-type: web-api-instance-property browser-compat: api.SpeechRecognitionErrorEvent.error --- {{APIRef("Web Speech API")}} The **`error`** read-only property of the {{domxref("SpeechRecognitionErrorEvent")}} interface returns the type of error raised. ## Value A string naming the type of error. The possible error types are: - `no-speech` - : No speech was detected. - `aborted` - : Speech input was aborted in some manner, perhaps by some user-agent-specific behavior like a button the user can press to cancel speech input. - `audio-capture` - : Audio capture failed. - `network` - : Network communication required for completing the recognition failed. - `not-allowed` - : The user agent disallowed any speech input from occurring for reasons of security, privacy or user preference. - `service-not-allowed` - : The user agent disallowed the requested speech recognition service, either because the user agent doesn't support it or because of reasons of security, privacy or user preference. In this case it would allow another more suitable speech recognition service to be used instead. - `bad-grammar` - : There was an error in the speech recognition grammar or semantic tags, or the chosen grammar format or semantic tag format was unsupported. - `language-not-supported` - : The user agent does not support the language specified in the value of [`lang`](/en-US/docs/Web/API/SpeechRecognition/lang) attribute of the {{domxref("SpeechRecognition")}} object. The set of supported languages is browser-dependent, and from frontend code there is no way to programmatically determine what languages a user's browser supports for speech recognition. ## Examples ```js const recognition = new SpeechRecognition(); recognition.onerror = (event) => { console.log(`Speech recognition error detected: ${event.error}`); console.log(`Additional information: ${event.message}`); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/speechrecognitionerrorevent
data/mdn-content/files/en-us/web/api/speechrecognitionerrorevent/message/index.md
--- title: "SpeechRecognitionErrorEvent: message property" short-title: message slug: Web/API/SpeechRecognitionErrorEvent/message page-type: web-api-instance-property browser-compat: api.SpeechRecognitionErrorEvent.message --- {{APIRef("Web Speech API")}} The **`message`** read-only property of the {{domxref("SpeechRecognitionErrorEvent")}} interface returns a message describing the error in more detail. ## Value A string containing more details about the error that was raised. Note that the spec does not define the exact wording of these messages — this is up to the implementors to decide upon. ## Examples ```js const recognition = new SpeechRecognition(); recognition.onerror = (event) => { console.log(`Speech recognition error detected: ${event.error}`); console.log(`Additional information: ${event.message}`); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmltablesectionelement/index.md
--- title: HTMLTableSectionElement slug: Web/API/HTMLTableSectionElement page-type: web-api-interface browser-compat: api.HTMLTableSectionElement --- {{ APIRef("HTML DOM") }} The **`HTMLTableSectionElement`** interface provides special properties and methods (beyond the {{domxref("HTMLElement")}} interface it also has available to it by inheritance) for manipulating the layout and presentation of sections, that is headers, footers and bodies ({{HTMLElement("thead")}}, {{HTMLElement("tfoot")}}, and {{HTMLElement("tbody")}}, respectively) in an HTML table. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent, {{domxref("HTMLElement")}}._ - {{domxref("HTMLTableSectionElement.align")}} {{deprecated_inline}} - : A string containing an enumerated value reflecting the [`align`](/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"`. - {{domxref("HTMLTableSectionElement.rows")}} {{ReadOnlyInline}} - : Returns a live {{domxref("HTMLCollection")}} containing the rows in the section. The `HTMLCollection` is live and is automatically updated when rows are added or removed. - {{domxref("HTMLTableSectionElement.ch")}} {{deprecated_inline}} - : A string containing one single character. This character is the one to align all the cell of a column on. It reflects the [`char`](/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. - {{domxref("HTMLTableSectionElement.chOff")}} {{deprecated_inline}} - : 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. - {{domxref("HTMLTableSectionElement.vAlign")}} {{deprecated_inline}} - : A string representing an enumerated value indicating how the content of the cell must be vertically aligned. It reflects the [`valign`](/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, {{domxref("HTMLElement")}}_. - {{domxref("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 {{DOMxRef("DOMException")}} with the value `IndexSizeError` is raised. - {{domxref("HTMLTableSectionElement.insertRow()")}} - : Returns an {{DOMxRef("HTMLTableRowElement")}} representing a new row of the section. It inserts it in the rows collection immediately before the {{HTMLElement("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 {{DOMxRef("DOMException")}} with the value `IndexSizeError` is raised. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The HTML elements implementing this interface: {{HTMLElement("tfoot")}}, {{HTMLElement("thead")}}, and {{HTMLElement("tbody")}}.
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/editcontext_api/index.md
--- title: EditContext API slug: Web/API/EditContext_API page-type: web-api-overview status: - experimental browser-compat: api.EditContext --- {{DefaultAPISidebar("EditContext API")}}{{SeeCompatTable}} The **EditContext API** can be used to build rich text editors on the web that support advanced text input experiences, such as {{glossary("Input Method Editor")}} (IME) composition, emoji picker, or any other platform-specific editing-related UI surfaces. With the EditContext API, you get the flexibility to render your own editable text region using any technology you want. ## Concept Multiple actors are involved when entering text in an editable region of an application: - **User** - : The user provides the text by means of an input method: a keyboard, mouse, voice, or other input method. - **Input method software** - : The input method software converts the user's input into text. For example, this could be an {{glossary("Input Method Editor")}} (IME) that converts keystrokes from a standard keyboard into Japanese, Chinese, or Korean characters. - **OS text input service** - : The text input service of the operating system acts as a link between the input method software and the application. - **Application text edit context** - : The application text edit context provides a state of the text being edited. The state contains information such as the text itself, the current selection, the location of the text in the app's UI. - **Application editable region** - : The application editable region is the UI element of the application that displays the text. While the three first actors are provided by the operating system, the application is responsible for providing the editable region and the text edit context. On the web, editable regions are often [`<textarea>`](/en-US/docs/Web/HTML/Element/textarea) elements, [`<input>`](/en-US/docs/Web/HTML/Element/input) elements, or elements with the [`contenteditable`](/en-US/docs/Web/HTML/Global_attributes/contenteditable) attribute set to `true`. For these elements, the browser automatically provides the text edit context, and web authors are not required to write any code to support text input. ### Creating custom editable regions Web authors can also create custom editable regions using the EditContext API. For example, a web author could create a rich text editor using a [`<canvas>`](/en-US/docs/Web/HTML/Element/canvas) element to render the text. In this case, the web author needs to write code to support text input. ### Author's responsibilities If you decide to implement your own editable region, whether it draws text into a `<canvas>` or renders it into a series of DOM elements, you are responsible for providing the things that the browser would normally provide for you if you were using a `<textarea>` instead. This includes: - Rendering the text. - Rendering the selection (if you build your editable region with DOM elements instead of a `<canvas>`, the browser does render the selection for you). - Letting the OS text input service know when the selection changes. - Letting the OS text input service know where the text is located in the UI, so the input method software can display the IME composition window in the correct location. - Applying certain text formats when the user is composing text within the IME composition window. In return, the EditContext API makes the DOM element you choose editable and part of the document's focus order. In addition, the EditContext API also provides information about the state of the text being edited, which allows you to render it in a custom way. The information provided to you includes: - The current text content. - The current selection. - Whether IME composition is in progress, and whether text formats need to be applied. ### Accessibility If you use the EditContext API with a `<canvas>` element, make sure to also make the text accessible to assistive technology. Screen readers can't read the text in a `<canvas>` element. For example, you could maintain a separate view of the text in an offscreen DOM element that's presented to screen readers. ### Basic usage To use the EditContext API, you need to create an instance of the {{domxref("EditContext")}} interface, and then attach it to the DOM element you want to make editable by using the {{domxref("HTMLElement/editContext", "editContext")}} property. The DOM element can be any element, including a `<div>` or a `<canvas>` element. ```html <canvas id="editor-canvas"></canvas> ``` ```js-nolint const canvas = document.getElementById("editor-canvas"); const editContext = new EditContext(); canvas.editContext = editContext; ``` An `EditContext` instance can only be attached to one DOM element at a time. Attaching an `EditContext` instance to a DOM element makes the element focusable, as part of the document's focus order. The user can enter text into the element using the input method of their choice, and you can use event fired by the `EditContext` instance to render the text and selection. ### Model and view architecture When using the EditContext API, it helps to build your editing experience as a model and view architecture. The `EditContext` instance represents the model of your editable region. Its internal state gets updated when text input is received, and when the selection changes. You can then render the text and selection in the view, using the information provided by the `EditContext` instance, however your view doesn't need to match the model exactly. You're free to render the text in any way you want. ## Interfaces - {{DOMxRef("EditContext")}} {{experimental_inline}} - : The **`EditContext`** interface is a JavaScript reflection of the text edit context that's normally provided transparently by the browser when using standard editable regions such as `textarea`. `EditContext` provides the state of the text being edited, with information such as the text itself, the current selection, or the location of the text in the app's UI. - {{DOMxRef("TextFormat")}} - : The **`TextFormat`** interface is used to represent certain formats that should be applied to text ranges when the user is composing text within the IME composition window. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/xmlhttprequest/index.md
--- title: XMLHttpRequest slug: Web/API/XMLHttpRequest page-type: web-api-interface browser-compat: api.XMLHttpRequest --- {{APIRef("XMLHttpRequest API")}} `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. {{InheritanceDiagram}} 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](/en-US/docs/Web/API/Server-sent_events) through the {{domxref("EventSource")}} interface. For full-duplex communication, [WebSockets](/en-US/docs/Web/API/WebSockets_API) may be a better choice. {{AvailableInWorkers("notservice")}} ## Constructor - {{domxref("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 {{domxref("XMLHttpRequestEventTarget")}} and of {{domxref("EventTarget")}}._ - {{domxref("XMLHttpRequest.readyState")}} {{ReadOnlyInline}} - : Returns a number representing the state of the request. - {{domxref("XMLHttpRequest.response")}} {{ReadOnlyInline}} - : Returns an {{jsxref("ArrayBuffer")}}, a {{domxref("Blob")}}, a {{domxref("Document")}}, a JavaScript object, or a string, depending on the value of {{domxref("XMLHttpRequest.responseType")}}, that contains the response entity body. - {{domxref("XMLHttpRequest.responseText")}} {{ReadOnlyInline}} - : 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. - {{domxref("XMLHttpRequest.responseType")}} - : Specifies the type of the response. - {{domxref("XMLHttpRequest.responseURL")}} {{ReadOnlyInline}} - : Returns the serialized URL of the response or the empty string if the URL is null. - {{domxref("XMLHttpRequest.responseXML")}} {{ReadOnlyInline}} - : Returns a {{domxref("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](/en-US/docs/Web/API/Web_Workers_API). - {{domxref("XMLHttpRequest.status")}} {{ReadOnlyInline}} - : Returns the [HTTP response status code](/en-US/docs/Web/HTTP/Status) of the request. - {{domxref("XMLHttpRequest.statusText")}} {{ReadOnlyInline}} - : Returns a string containing the response string returned by the HTTP server. Unlike {{domxref("XMLHttpRequest.status")}}, this includes the entire text of the response message ("`OK`", for example). > **Note:** According to the HTTP/2 specification {{RFC(7540, "Response Pseudo-Header Fields", "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. - {{domxref("XMLHttpRequest.timeout")}} - : The time in milliseconds a request can take before automatically being terminated. - {{domxref("XMLHttpRequest.upload")}} {{ReadOnlyInline}} - : A {{domxref("XMLHttpRequestUpload")}} representing the upload process. - {{domxref("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 - {{domxref("XMLHttpRequest.channel")}} {{ReadOnlyInline}} - : The channel used by the object when performing the request. - {{domxref("XMLHttpRequest.mozAnon")}} {{ReadOnlyInline}} - : A boolean. If true, the request will be sent without cookie and authentication headers. - {{domxref("XMLHttpRequest.mozSystem")}} {{ReadOnlyInline}} - : A boolean. If true, the same origin policy will not be enforced on the request. - {{domxref("XMLHttpRequest.mozBackgroundRequest")}} - : A boolean. It indicates whether or not the object represents a background service request. ## Instance methods - {{domxref("XMLHttpRequest.abort()")}} - : Aborts the request if it has already been sent. - {{domxref("XMLHttpRequest.getAllResponseHeaders()")}} - : Returns all the response headers, separated by {{Glossary("CRLF")}}, as a string, or `null` if no response has been received. - {{domxref("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. - {{domxref("XMLHttpRequest.open()")}} - : Initializes a request. - {{domxref("XMLHttpRequest.overrideMimeType()")}} - : Overrides the MIME type returned by the server. - {{domxref("XMLHttpRequest.send()")}} - : Sends the request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent. - {{domxref("XMLHttpRequest.setRequestHeader()")}} - : Sets the value of an HTTP request header. You must call `setRequestHeader()` after {{domxref("XMLHttpRequest.open", "open()")}}, but before {{domxref("XMLHttpRequest.send", "send()")}}. ## Events - {{domxref("XMLHttpRequest/abort_event", "abort")}} - : Fired when a request has been aborted, for example because the program called {{domxref("XMLHttpRequest.abort()")}}. Also available via the `onabort` event handler property. - {{domxref("XMLHttpRequest/error_event", "error")}} - : Fired when the request encountered an error. Also available via the `onerror` event handler property. - {{domxref("XMLHttpRequest/load_event", "load")}} - : Fired when an `XMLHttpRequest` transaction completes successfully. Also available via the `onload` event handler property. - {{domxref("XMLHttpRequest/loadend_event", "loadend")}} - : Fired when a request has completed, whether successfully (after {{domxref("XMLHttpRequest/load_event", "load")}}) or unsuccessfully (after {{domxref("XMLHttpRequest/abort_event", "abort")}} or {{domxref("XMLHttpRequest/error_event", "error")}}). Also available via the `onloadend` event handler property. - {{domxref("XMLHttpRequest/loadstart_event", "loadstart")}} - : Fired when a request has started to load data. Also available via the `onloadstart` event handler property. - {{domxref("XMLHttpRequest/progress_event", "progress")}} - : Fired periodically when a request receives more data. Also available via the `onprogress` event handler property. - {{domxref("XMLHttpRequest/readystatechange_event", "readystatechange")}} - : Fired whenever the {{domxref("XMLHttpRequest.readyState", "readyState")}} property changes. Also available via the `onreadystatechange` event handler property. - {{domxref("XMLHttpRequest/timeout_event", "timeout")}} - : Fired when progress is terminated due to preset time expiring. Also available via the `ontimeout` event handler property. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XMLSerializer")}}: Serializing a DOM tree into XML - [Using XMLHttpRequest](/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest) - [Fetch API](/en-US/docs/Web/API/Fetch_API)
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/mozsystem/index.md
--- title: "XMLHttpRequest: mozSystem property" short-title: mozSystem slug: Web/API/XMLHttpRequest/mozSystem page-type: web-api-instance-property status: - non-standard --- {{APIRef("XMLHttpRequest API")}} **`mozSystem`** is a boolean. If true, the same origin policy is not enforced on the request.
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/responsexml/index.md
--- title: "XMLHttpRequest: responseXML property" short-title: responseXML slug: Web/API/XMLHttpRequest/responseXML page-type: web-api-instance-property browser-compat: api.XMLHttpRequest.responseXML --- {{APIRef("XMLHttpRequest API")}} The **`XMLHttpRequest.responseXML`** read-only property returns a {{domxref("Document")}} containing the HTML or XML retrieved by the request; or `null` if the request was unsuccessful, has not yet been sent, or if the data can't be parsed as XML or HTML. > **Note:** The name `responseXML` is an artifact of this > property's history; it works for both HTML and XML. Usually, the response is parsed as "`text/xml`". If the {{domxref("XMLHttpRequest.responseType", "responseType")}} is set to "`document`" and the request was made asynchronously, instead the response is parsed as "`text/html`". `responseXML` is `null` for any other types of data, as well as for [`data:` URLs](/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs). If the server doesn't specify the {{HTTPHeader("Content-Type")}} as "`text/xml`" or "`application/xml`", you can use {{domxref("XMLHttpRequest.overrideMimeType()")}} to parse it as XML anyway. This property isn't available to workers. ## Value A {{domxref("Document")}} from parsing the XML or HTML received using {{domxref("XMLHttpRequest")}}, or `null` if no data was received or if the data is not XML/HTML. ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the {{domxref("XMLHttpRequest.responseType", "responseType")}} isn't either `document` or an empty string. ## Examples ```js const xhr = new XMLHttpRequest(); xhr.open("GET", "/server"); // If specified, responseType must be empty string or "document" xhr.responseType = "document"; // Force the response to be parsed as XML xhr.overrideMimeType("text/xml"); xhr.onload = () => { if (xhr.readyState === xhr.DONE && xhr.status === 200) { console.log(xhr.response, xhr.responseXML); } }; xhr.send(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XMLHttpRequest")}} - {{domxref("XMLHttpRequest.response")}} - {{domxref("XMLHttpRequest.responseType")}} - [Parsing and serializing XML](/en-US/docs/Web/XML/Parsing_and_serializing_XML) - Parsing XML into a DOM tree: {{domxref("DOMParser")}} - Serializing a DOM tree into XML: {{domxref("XMLSerializer")}} (specifically, the {{domxref("XMLSerializer.serializeToString", "serializeToString()")}} method)
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/channel/index.md
--- title: "XMLHttpRequest: channel property" short-title: channel slug: Web/API/XMLHttpRequest/channel page-type: web-api-instance-property status: - non-standard --- {{APIRef("XMLHttpRequest API")}} XMLHttpRequest.channel is an `nsIChannel` that used by the object when performing the request. This is `null` if the channel hasn't been created yet. In the case of a multi-part request, this is the initial channel, not the different parts in the multi-part request. **Requires elevated privileges to access.**
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/mozanon/index.md
--- title: "XMLHttpRequest: mozAnon property" short-title: mozAnon slug: Web/API/XMLHttpRequest/mozAnon page-type: web-api-instance-property status: - non-standard --- {{APIRef("XMLHttpRequest API")}} **`XMLHttpRequest.mozAnon`** is a boolean. If true, the request will be sent without cookies or authentication headers.
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/response/index.md
--- title: "XMLHttpRequest: response property" short-title: response slug: Web/API/XMLHttpRequest/response page-type: web-api-instance-property browser-compat: api.XMLHttpRequest.response --- {{APIRef("XMLHttpRequest API")}} The {{domxref("XMLHttpRequest")}} **`response`** property returns the response's body content as an {{jsxref("ArrayBuffer")}}, a {{domxref("Blob")}}, a {{domxref("Document")}}, a JavaScript {{jsxref("Object")}}, or a string, depending on the value of the request's {{domxref("XMLHttpRequest.responseType", "responseType")}} property. ## Value An appropriate object based on the value of {{domxref("XMLHttpRequest.responseType", "responseType")}}. You may attempt to request the data be provided in a specific format by setting the value of `responseType` after calling {{domxref("XMLHttpRequest.open", "open()")}} to initialize the request but before calling {{domxref("XMLHttpRequest.send", "send()")}} to send the request to the server. The value is `null` if the request is not yet complete or was unsuccessful, with the exception that when reading text data using a `responseType` of `"text"` or the empty string (`""`), the response can contain the response so far while the request is still in the `LOADING` {{domxref("XMLHttpRequest.readyState", "readyState")}} (3). ## Examples This example presents a function, `load()`, which loads and processes a page from the server. It works by creating an {{domxref("XMLHttpRequest")}} object and creating a listener for {{domxref("XMLHttpRequest/readystatechange_event", "readystatechange")}} events such that when `readyState` changes to `DONE` (4), the `response` is obtained and passed into the callback function provided to `load()`. The content is handled as raw text data (since nothing here is overriding the default {{domxref("XMLHttpRequest.responseType", "responseType")}}). ```js const url = "somePage.html"; //A local page function load(url, callback) { const xhr = new XMLHttpRequest(); xhr.onreadystatechange = () => { if (xhr.readyState === 4) { callback(xhr.response); } }; xhr.open("GET", url, true); xhr.send(""); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using XMLHttpRequest](/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest) - Getting text and HTML/XML data: {{domxref("XMLHttpRequest.responseText")}} and {{domxref("XMLHttpRequest.responseXML")}}
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/responsetext/index.md
--- title: "XMLHttpRequest: responseText property" short-title: responseText slug: Web/API/XMLHttpRequest/responseText page-type: web-api-instance-property browser-compat: api.XMLHttpRequest.responseText --- {{APIRef("XMLHttpRequest API")}} The read-only {{domxref("XMLHttpRequest")}} property **`responseText`** returns the text received from a server following a request being sent. ## Value A string which contains either the textual data received using the `XMLHttpRequest` or `null` if the request failed or `""` if the request has not yet been sent by calling {{domxref("XMLHttpRequest.send", "send()")}}. While handling an asynchronous request, the value of `responseText` always has the current content received from the server, even if it's incomplete because the data has not been completely received yet. You know the entire content has been received when the value of {{domxref("XMLHttpRequest.readyState", "readyState")}} becomes `XMLHttpRequest.DONE` (`4`), and {{domxref("XMLHttpRequest.status", "status")}} becomes 200 (`"OK"`). ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the {{domxref("XMLHttpRequest.responseType")}} is not set to either the empty string or `"text"`. Since the `responseText` property is only valid for text content, any other value is an error condition. ## Examples ```js const xhr = new XMLHttpRequest(); xhr.open("GET", "/server", true); // If specified, responseType must be empty string or "text" xhr.responseType = "text"; xhr.onload = () => { if (xhr.readyState === xhr.DONE) { if (xhr.status === 200) { console.log(xhr.response); console.log(xhr.responseText); } } }; xhr.send(null); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/status/index.md
--- title: "XMLHttpRequest: status property" short-title: status slug: Web/API/XMLHttpRequest/status page-type: web-api-instance-property browser-compat: api.XMLHttpRequest.status --- {{APIRef("XMLHttpRequest API")}} The read-only **`XMLHttpRequest.status`** property returns the numerical HTTP [status code](/en-US/docs/Web/HTTP/Status) of the `XMLHttpRequest`'s response. Before the request completes, the value of `status` is 0. Browsers also report a status of 0 in case of `XMLHttpRequest` errors. ## Value A number. ## Examples ```js const xhr = new XMLHttpRequest(); console.log("UNSENT: ", xhr.status); xhr.open("GET", "/server"); console.log("OPENED: ", xhr.status); xhr.onprogress = () => { console.log("LOADING: ", xhr.status); }; xhr.onload = () => { console.log("DONE: ", xhr.status); }; xhr.send(); /** * Outputs the following: * * UNSENT: 0 * OPENED: 0 * LOADING: 200 * DONE: 200 */ ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - List of [HTTP status](/en-US/docs/Web/HTTP/Status) - [HTTP](/en-US/docs/Web/HTTP)
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/send/index.md
--- title: "XMLHttpRequest: send() method" short-title: send() slug: Web/API/XMLHttpRequest/send page-type: web-api-instance-method browser-compat: api.XMLHttpRequest.send --- {{APIRef("XMLHttpRequest API")}} The {{domxref("XMLHttpRequest")}} method **`send()`** sends the request to the server. If the request is asynchronous (which is the default), this method returns as soon as the request is sent and the result is delivered using events. If the request is synchronous, this method doesn't return until the response has arrived. `send()` accepts an optional parameter which lets you specify the request's body; this is primarily used for requests such as {{HTTPMethod("PUT")}}. If the request method is {{HTTPMethod("GET")}} or {{HTTPMethod("HEAD")}}, the `body` parameter is ignored and the request body is set to `null`. If no {{HTTPHeader("Accept")}} header has been set using the {{domxref("XMLHttpRequest.setRequestHeader", "setRequestHeader()")}}, an `Accept` header with the type `"*/*"` (any type) is sent. ## Syntax ```js-nolint send() send(body) ``` ### Parameters - `body` {{optional_inline}} - : A body of data to be sent in the XHR request. This can be: - A {{domxref("Document")}}, in which case it is serialized before being sent. - An `XMLHttpRequestBodyInit`, which [per the Fetch spec](https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit) can be a {{domxref("Blob")}}, an {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}}, a {{jsxref("DataView")}}, a {{domxref("FormData")}}, a {{domxref("URLSearchParams")}}, or a string literal or object. - `null` If no value is specified for the body, a default value of `null` is used. The best way to send binary content (e.g. in file uploads) is by using a {{jsxref("TypedArray")}}, a {{jsxref("DataView")}} or a {{domxref("Blob")}} object in conjunction with the `send()` method. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if `send()` has already been invoked for the request, and/or the request is complete. - `NetworkError` {{domxref("DOMException")}} - : Thrown if the resource type to be fetched is a Blob, and the method is not `GET`. ## Example: GET ```js const xhr = new XMLHttpRequest(); xhr.open("GET", "/server", true); xhr.onload = () => { // Request finished. Do processing here. }; xhr.send(null); // xhr.send('string'); // xhr.send(new Blob()); // xhr.send(new Int8Array()); // xhr.send(document); ``` ## Example: POST ```js const xhr = new XMLHttpRequest(); xhr.open("POST", "/server", true); // Send the proper header information along with the request xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = () => { // Call a function when the state changes. if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { // Request finished. Do processing here. } }; xhr.send("foo=bar&lorem=ipsum"); // xhr.send(new Int8Array()); // xhr.send(document); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using XMLHttpRequest](/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest) - [HTML in XMLHttpRequest](/en-US/docs/Web/API/XMLHttpRequest_API/HTML_in_XMLHttpRequest)
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/setrequestheader/index.md
--- title: "XMLHttpRequest: setRequestHeader() method" short-title: setRequestHeader() slug: Web/API/XMLHttpRequest/setRequestHeader page-type: web-api-instance-method browser-compat: api.XMLHttpRequest.setRequestHeader --- {{APIRef("XMLHttpRequest API")}} The {{domxref("XMLHttpRequest")}} method **`setRequestHeader()`** sets the value of an HTTP request header. When using `setRequestHeader()`, you must call it after calling {{domxref("XMLHttpRequest.open", "open()")}}, but before calling {{domxref("XMLHttpRequest.send", "send()")}}. If this method is called several times with the same header, the values are merged into one single request header. Each time you call `setRequestHeader()` after the first time you call it, the specified text is appended to the end of the existing header's content. If no {{HTTPHeader("Accept")}} header has been set using this, an `Accept` header with the type `"*/*"` is sent with the request when {{domxref("XMLHttpRequest.send", "send()")}} is called. For security reasons, there are several {{Glossary("Forbidden_header_name", "forbidden header names")}} whose values are controlled by the user agent. Any attempt to set a value for one of those headers from frontend JavaScript code will be ignored without warning or error. In addition, the [`Authorization`](/en-US/docs/Web/HTTP/Headers/Authorization) HTTP header may be added to a request, but will be removed if the request is redirected cross-origin. > **Note:** For your custom fields, you may encounter a "**not allowed by Access-Control-Allow-Headers in preflight response**" exception when you send requests across domains. > In this situation, you need to set up the {{HTTPHeader("Access-Control-Allow-Headers")}} in your response header at server side. ## Syntax ```js-nolint setRequestHeader(header, value) ``` ### Parameters - `header` - : The name of the header whose value is to be set. - `value` - : The value to set as the body of the header. ### Return value None ({{jsxref("undefined")}}). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using XMLHttpRequest](/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest) - [HTML in XMLHttpRequest](/en-US/docs/Web/API/XMLHttpRequest_API/HTML_in_XMLHttpRequest)
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/timeout/index.md
--- title: "XMLHttpRequest: timeout property" short-title: timeout slug: Web/API/XMLHttpRequest/timeout page-type: web-api-instance-property browser-compat: api.XMLHttpRequest.timeout --- {{APIRef("XMLHttpRequest API")}} The **`XMLHttpRequest.timeout`** property is an `unsigned long` representing the number of milliseconds a request can take before automatically being terminated. The default value is 0, which means there is no timeout. Timeout shouldn't be used for synchronous XMLHttpRequests requests used in a {{Glossary('document environment')}} or it will throw an `InvalidAccessError` exception. When a timeout happens, a [timeout](/en-US/docs/Web/API/XMLHttpRequest/timeout_event) event is fired. > **Note:** You may not use a timeout for synchronous requests with an owning window. [Using a timeout with an asynchronous request](/en-US/docs/Web/API/XMLHttpRequest_API/Synchronous_and_Asynchronous_Requests#example_using_a_timeout). ## Example ```js const xhr = new XMLHttpRequest(); xhr.open("GET", "/server", true); xhr.timeout = 2000; // time in milliseconds xhr.onload = () => { // Request finished. Do processing here. }; xhr.ontimeout = (e) => { // XMLHttpRequest timed out. Do something here. }; xhr.send(null); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/readystatechange_event/index.md
--- title: "XMLHttpRequest: readystatechange event" short-title: readystatechange slug: Web/API/XMLHttpRequest/readystatechange_event page-type: web-api-event browser-compat: api.XMLHttpRequest.readystatechange_event --- {{APIRef("XMLHttpRequest API")}} The `readystatechange` event is fired whenever the {{domxref("XMLHttpRequest.readyState", "readyState")}} property of the {{domxref("XMLHttpRequest")}} changes. > **Warning:** This should not be used with synchronous requests and must > not be used from native code. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("readystatechange", (event) => {}); onreadystatechange = (event) => {}; ``` ## Event type A generic {{DOMxRef("Event")}} with no added properties. ## Examples ```js const xhr = new XMLHttpRequest(); const method = "GET"; const url = "https://developer.mozilla.org/"; xhr.open(method, url, true); xhr.onreadystatechange = () => { // In local files, status is 0 upon success in Mozilla Firefox if (xhr.readyState === XMLHttpRequest.DONE) { const status = xhr.status; if (status === 0 || (status >= 200 && status < 400)) { // The request has been completed successfully console.log(xhr.responseText); } else { // Oh no! There has been an error with the request! } } }; xhr.send(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/abort_event/index.md
--- title: "XMLHttpRequest: abort event" short-title: abort slug: Web/API/XMLHttpRequest/abort_event page-type: web-api-event browser-compat: api.XMLHttpRequest.abort_event --- {{APIRef("XMLHttpRequest API")}} The `abort` event is fired when a request has been aborted, for example because the program called {{domxref("XMLHttpRequest.abort()")}}. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("abort", (event) => {}); onabort = (event) => {}; ``` ## Event type A {{domxref("ProgressEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("ProgressEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("ProgressEvent.lengthComputable", "lengthComputable")}} {{ReadOnlyInline}} - : 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. - {{domxref("ProgressEvent.loaded", "loaded")}} {{ReadOnlyInline}} - : 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. - {{domxref("ProgressEvent.total", "total")}} {{ReadOnlyInline}} - : 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. ## Examples ### Live example #### HTML ```html <div class="controls"> <input class="xhr success" type="button" name="xhr" value="Click to start XHR (success)" /> <input class="xhr error" type="button" name="xhr" value="Click to start XHR (error)" /> <input class="xhr abort" type="button" name="xhr" value="Click to start XHR (abort)" /> </div> <textarea readonly class="event-log"></textarea> ``` ```css hidden .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: 0.5rem; padding: 0.2rem; } input { width: 11rem; margin: 0.5rem; } ``` #### JavaScript ```js const xhrButtonSuccess = document.querySelector(".xhr.success"); const xhrButtonError = document.querySelector(".xhr.error"); const xhrButtonAbort = document.querySelector(".xhr.abort"); const log = document.querySelector(".event-log"); function handleEvent(e) { log.textContent = `${log.textContent}${e.type}: ${e.loaded} bytes transferred\n`; } function addListeners(xhr) { xhr.addEventListener("loadstart", handleEvent); xhr.addEventListener("load", handleEvent); xhr.addEventListener("loadend", handleEvent); xhr.addEventListener("progress", handleEvent); xhr.addEventListener("error", handleEvent); xhr.addEventListener("abort", handleEvent); } function runXHR(url) { log.textContent = ""; const xhr = new XMLHttpRequest(); addListeners(xhr); xhr.open("GET", url); xhr.send(); return xhr; } xhrButtonSuccess.addEventListener("click", () => { runXHR("my-picture.jpg"); }); xhrButtonError.addEventListener("click", () => { runXHR("https://example.com/some-path"); }); xhrButtonAbort.addEventListener("click", () => { runXHR("my-picture.jpg").abort(); }); ``` #### Result {{ EmbedLiveSample('Live_example', '100%', '150px') }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: {{domxref("XMLHttpRequest/loadstart_event", "loadstart")}}, {{domxref("XMLHttpRequest/load_event", "load")}}, {{domxref("XMLHttpRequest/progress_event", "progress")}}, {{domxref("XMLHttpRequest/error_event", "error")}}, {{domxref("XMLHttpRequest/loadend_event", "loadend")}} - [Monitoring progress](/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest#monitoring_progress)
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/withcredentials/index.md
--- title: "XMLHttpRequest: withCredentials property" short-title: withCredentials slug: Web/API/XMLHttpRequest/withCredentials page-type: web-api-instance-property browser-compat: api.XMLHttpRequest.withCredentials --- {{APIRef("XMLHttpRequest API")}} The **`XMLHttpRequest.withCredentials`** property is a boolean value that indicates whether or not cross-site `Access-Control` requests should be made using credentials such as cookies, authorization headers or TLS client certificates. Setting `withCredentials` has no effect on same-origin requests. In addition, this flag is also used to indicate when cookies are to be ignored in the response. The default is `false`. `XMLHttpRequest` responses from a different domain cannot set cookie values for their own domain unless `withCredentials` is set to `true` before making the request. The third-party cookies obtained by setting `withCredentials` to true will still honor same-origin policy and hence can not be accessed by the requesting script through [document.cookie](/en-US/docs/Web/API/Document/cookie) or from response headers. > **Note:** This never affects same-origin requests. > **Note:** `XMLHttpRequest` responses from a different domain _cannot_ set cookie values for their own domain unless `withCredentials` is set to `true` before making the request, regardless of `Access-Control-` header values. ## Value A boolean. ## Examples ```js const xhr = new XMLHttpRequest(); xhr.open("GET", "http://example.com/", true); xhr.withCredentials = true; xhr.send(null); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/getresponseheader/index.md
--- title: "XMLHttpRequest: getResponseHeader() method" short-title: getResponseHeader() slug: Web/API/XMLHttpRequest/getResponseHeader page-type: web-api-instance-method browser-compat: api.XMLHttpRequest.getResponseHeader --- {{APIRef("XMLHttpRequest API")}} The {{DOMxRef("XMLHttpRequest")}} method **`getResponseHeader()`** returns the string containing the text of a particular header's value. If there are multiple response headers with the same name, then their values are returned as a single concatenated string, where each value is separated from the previous one by a pair of comma and space. The `getResponseHeader()` method returns the value as a UTF byte sequence. > **Note:** The search for the header name is case-insensitive. If you need to get the raw string of all of the headers, use the {{DOMxRef("XMLHttpRequest.getAllResponseHeaders", "getAllResponseHeaders()")}} method, which returns the entire raw header string. ## Syntax ```js-nolint getResponseHeader(headerName) ``` ### Parameters - `headerName` - : A string indicating the name of the header you want to return the text value of. ### Return value A string representing the header's text value, or `null` if either the response has not yet been received or the header doesn't exist in the response. ## Examples In this example, a request is created and sent, and a {{domxref("XMLHttpRequest/readystatechange_event", "readystatechange")}} handler is established to look for the {{DOMxRef("XMLHttpRequest.readyState", "readyState")}} to indicate that the headers have been received; when that is the case, the value of the {{httpheader("Content-Type")}} header is fetched. If the `Content-Type` isn't the desired value, the {{DOMxRef("XMLHttpRequest")}} is canceled by calling {{DOMxRef("XMLHttpRequest.abort", "abort()")}}. ```js const client = new XMLHttpRequest(); client.open("GET", "unicorns-are-awesome.txt", true); client.send(); client.onreadystatechange = () => { if (client.readyState === client.HEADERS_RECEIVED) { const contentType = client.getResponseHeader("Content-Type"); if (contentType !== my_expected_type) { client.abort(); } } }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using XMLHttpRequest](/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest) - [HTTP headers](/en-US/docs/Web/HTTP/Headers) - {{DOMxRef("XMLHttpRequest.getAllResponseHeaders", "getAllResponseHeaders()")}} - {{DOMxRef("XMLHttpRequest.response", "response")}} - Setting request headers: {{DOMxRef("XMLHttpRequest.setRequestHeader", "setRequestHeader()")}}
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/progress_event/index.md
--- title: "XMLHttpRequest: progress event" short-title: progress slug: Web/API/XMLHttpRequest/progress_event page-type: web-api-event browser-compat: api.XMLHttpRequest.progress_event --- {{APIRef("XMLHttpRequest API")}} The **`progress`** event is fired periodically when a request receives more data. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("progress", (event) => {}); onprogress = (event) => {}; ``` ## Event type A {{domxref("ProgressEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("ProgressEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("ProgressEvent.lengthComputable", "lengthComputable")}} {{ReadOnlyInline}} - : 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. - {{domxref("ProgressEvent.loaded", "loaded")}} {{ReadOnlyInline}} - : 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. - {{domxref("ProgressEvent.total", "total")}} {{ReadOnlyInline}} - : 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. ## Examples ### Live example #### HTML ```html <div class="controls"> <input class="xhr success" type="button" name="xhr" value="Click to start XHR (success)" /> <input class="xhr error" type="button" name="xhr" value="Click to start XHR (error)" /> <input class="xhr abort" type="button" name="xhr" value="Click to start XHR (abort)" /> </div> <textarea readonly class="event-log"></textarea> ``` ```css hidden .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: 0.5rem; padding: 0.2rem; } input { width: 11rem; margin: 0.5rem; } ``` #### JavaScript ```js const xhrButtonSuccess = document.querySelector(".xhr.success"); const xhrButtonError = document.querySelector(".xhr.error"); const xhrButtonAbort = document.querySelector(".xhr.abort"); const log = document.querySelector(".event-log"); function handleEvent(e) { log.textContent = `${log.textContent}${e.type}: ${e.loaded} bytes transferred\n`; } function addListeners(xhr) { xhr.addEventListener("loadstart", handleEvent); xhr.addEventListener("load", handleEvent); xhr.addEventListener("loadend", handleEvent); xhr.addEventListener("progress", handleEvent); xhr.addEventListener("error", handleEvent); xhr.addEventListener("abort", handleEvent); } function runXHR(url) { log.textContent = ""; const xhr = new XMLHttpRequest(); addListeners(xhr); xhr.open("GET", url); xhr.send(); return xhr; } xhrButtonSuccess.addEventListener("click", () => { runXHR( "https://raw.githubusercontent.com/mdn/content/main/files/en-us/_wikihistory.json", ); }); xhrButtonError.addEventListener("click", () => { runXHR("http://i-dont-exist"); }); xhrButtonAbort.addEventListener("click", () => { runXHR( "https://raw.githubusercontent.com/mdn/content/main/files/en-us/_wikihistory.json", ).abort(); }); ``` #### Result {{ EmbedLiveSample('Live_example', '100%', '150px') }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: {{domxref("XMLHttpRequest/loadstart_event", "loadstart")}}, {{domxref("XMLHttpRequest/load_event", "load")}}, {{domxref("XMLHttpRequest/loadend_event", "loadend")}}, {{domxref("XMLHttpRequest/error_event", "error")}}, {{domxref("XMLHttpRequest/abort_event", "abort")}} - [Monitoring progress](/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest#monitoring_progress)
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/loadstart_event/index.md
--- title: "XMLHttpRequest: loadstart event" short-title: loadstart slug: Web/API/XMLHttpRequest/loadstart_event page-type: web-api-event browser-compat: api.XMLHttpRequest.loadstart_event --- {{APIRef("XMLHttpRequest API")}} The **`loadstart`** event is fired when a request has started to load data. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("loadstart", (event) => {}); onloadstart = (event) => {}; ``` ## Event type A {{domxref("ProgressEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("ProgressEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("ProgressEvent.lengthComputable", "lengthComputable")}} {{ReadOnlyInline}} - : 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. - {{domxref("ProgressEvent.loaded", "loaded")}} {{ReadOnlyInline}} - : 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. - {{domxref("ProgressEvent.total", "total")}} {{ReadOnlyInline}} - : 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. ## Examples ### Live example #### HTML ```html <div class="controls"> <input class="xhr success" type="button" name="xhr" value="Click to start XHR (success)" /> <input class="xhr error" type="button" name="xhr" value="Click to start XHR (error)" /> <input class="xhr abort" type="button" name="xhr" value="Click to start XHR (abort)" /> </div> <textarea readonly class="event-log"></textarea> ``` ```css hidden .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: 0.5rem; padding: 0.2rem; } input { width: 11rem; margin: 0.5rem; } ``` #### JavaScript ```js const xhrButtonSuccess = document.querySelector(".xhr.success"); const xhrButtonError = document.querySelector(".xhr.error"); const xhrButtonAbort = document.querySelector(".xhr.abort"); const log = document.querySelector(".event-log"); function handleEvent(e) { log.textContent = `${log.textContent}${e.type}: ${e.loaded} bytes transferred\n`; } function addListeners(xhr) { xhr.addEventListener("loadstart", handleEvent); xhr.addEventListener("load", handleEvent); xhr.addEventListener("loadend", handleEvent); xhr.addEventListener("progress", handleEvent); xhr.addEventListener("error", handleEvent); xhr.addEventListener("abort", handleEvent); } function runXHR(url) { log.textContent = ""; const xhr = new XMLHttpRequest(); addListeners(xhr); xhr.open("GET", url); xhr.send(); return xhr; } xhrButtonSuccess.addEventListener("click", () => { runXHR("example-image.jpg"); }); xhrButtonError.addEventListener("click", () => { runXHR("https://example.com/notfound.jpg"); }); xhrButtonAbort.addEventListener("click", () => { runXHR("example-image.jpg").abort(); }); ``` #### Result {{ EmbedLiveSample('Live_example', '100%', '150px') }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: {{domxref("XMLHttpRequest/loadend_event", "loadend")}}, {{domxref("XMLHttpRequest/load_event", "load")}}, {{domxref("XMLHttpRequest/progress_event", "progress")}}, {{domxref("XMLHttpRequest/error_event", "error")}}, {{domxref("XMLHttpRequest/abort_event", "abort")}} - [Monitoring progress](/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest#monitoring_progress)
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/loadend_event/index.md
--- title: "XMLHttpRequest: loadend event" short-title: loadend slug: Web/API/XMLHttpRequest/loadend_event page-type: web-api-event browser-compat: api.XMLHttpRequest.loadend_event --- {{APIRef("XMLHttpRequest API")}} The **`loadend`** event is fired when a request has completed, whether successfully (after {{domxref("XMLHttpRequest/load_event", "load")}}) or unsuccessfully (after {{domxref("XMLHttpRequest/abort_event", "abort")}} or {{domxref("XMLHttpRequest/error_event", "error")}}). ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("loadend", (event) => {}); onloadend = (event) => {}; ``` ## Event type A {{domxref("ProgressEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("ProgressEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("ProgressEvent.lengthComputable", "lengthComputable")}} {{ReadOnlyInline}} - : 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. - {{domxref("ProgressEvent.loaded", "loaded")}} {{ReadOnlyInline}} - : 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. - {{domxref("ProgressEvent.total", "total")}} {{ReadOnlyInline}} - : 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. ## Examples ### Live example #### HTML ```html <div class="controls"> <input class="xhr success" type="button" name="xhr" value="Click to start XHR (success)" /> <input class="xhr error" type="button" name="xhr" value="Click to start XHR (error)" /> <input class="xhr abort" type="button" name="xhr" value="Click to start XHR (abort)" /> </div> <textarea readonly class="event-log"></textarea> ``` ```css hidden .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: 0.5rem; padding: 0.2rem; } input { width: 11rem; margin: 0.5rem; } ``` #### JavaScript ```js const xhrButtonSuccess = document.querySelector(".xhr.success"); const xhrButtonError = document.querySelector(".xhr.error"); const xhrButtonAbort = document.querySelector(".xhr.abort"); const log = document.querySelector(".event-log"); function handleEvent(e) { log.textContent = `${log.textContent}${e.type}: ${e.loaded} bytes transferred\n`; } function addListeners(xhr) { xhr.addEventListener("loadstart", handleEvent); xhr.addEventListener("load", handleEvent); xhr.addEventListener("loadend", handleEvent); xhr.addEventListener("progress", handleEvent); xhr.addEventListener("error", handleEvent); xhr.addEventListener("abort", handleEvent); } function runXHR(url) { log.textContent = ""; const xhr = new XMLHttpRequest(); addListeners(xhr); xhr.open("GET", url); xhr.send(); return xhr; } xhrButtonSuccess.addEventListener("click", () => { runXHR( "https://raw.githubusercontent.com/mdn/content/main/files/en-us/_wikihistory.json", ); }); xhrButtonError.addEventListener("click", () => { runXHR("http://i-dont-exist"); }); xhrButtonAbort.addEventListener("click", () => { runXHR( "https://raw.githubusercontent.com/mdn/content/main/files/en-us/_wikihistory.json", ).abort(); }); ``` #### Result {{ EmbedLiveSample('Live_example', '100%', '150px') }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: {{domxref("XMLHttpRequest/loadstart_event", "loadstart")}}, {{domxref("XMLHttpRequest/load_event", "load")}}, {{domxref("XMLHttpRequest/progress_event", "progress")}}, {{domxref("XMLHttpRequest/error_event", "error")}}, {{domxref("XMLHttpRequest/abort_event", "abort")}} - [Monitoring progress](/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest#monitoring_progress)
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/upload/index.md
--- title: "XMLHttpRequest: upload property" short-title: upload slug: Web/API/XMLHttpRequest/upload page-type: web-api-instance-property browser-compat: api.XMLHttpRequest.upload --- {{APIRef("XMLHttpRequest API")}} The {{domxref("XMLHttpRequest")}} `upload` property returns an {{domxref("XMLHttpRequestUpload")}} object that can be observed to monitor an upload's progress. It is an opaque object, but because it's also an {{domxref("XMLHttpRequestEventTarget")}}, event listeners can be attached to track its process. > **Note:** Attaching event listeners to this object prevents the request from being a "simple request" and will cause a preflight request to be issued if cross-origin; see [CORS](/en-US/docs/Web/HTTP/CORS). Because of this, event listeners need to be registered before calling {{domxref("XMLHttpRequest.send", "send()")}} or upload events won't be dispatched. > **Note:** The spec also seems to indicate that event listeners should be attached after {{domxref("XMLHttpRequest.open", "open()")}}. However, browsers are buggy on this matter, and often need the listeners to be registered _before_ {{domxref("XMLHttpRequest.open", "open()")}} to work. The following events can be triggered on an upload object and used to monitor the upload: <table class="no-markdown"> <thead> <tr> <th>Event</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>{{domxref("XMLHttpRequestUpload/loadstart_event", "loadstart")}}</td> <td>The upload has begun.</td> </tr> <tr> <td>{{domxref("XMLHttpRequestUpload/progress_event", "progress")}}</td> <td> Periodically delivered to indicate the amount of progress made so far. </td> </tr> <tr> <td>{{domxref("XMLHttpRequestUpload/abort_event", "abort")}}</td> <td>The upload operation was aborted.</td> </tr> <tr> <td>{{domxref("XMLHttpRequestUpload/error_event", "error")}}</td> <td>The upload failed due to an error.</td> </tr> <tr> <td>{{domxref("XMLHttpRequestUpload/load_event", "load")}}</td> <td>The upload completed successfully.</td> </tr> <tr> <td>{{domxref("XMLHttpRequestUpload/timeout_event", "timeout")}}</td> <td> The upload timed out because a reply did not arrive within the time interval specified by the {{domxref("XMLHttpRequest.timeout")}}. </td> </tr> <tr> <td>{{domxref("XMLHttpRequestUpload/loadend_event", "loadend")}}</td> <td> The upload finished. This event does not differentiate between success or failure, and is sent at the end of the upload regardless of the outcome. Prior to this event, one of <code>load</code>, <code>error</code>, <code>abort</code>, or <code>timeout</code> will already have been delivered to indicate why the upload ended. </td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using XMLHttpRequest](/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest) - {{domxref("XMLHttpRequestUpload")}}
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/responsetype/index.md
--- title: "XMLHttpRequest: responseType property" short-title: responseType slug: Web/API/XMLHttpRequest/responseType page-type: web-api-instance-property browser-compat: api.XMLHttpRequest.responseType --- {{APIRef("XMLHttpRequest API")}} The {{domxref("XMLHttpRequest")}} property **`responseType`** is an enumerated string value specifying the type of data contained in the response. It also lets the author change the response type. If an empty string is set as the value of `responseType`, the default value of `text` is used. ## Value A string which specifies what type of data the response contains. It can take the following values: - `""` - : An empty `responseType` string is the same as `"text"`, the default type. - `"arraybuffer"` - : The {{domxref("XMLHttpRequest.response", "response")}} is a JavaScript {{jsxref("ArrayBuffer")}} containing binary data. - `"blob"` - : The `response` is a {{domxref("Blob")}} object containing the binary data. - `"document"` - : The `response` is an {{Glossary("HTML")}} {{domxref("Document")}} or {{Glossary("XML")}} {{domxref("XMLDocument")}}, as appropriate based on the MIME type of the received data. See [HTML in XMLHttpRequest](/en-US/docs/Web/API/XMLHttpRequest_API/HTML_in_XMLHttpRequest) to learn more about using XHR to fetch HTML content. - `"json"` - : The `response` is a JavaScript object created by parsing the contents of received data as {{Glossary("JSON")}}. - `"text"` - : The `response` is a text in a string. > **Note:** When setting `responseType` to a particular value, the author should make > sure that the server is actually sending a response compatible with that format. If > the server returns data that is not compatible with the `responseType` that > was set, the value of {{domxref("XMLHttpRequest.response", "response")}} will be > `null`. ### Exceptions - `InvalidAccessError` {{domxref("DOMException")}} - : An attempt was made to change the value of `responseType` on an `XMLHttpRequest` which is in synchronous mode but not in a {{domxref("Worker")}}. For additional details, see [Synchronous XHR restrictions](#synchronous_xhr_restrictions) below. ## Usage notes ### Synchronous XHR restrictions You cannot change the value of `responseType` in a synchronous `XMLHttpRequest` except when the request belongs to a {{domxref("Worker")}}. This restriction is designed in part to help ensure that synchronous operations aren't used for large transactions that block the browser's main thread, thereby bogging down the user experience. XHR requests are asynchronous by default; they are only placed in synchronous mode by passing `false` as the value of the optional `async` parameter when calling {{domxref("XMLHttpRequest.open", "open()")}}. ### Restrictions in Workers Attempts to set the value of `responseType` to `document` are ignored in a {{domxref("Worker")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using XMLHttpRequest](/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest) - [HTML in XMLHttpRequest](/en-US/docs/Web/API/XMLHttpRequest_API/HTML_in_XMLHttpRequest) - The response data: {{domxref("XMLHttpRequest.response", "response")}}, {{domxref("XMLHttpRequest.responseText", "responseText")}}, and {{domxref("XMLHttpRequest.responseXML", "responseXML")}}
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/readystate/index.md
--- title: "XMLHttpRequest: readyState property" short-title: readyState slug: Web/API/XMLHttpRequest/readyState page-type: web-api-instance-property browser-compat: api.XMLHttpRequest.readyState --- {{APIRef("XMLHttpRequest API")}} The **XMLHttpRequest.readyState** property returns the state an XMLHttpRequest client is in. An XHR client exists in one of the following states: | Value | State | Description | | ----- | ------------------ | --------------------------------------------------------------- | | `0` | `UNSENT` | Client has been created. `open()` not called yet. | | `1` | `OPENED` | `open()` has been called. | | `2` | `HEADERS_RECEIVED` | `send()` has been called, and headers and status are available. | | `3` | `LOADING` | Downloading; `responseText` holds partial data. | | `4` | `DONE` | The operation is complete. | - UNSENT - : The XMLHttpRequest client has been created, but the open() method hasn't been called yet. - OPENED - : open() method has been invoked. During this state, the request headers can be set using the [setRequestHeader()](/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader) method and the [send()](/en-US/docs/Web/API/XMLHttpRequest/send) method can be called which will initiate the fetch. - HEADERS_RECEIVED - : send() has been called, all redirects (if any) have been followed and the response headers have been received. - LOADING - : Response's body is being received. If [`responseType`](/en-US/docs/Web/API/XMLHttpRequest/responseType) is "text" or empty string, [`responseText`](/en-US/docs/Web/API/XMLHttpRequest/responseText) will have the partial text response as it loads. - DONE - : The fetch operation is complete. This could mean that either the data transfer has been completed successfully or failed. ## Example ```js const xhr = new XMLHttpRequest(); console.log("UNSENT", xhr.readyState); // readyState will be 0 xhr.open("GET", "/api", true); console.log("OPENED", xhr.readyState); // readyState will be 1 xhr.onprogress = () => { console.log("LOADING", xhr.readyState); // readyState will be 3 }; xhr.onload = () => { console.log("DONE", xhr.readyState); // readyState will be 4 }; xhr.send(null); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/timeout_event/index.md
--- title: "XMLHttpRequest: timeout event" short-title: timeout slug: Web/API/XMLHttpRequest/timeout_event page-type: web-api-event browser-compat: api.XMLHttpRequest.timeout_event --- {{APIRef("XMLHttpRequest API")}} The **`timeout`** event is fired when progression is terminated due to preset time expiring. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("timeout", (event) => {}); ontimeout = (event) => {}; ``` ## Event type A {{domxref("ProgressEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("ProgressEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("ProgressEvent.lengthComputable", "lengthComputable")}} {{ReadOnlyInline}} - : 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. - {{domxref("ProgressEvent.loaded", "loaded")}} {{ReadOnlyInline}} - : 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. - {{domxref("ProgressEvent.total", "total")}} {{ReadOnlyInline}} - : 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. ## Examples ```js const client = new XMLHttpRequest(); client.open("GET", "http://www.example.org/example.txt"); client.ontimeout = () => { console.error("Timeout!!"); }; client.send(); ``` You could also set up the event handler using the {{domxref("EventTarget/addEventListener", "addEventListener()")}} method: ```js client.addEventListener("timeout", () => { console.error("Timeout!!"); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("XMLHttpRequest")}}
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/abort/index.md
--- title: "XMLHttpRequest: abort() method" short-title: abort() slug: Web/API/XMLHttpRequest/abort page-type: web-api-instance-method browser-compat: api.XMLHttpRequest.abort --- {{APIRef("XMLHttpRequest API")}} The **`XMLHttpRequest.abort()`** method aborts the request if it has already been sent. When a request is aborted, its {{domxref("XMLHttpRequest.readyState", "readyState")}} is changed to `XMLHttpRequest.UNSENT` (0) and the request's {{domxref("XMLHttpRequest.status", "status")}} code is set to 0. ## Syntax ```js-nolint abort() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples This example begins loading content from the MDN home page, then due to some condition, aborts the transfer by calling `abort()`. ```js const xhr = new XMLHttpRequest(); const method = "GET"; const url = "https://developer.mozilla.org/"; xhr.open(method, url, true); xhr.send(); if (OH_NOES_WE_NEED_TO_CANCEL_RIGHT_NOW_OR_ELSE) { xhr.abort(); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using XMLHttpRequest](/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest)
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/load_event/index.md
--- title: "XMLHttpRequest: load event" short-title: load slug: Web/API/XMLHttpRequest/load_event page-type: web-api-event browser-compat: api.XMLHttpRequest.load_event --- {{APIRef("XMLHttpRequest API")}} The `load` event is fired when an {{domxref("XMLHttpRequest")}} transaction completes successfully. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("load", (event) => {}); onload = (event) => {}; ``` ## Event type A {{domxref("ProgressEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("ProgressEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("ProgressEvent.lengthComputable", "lengthComputable")}} {{ReadOnlyInline}} - : 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. - {{domxref("ProgressEvent.loaded", "loaded")}} {{ReadOnlyInline}} - : 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. - {{domxref("ProgressEvent.total", "total")}} {{ReadOnlyInline}} - : 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. ## Examples ### Live example #### HTML ```html <div class="controls"> <input class="xhr success" type="button" name="xhr" value="Click to start XHR (success)" /> <input class="xhr error" type="button" name="xhr" value="Click to start XHR (error)" /> <input class="xhr abort" type="button" name="xhr" value="Click to start XHR (abort)" /> </div> <textarea readonly class="event-log"></textarea> ``` ```css hidden .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: 0.5rem; padding: 0.2rem; } input { width: 11rem; margin: 0.5rem; } ``` #### JavaScript ```js const xhrButtonSuccess = document.querySelector(".xhr.success"); const xhrButtonError = document.querySelector(".xhr.error"); const xhrButtonAbort = document.querySelector(".xhr.abort"); const log = document.querySelector(".event-log"); function handleEvent(e) { log.textContent = `${log.textContent}${e.type}: ${e.loaded} bytes transferred\n`; } function addListeners(xhr) { xhr.addEventListener("loadstart", handleEvent); xhr.addEventListener("load", handleEvent); xhr.addEventListener("loadend", handleEvent); xhr.addEventListener("progress", handleEvent); xhr.addEventListener("error", handleEvent); xhr.addEventListener("abort", handleEvent); } function runXHR(url) { log.textContent = ""; const xhr = new XMLHttpRequest(); addListeners(xhr); xhr.open("GET", url); xhr.send(); return xhr; } xhrButtonSuccess.addEventListener("click", () => { runXHR("image.jpg"); }); xhrButtonError.addEventListener("click", () => { runXHR("https://somewhere.org/i-dont-exist"); }); xhrButtonAbort.addEventListener("click", () => { runXHR("image.jpg").abort(); }); ``` #### Result {{ EmbedLiveSample('Live_example', '100%', '150px') }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: {{domxref("XMLHttpRequest/loadstart_event", "loadstart")}}, {{domxref("XMLHttpRequest/loadend_event", "loadend")}}, {{domxref("XMLHttpRequest/progress_event", "progress")}}, {{domxref("XMLHttpRequest/error_event", "error")}}, {{domxref("XMLHttpRequest/abort_event", "abort")}} - [Monitoring progress](/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest#monitoring_progress)
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/getallresponseheaders/index.md
--- title: "XMLHttpRequest: getAllResponseHeaders() method" short-title: getAllResponseHeaders() slug: Web/API/XMLHttpRequest/getAllResponseHeaders page-type: web-api-instance-method browser-compat: api.XMLHttpRequest.getAllResponseHeaders --- {{APIRef("XMLHttpRequest API")}} The {{domxref("XMLHttpRequest")}} method **`getAllResponseHeaders()`** returns all the response headers, separated by {{Glossary('CRLF')}}, as a string, or returns `null` if no response has been received. If a network error happened, an empty string is returned. > **Note:** For multipart requests, this returns the headers from the > _current_ part of the request, not from the original channel. ## Syntax ```js-nolint getAllResponseHeaders() ``` ### Parameters None. ### Return value A string representing all of the response's headers (except those whose field name is `Set-Cookie`) separated by {{Glossary('CRLF')}}, or `null` if no response has been received. If a network error happened, an empty string is returned. An example of what a raw header string looks like: ```http date: Fri, 08 Dec 2017 21:04:30 GMT\r\n content-encoding: gzip\r\n x-content-type-options: nosniff\r\n server: meinheld/0.6.1\r\n x-frame-options: DENY\r\n content-type: text/html; charset=utf-8\r\n connection: keep-alive\r\n strict-transport-security: max-age=63072000\r\n vary: Cookie, Accept-Encoding\r\n content-length: 6502\r\n x-xss-protection: 1; mode=block\r\n ``` Each line is terminated by both carriage return and line feed characters (`\r\n`). These are essentially delimiters separating each of the headers. > **Note:** In modern browsers, the header names are returned in all lower > case, as per the latest spec. ## Examples This example examines the headers in the request's {{domxref("XMLHttpRequest/readystatechange_event", "readystatechange")}} event. The code shows how to obtain the raw header string, as well as how to convert it into an array of individual headers and then how to take that array and create a mapping of header names to their values. ```js const request = new XMLHttpRequest(); request.open("GET", "foo.txt", true); request.send(); request.onreadystatechange = () => { if (request.readyState === this.HEADERS_RECEIVED) { // Get the raw header string const headers = request.getAllResponseHeaders(); // Convert the header string into an array // of individual headers const arr = headers.trim().split(/[\r\n]+/); // Create a map of header names to values const headerMap = {}; arr.forEach((line) => { const parts = line.split(": "); const header = parts.shift(); const value = parts.join(": "); headerMap[header] = value; }); } }; ``` Once this is done, you can, for example: ```js const contentType = headerMap["content-type"]; ``` This obtains the value of the {{httpheader("Content-Type")}} header into the variable `contentType`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using XMLHttpRequest](/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest) - Setting request headers: {{domxref("XMLHttpRequest.setRequestHeader", "setRequestHeader()")}}
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/mozbackgroundrequest/index.md
--- title: "XMLHttpRequest: mozBackgroundRequest property" short-title: mozBackgroundRequest slug: Web/API/XMLHttpRequest/mozBackgroundRequest page-type: web-api-instance-property status: - non-standard --- {{APIRef("XMLHttpRequest API")}} > **Note:** This method is not available from Web content. It requires elevated privileges to access. **`XMLHttpRequest.mozBackgroundRequest`** is a Boolean, indicating if the object represents a background service request. If `true`, no load group is associated with the request, with security dialogs prevented from being shown to the user. In cases in where a security dialog (such as authentication or a bad certificate notification) would normally be shown, this request fails instead. > **Note:** This property must be set before calling `open()`.
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/xmlhttprequest/index.md
--- title: "XMLHttpRequest: XMLHttpRequest() constructor" short-title: XMLHttpRequest() slug: Web/API/XMLHttpRequest/XMLHttpRequest page-type: web-api-constructor browser-compat: api.XMLHttpRequest.XMLHttpRequest --- {{APIRef("XMLHttpRequest API")}} The **`XMLHttpRequest()`** constructor creates a new {{domxref("XMLHttpRequest")}}. ## Syntax ```js-nolint new XMLHttpRequest() ``` ### Parameters None. ### Return value A new {{domxref("XMLHttpRequest")}} object. The object must be prepared by at least calling {{domxref("XMLHttpRequest.open", "open()")}} to initialize it before calling {{domxref("XMLHttpRequest.send", "send()")}} to send the request to the server. ## Non-standard Firefox syntax Firefox 16 added a non-standard parameter to the constructor that can enable anonymous mode (see [Firefox bug 692677](https://bugzil.la/692677)). Setting the `mozAnon` flag to `true` effectively resembles the [`AnonXMLHttpRequest()`](https://www.w3.org/TR/2012/WD-XMLHttpRequest-20120117/#dom-anonxmlhttprequest) constructor described in older versions of the XMLHttpRequest specification. ```js const request = new XMLHttpRequest(paramsDictionary); ``` ### Parameters (non-standard) - `objParameters` - : One flag you can set: - `mozAnon` - : Boolean: Setting this flag to `true` will cause the browser not to expose the {{Glossary("origin")}} and [user credentials](https://www.w3.org/TR/2012/WD-XMLHttpRequest-20120117/#user-credentials) when fetching resources. Most important, this means that {{Glossary("Cookie", "cookies")}} will not be sent unless explicitly added using setRequestHeader. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using XMLHttpRequest](/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest) - [HTML in XMLHttpRequest](/en-US/docs/Web/API/XMLHttpRequest_API/HTML_in_XMLHttpRequest)
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/error_event/index.md
--- title: "XMLHttpRequest: error event" short-title: error slug: Web/API/XMLHttpRequest/error_event page-type: web-api-event browser-compat: api.XMLHttpRequest.error_event --- {{APIRef("XMLHttpRequest API")}} The `error` event is fired when the request encountered an error. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("error", (event) => {}); onerror = (event) => {}; ``` ## Event type A {{domxref("ProgressEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("ProgressEvent")}} ## Event properties _In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._ - {{domxref("ProgressEvent.lengthComputable", "lengthComputable")}} {{ReadOnlyInline}} - : 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. - {{domxref("ProgressEvent.loaded", "loaded")}} {{ReadOnlyInline}} - : 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. - {{domxref("ProgressEvent.total", "total")}} {{ReadOnlyInline}} - : 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. ## Examples ### Live example #### HTML ```html <div class="controls"> <input class="xhr success" type="button" name="xhr" value="Click to start XHR (success)" /> <input class="xhr error" type="button" name="xhr" value="Click to start XHR (error)" /> <input class="xhr abort" type="button" name="xhr" value="Click to start XHR (abort)" /> </div> <textarea readonly class="event-log"></textarea> ``` ```css hidden .event-log { width: 25rem; height: 4rem; border: 1px solid black; margin: 0.5rem; padding: 0.2rem; } input { width: 11rem; margin: 0.5rem; } ``` #### JavaScript ```js const xhrButtonSuccess = document.querySelector(".xhr.success"); const xhrButtonError = document.querySelector(".xhr.error"); const xhrButtonAbort = document.querySelector(".xhr.abort"); const log = document.querySelector(".event-log"); function handleEvent(e) { log.textContent = `${log.textContent}${e.type}: ${e.loaded} bytes transferred\n`; } function addListeners(xhr) { xhr.addEventListener("loadstart", handleEvent); xhr.addEventListener("load", handleEvent); xhr.addEventListener("loadend", handleEvent); xhr.addEventListener("progress", handleEvent); xhr.addEventListener("error", handleEvent); xhr.addEventListener("abort", handleEvent); } function runXHR(url) { log.textContent = ""; const xhr = new XMLHttpRequest(); addListeners(xhr); xhr.open("GET", url); xhr.send(); return xhr; } xhrButtonSuccess.addEventListener("click", () => { runXHR("example-image.jpg"); }); xhrButtonError.addEventListener("click", () => { runXHR("https://example.com/notfound.jpg"); }); xhrButtonAbort.addEventListener("click", () => { runXHR("example-image.jpg").abort(); }); ``` #### Result {{ EmbedLiveSample('Live_example', '100%', '150px') }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: {{domxref("XMLHttpRequest/loadstart_event", "loadstart")}}, {{domxref("XMLHttpRequest/load_event", "load")}}, {{domxref("XMLHttpRequest/progress_event", "progress")}}, {{domxref("XMLHttpRequest/loadend_event", "loadend")}}, {{domxref("XMLHttpRequest/abort_event", "abort")}} - [Monitoring progress](/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest#monitoring_progress)
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/overridemimetype/index.md
--- title: "XMLHttpRequest: overrideMimeType() method" short-title: overrideMimeType() slug: Web/API/XMLHttpRequest/overrideMimeType page-type: web-api-instance-method browser-compat: api.XMLHttpRequest.overrideMimeType --- {{APIRef("XMLHttpRequest API")}} The {{domxref("XMLHttpRequest")}} method **`overrideMimeType()`** specifies a MIME type other than the one provided by the server to be used instead when interpreting the data being transferred in a request. This may be used, for example, to force a stream to be treated and parsed as `"text/xml"`, even if the server does not report it as such. This method must be called before calling {{domxref("XMLHttpRequest.send", "send()")}}. ## Syntax ```js-nolint overrideMimeType(mimeType) ``` ### Parameters - `mimeType` - : A string specifying the MIME type to use instead of the one specified by the server. If the server doesn't specify a type, `XMLHttpRequest` assumes `"text/xml"`. ### Return value None ({{jsxref("undefined")}}). ## Examples This example specifies a MIME type of `"text/plain"`, overriding the server's stated type for the data being received. > **Note:** If the server doesn't provide a > [`Content-Type`](/en-US/docs/Web/HTTP/Headers/Content-Type) > header, {{domxref("XMLHttpRequest")}} assumes that the MIME type is > `"text/xml"`. If the content isn't valid XML, an "XML Parsing Error: not > well-formed" error occurs. You can avoid this by calling > `overrideMimeType()` to specify a different type. ```js // Interpret the received data as plain text req = new XMLHttpRequest(); req.overrideMimeType("text/plain"); req.addEventListener("load", callback, false); req.open("get", url); req.send(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using XMLHttpRequest](/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest) - {{domxref("XMLHttpRequest.responseType")}}
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/statustext/index.md
--- title: "XMLHttpRequest: statusText property" short-title: statusText slug: Web/API/XMLHttpRequest/statusText page-type: web-api-instance-property browser-compat: api.XMLHttpRequest.statusText --- {{APIRef("XMLHttpRequest API")}} The read-only **`XMLHttpRequest.statusText`** property returns a string containing the response's status message as returned by the HTTP server. Unlike [`XMLHTTPRequest.status`](/en-US/docs/Web/API/XMLHttpRequest/status) which indicates a numerical status code, this property contains the _text_ of the response status, such as "OK" or "Not Found". If the request's [`readyState`](/en-US/docs/Web/API/XMLHttpRequest/readyState) is in `UNSENT` or `OPENED` state, the value of `statusText` will be an empty string. If the server response doesn't explicitly specify a status text, `statusText` will assume the default value "OK". > **Note:** Responses over an HTTP/2 connection will always have an empty string as status message as HTTP/2 does not support them. ## Value A string. ## Examples ```js const xhr = new XMLHttpRequest(); console.log("0 UNSENT", xhr.statusText); xhr.open("GET", "/server", true); console.log("1 OPENED", xhr.statusText); xhr.onprogress = () => { console.log("3 LOADING", xhr.statusText); }; xhr.onload = () => { console.log("4 DONE", xhr.statusText); }; xhr.send(null); /** * Outputs the following: * * 0 UNSENT * 1 OPENED * 3 LOADING OK * 4 DONE OK */ ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - List of [HTTP status](/en-US/docs/Web/HTTP/Status) - [HTTP](/en-US/docs/Web/HTTP) - [WHATWG Fetch Living Standard](https://fetch.spec.whatwg.org/#concept-response-status-message)
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/open/index.md
--- title: "XMLHttpRequest: open() method" short-title: open() slug: Web/API/XMLHttpRequest/open page-type: web-api-instance-method browser-compat: api.XMLHttpRequest.open --- {{APIRef("XMLHttpRequest API")}} The {{domxref("XMLHttpRequest")}} method **`open()`** initializes a newly-created request, or re-initializes an existing one. > **Note:** Calling this method for an already active request > (one for which `open()` has already been called) is the equivalent of calling > {{domxref("XMLHttpRequest.abort", "abort()")}}. ## Syntax ```js-nolint open(method, url) open(method, url, async) open(method, url, async, user) open(method, url, async, user, password) ``` ### Parameters - `method` - : The [HTTP request method](/en-US/docs/Web/HTTP/Methods) to use, such as `"GET"`, `"POST"`, `"PUT"`, `"DELETE"`, etc. Ignored for non-HTTP(S) URLs. - `url` - : A string or any other object with a {{Glossary("stringifier")}} — including a {{domxref("URL")}} object — that provides the URL of the resource to send the request to. - `async` {{optional_inline}} - : An optional Boolean parameter, defaulting to `true`, indicating whether or not to perform the operation asynchronously. If this value is `false`, the `send()` method does not return until the response is received. If `true`, notification of a completed transaction is provided using event listeners. This _must_ be true if the `multipart` attribute is `true`, or an exception will be thrown. > **Note:** Synchronous requests on the main thread can > be easily disruptive to the user experience and should be avoided; in fact, many > browsers have deprecated synchronous XHR support on the main thread entirely. > Synchronous requests are permitted in {{domxref("Worker")}}s. - `user` {{optional_inline}} - : The optional user name to use for authentication purposes; by default, this is the `null` value. - `password` {{optional_inline}} - : The optional password to use for authentication purposes; by default, this is the `null` value. ### Return value None ({{jsxref("undefined")}}). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using XMLHttpRequest](/en-US/docs/Web/API/XMLHttpRequest_API/Using_XMLHttpRequest) - Related {{domxref("XMLHttpRequest")}} methods: {{domxref("XMLHttpRequest.setRequestHeader", "setRequestHeader()")}}, {{domxref("XMLHttpRequest.send", "send()")}}, and {{domxref("XMLHttpRequest.abort", "abort()")}}
0
data/mdn-content/files/en-us/web/api/xmlhttprequest
data/mdn-content/files/en-us/web/api/xmlhttprequest/responseurl/index.md
--- title: "XMLHttpRequest: responseURL property" short-title: responseURL slug: Web/API/XMLHttpRequest/responseURL page-type: web-api-instance-property browser-compat: api.XMLHttpRequest.responseURL --- {{APIRef("XMLHttpRequest API")}} The read-only **`XMLHttpRequest.responseURL`** property returns the serialized URL of the response or the empty string if the URL is `null`. If the URL is returned, any URL fragment present in the URL will be stripped away. The value of `responseURL` will be the final URL obtained after any redirects. ## Example ```js const xhr = new XMLHttpRequest(); xhr.open("GET", "http://example.com/test", true); xhr.onload = () => { console.log(xhr.responseURL); // http://example.com/test }; xhr.send(null); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/csstranslate/index.md
--- title: CSSTranslate slug: Web/API/CSSTranslate page-type: web-api-interface browser-compat: api.CSSTranslate --- {{APIRef("CSS Typed Object Model API")}} The **`CSSTranslate`** interface of the {{domxref('CSS_Object_Model#css_typed_object_model','','',' ')}} represents the [translate()](/en-US/docs/Web/CSS/transform-function/translate) value of the individual {{CSSXRef('transform')}} property in CSS. It inherits properties and methods from its parent {{domxref('CSSTransformValue')}}. {{InheritanceDiagram}} ## Constructor - {{domxref("CSSTranslate.CSSTranslate", "CSSTranslate()")}} - : Creates a new `CSSTranslate` object. ## Instance properties - {{domxref('CSSTranslate.x','x')}} - : Returns or sets the x-axis value. - {{domxref('CSSTranslate.y','y')}} - : Returns or sets the y-axis value. - {{domxref('CSSTranslate.z','z')}} - : Returns or sets the z-axis value. ## Examples To do. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/csstranslate
data/mdn-content/files/en-us/web/api/csstranslate/z/index.md
--- title: "CSSTranslate: z property" short-title: z slug: Web/API/CSSTranslate/z page-type: web-api-instance-property browser-compat: api.CSSTranslate.z --- {{APIRef("CSS Typed OM")}} The **`z`** property of the {{domxref("CSSTranslate")}} interface representing the z-component of the translating vector. A positive value moves the element towards the viewer, and a negative value farther away. If this value is present then the transform is a 3D transform and the `is2D` property will be set to false. ## Value A {{cssxref('length')}}. ## Examples To Do ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/csstranslate
data/mdn-content/files/en-us/web/api/csstranslate/y/index.md
--- title: "CSSTranslate: y property" short-title: "y" slug: Web/API/CSSTranslate/y page-type: web-api-instance-property browser-compat: api.CSSTranslate.y --- {{APIRef("CSS Typed OM")}} The **`y`** property of the {{domxref("CSSTranslate")}} interface gets and sets the ordinate or y-axis of the translating vector. ## Value A {{cssxref('length-percentage')}} ## Examples To Do ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/csstranslate
data/mdn-content/files/en-us/web/api/csstranslate/x/index.md
--- title: "CSSTranslate: x property" short-title: x slug: Web/API/CSSTranslate/x page-type: web-api-instance-property browser-compat: api.CSSTranslate.x --- {{APIRef("CSS Typed OM")}} The **`x`** property of the {{domxref("CSSTranslate")}} interface gets and sets the abscissa or x-axis of the translating vector. ## Value A {{cssxref('length-percentage')}} ## Examples To Do ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/csstranslate
data/mdn-content/files/en-us/web/api/csstranslate/csstranslate/index.md
--- title: "CSSTranslate: CSSTranslate() constructor" short-title: CSSTranslate() slug: Web/API/CSSTranslate/CSSTranslate page-type: web-api-constructor browser-compat: api.CSSTranslate.CSSTranslate --- {{APIRef("CSS Typed OM")}} The **`CSSTranslate()`** constructor creates a new {{domxref("CSSTranslate")}} object representing the [translate()](/en-US/docs/Web/CSS/transform-function/translate) value of the individual {{CSSXref('transform')}} property in CSS. ## Syntax ```js-nolint new CSSTranslate(x, y) new CSSTranslate(x, y, z) ``` ### Parameters - {{domxref('CSSTranslate.x','x')}} - : A value for the x-axis of the {{domxref('CSSTranslate')}} object to be constructed. This must be a {{cssxref('length-percentage')}}. - {{domxref('CSSTranslate.y','y')}} - : A value for the y-axis of the {{domxref('CSSTranslate')}} object to be constructed. This must be a {{cssxref('length-percentage')}}. - {{domxref('CSSTranslate.z','z')}} {{optional_inline}} - : A value for the z-axis of the {{domxref('CSSTranslate')}} object to be constructed. This must be a {{cssxref('length')}}. If a value is passed for the `z-axis` this is a 3d transform. The value of `is2D` will be set to false. ### Exceptions - [`TypeError`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) - : Raised if the value of `CSSTranslate.x` or `CSSTranslate.y` is not a {{cssxref('length-percentage')}}. - [`TypeError`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError) - : Raised if the value of `CSSTranslate.z` exists but is not a {{cssxref('length')}}. ## Examples To do ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/navigation/index.md
--- title: Navigation slug: Web/API/Navigation page-type: web-api-interface status: - experimental browser-compat: api.Navigation --- {{APIRef("Navigation API")}}{{SeeCompatTable}} The **`Navigation`** interface of the {{domxref("Navigation API", "Navigation API", "", "nocode")}} 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 {{domxref("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 {{htmlelement("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 {{domxref("History API", "History API", "", "nocode")}}. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent, {{DOMxRef("EventTarget")}}._ - {{domxref("Navigation.canGoBack", "canGoBack")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns `true` if it is possible to navigate backwards in the navigation history (i.e. the {{domxref("Navigation.currentEntry", "currentEntry")}} is not the first one in the history entry list), and `false` if it is not. - {{domxref("Navigation.canGoForward", "canGoForward")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns `true` if it is possible to navigate forwards in the navigation history (i.e. the {{domxref("Navigation.currentEntry", "currentEntry")}} is not the last one in the history entry list), and `false` if it is not. - {{domxref("Navigation.currentEntry", "currentEntry")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a {{domxref("NavigationHistoryEntry")}} object representing the location the user is currently navigated to right now. - {{domxref("Navigation.transition", "transition")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns a {{domxref("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, {{DOMxRef("EventTarget")}}._ - {{domxref("Navigation.back", "back()")}} {{Experimental_Inline}} - : Navigates backwards by one entry in the navigation history. - {{domxref("Navigation.entries", "entries()")}} {{Experimental_Inline}} - : Returns an array of {{domxref("NavigationHistoryEntry")}} objects representing all existing history entries. - {{domxref("Navigation.forward", "forward()")}} {{Experimental_Inline}} - : Navigates forwards by one entry in the navigation history. - {{domxref("Navigation.navigate", "navigate()")}} {{Experimental_Inline}} - : Navigates to a specific URL, updating any provided state in the history entries list. - {{domxref("Navigation.reload", "reload()")}} {{Experimental_Inline}} - : Reloads the current URL, updating any provided state in the history entries list. - {{domxref("Navigation.traverseTo", "traverseTo()")}} {{Experimental_Inline}} - : Navigates to a specific {{domxref("NavigationHistoryEntry")}} identified by {{domxref("NavigationHistoryEntry.key", "key")}}. - {{domxref("Navigation.updateCurrentEntry", "updateCurrentEntry()")}} {{Experimental_Inline}} - : Updates the state of the {{domxref("Navigation.currentEntry","currentEntry")}}; used in cases where the state change will be independent from a navigation or reload. ## Events - {{domxref("Navigation/currententrychange_event", "currententrychange")}} {{Experimental_Inline}} - : Fired when the {{domxref("Navigation.currentEntry")}} has changed. - {{domxref("Navigation/navigate_event", "navigate")}} {{Experimental_Inline}} - : Fired when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated, allowing you to intercept as required. - {{domxref("Navigation/navigateerror_event", "navigateerror")}} {{Experimental_Inline}} - : Fired when a navigation fails. - {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} {{Experimental_Inline}} - : Fired when a successful navigation has finished. ## Examples ### Moving forwards and backwards in the history ```js 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 ```js // 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 ```js navigation.navigate(url, { state: newState }); ``` Or ```js navigation.reload({ state: newState }); ``` Or if the state is independent from a navigation or reload: ```js navigation.updateCurrentEntry({ state: newState }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## 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/)
0
data/mdn-content/files/en-us/web/api/navigation
data/mdn-content/files/en-us/web/api/navigation/navigatesuccess_event/index.md
--- title: "Navigation: navigatesuccess event" short-title: navigatesuccess slug: Web/API/Navigation/navigatesuccess_event page-type: web-api-event status: - experimental browser-compat: api.Navigation.navigatesuccess_event --- {{APIRef("Navigation API")}}{{SeeCompatTable}} The **`navigatesuccess`** event of the {{domxref("Navigation")}} interface is fired when a successful navigation has finished. In the case of an intercepted navigation, this would occur after any promises returned by your {{domxref("NavigateEvent.intercept", "intercept()")}} handler are fulfilled. The {{domxref("NavigationTransition.finished")}} promise will also fulfill at the same time. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("navigatesuccess", (event) => {}); onnavigatesuccess = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples You might deal with a successful navigation by hiding a previously displayed progress indicator, like this: ```js navigation.addEventListener("navigatesuccess", (event) => { loadingIndicator.hidden = true; }); ``` Or you might show an error message on failure: ```js navigation.addEventListener("navigateerror", (event) => { loadingIndicator.hidden = true; // also hide indicator showMessage(`Failed to load page: ${event.message}`); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## 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/)
0
data/mdn-content/files/en-us/web/api/navigation
data/mdn-content/files/en-us/web/api/navigation/currententrychange_event/index.md
--- title: "Navigation: currententrychange event" short-title: currententrychange slug: Web/API/Navigation/currententrychange_event page-type: web-api-event status: - experimental browser-compat: api.Navigation.currententrychange_event --- {{APIRef("Navigation API")}}{{SeeCompatTable}} The **`currententrychange`** event of the {{domxref("Navigation")}} interface is fired when the {{domxref("Navigation.currentEntry")}} has changed. This event will fire for: - Same-document navigations (e.g. {{domxref("Navigation.back", "back()")}} or {{domxref("Navigation.traverseTo", "traverseTo()")}}). - Replacements (i.e. a {{domxref("Navigation.navigate", "navigate()")}} call with `history` set to `replace`). - Other calls that change the entry's state (e.g. {{domxref("Navigation.updateCurrentEntry", "updateCurrentEntry()")}}, or the {{domxref("History API", "History API", "", "nocode")}}'s {{domxref("History.replaceState()")}}). This event fires after the navigation is committed, meaning that the visible URL has changed and the {{domxref("NavigationHistoryEntry")}} update has occurred. It is useful for migrating from usage of older API features like the {{domxref("Window/hashchange_event", "hashchange")}} or {{domxref("Window/popstate_event", "popstate")}} events. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("currententrychange", (event) => {}); oncurrententrychange = (event) => {}; ``` ## Event type A {{domxref("NavigationCurrentEntryChangeEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("NavigationCurrentEntryChangeEvent")}} ## Examples Navigation data reporting: ```js navigation.addEventListener("currententrychange", () => { const data = navigation.currentEntry.getState(); submitAnalyticsData(data.analytics); }); ``` Setting up a per-entry event: ```js navigation.addEventListener("currententrychange", () => { navigation.currentEntry.addEventListener("dispose", genericDisposeHandler); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## 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/)
0
data/mdn-content/files/en-us/web/api/navigation
data/mdn-content/files/en-us/web/api/navigation/currententry/index.md
--- title: "Navigation: currentEntry property" short-title: currentEntry slug: Web/API/Navigation/currentEntry page-type: web-api-instance-property status: - experimental browser-compat: api.Navigation.currentEntry --- {{APIRef("Navigation API")}}{{SeeCompatTable}} The **`currentEntry`** read-only property of the {{domxref("Navigation")}} interface returns a {{domxref("NavigationHistoryEntry")}} object representing the location the user is currently navigated to right now. ## Value A {{domxref("NavigationHistoryEntry")}} object. ## Examples ```js 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 {{Specifications}} ## Browser compatibility {{Compat}} ## 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/)
0
data/mdn-content/files/en-us/web/api/navigation
data/mdn-content/files/en-us/web/api/navigation/navigate_event/index.md
--- title: "Navigation: navigate event" short-title: navigate slug: Web/API/Navigation/navigate_event page-type: web-api-event status: - experimental browser-compat: api.Navigation.navigate_event --- {{APIRef("Navigation API")}}{{SeeCompatTable}} The **`navigate`** event of the {{domxref("Navigation")}} interface is fired when [any type of navigation](https://github.com/WICG/navigation-api#appendix-types-of-navigations) is initiated, allowing you to intercept as required. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("navigate", (event) => {}); onnavigate = (event) => {}; ``` ## Event type A {{domxref("NavigateEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("NavigateEvent")}} ## Examples ### Handling a navigation using `intercept()` ```js 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 `event.preventDefault()`, perform the appropriate {{domxref("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 {{domxref("NavigateEvent.scroll", "scroll()")}} call between the two. ```js 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 {{Specifications}} ## Browser compatibility {{Compat}} ## 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/)
0
data/mdn-content/files/en-us/web/api/navigation
data/mdn-content/files/en-us/web/api/navigation/reload/index.md
--- title: "Navigation: reload() method" short-title: reload() slug: Web/API/Navigation/reload page-type: web-api-instance-method status: - experimental browser-compat: api.Navigation.reload --- {{APIRef("Navigation API")}}{{SeeCompatTable}} The **`reload()`** method of the {{domxref("Navigation")}} interface reloads the current URL, updating any provided state in the history entries list. ## Syntax ```js-nolint navigate(options) ``` ### Parameters - `options` {{optional_inline}} - : An options object containing the following properties: - `state` {{optional_inline}} - : Developer-defined information to be stored in the associated {{domxref("NavigationHistoryEntry")}} once the navigation is complete, retrievable via {{domxref("NavigationHistoryEntry.getState", "getState()")}}. This can be any data type. You might, for example, wish to store a page visit count for analytics purposes, or store UI state details so the view can be shown exactly as the user last left it. Any data stored in `state` must be [structured-cloneable](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). - `info` {{optional_inline}} - : Developer-defined information to be passed along to the {{domxref("Navigation/navigate_event", "navigate")}} event, made available in {{domxref("NavigateEvent.info")}}. This can be any data type. You might, for example, wish to display newly-navigated content with a different animation depending on how it was navigated to (swipe left, swipe right, or go home). A string indicating which animation to use could be passed in as `info`. ### Return value An object with the following properties: - `committed` - : A {{jsxref("Promise")}} which will fulfill when the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. - `finished` - : A {{jsxref("Promise")}} which will fulfill when all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. Either one of these promises rejects if the navigation has failed for some reason. ### Exceptions - `DataCloneError` {{domxref("DOMException")}} - : Thrown if the `state` parameter had values included in it that are not structured-cloneable. ## Examples ### Using info and state ```js async function handleReload() { await navigation.reload({ info: { animation: "fade-in" }, state: { infoPaneOpen: true }, }).finished; // Update application state // ... } ``` Reload page and add a new state item: ```js async function handleReload() { await navigation.reload({ state: { ...navigation.currentEntry.getState(), newState: 3 }, }).finished; // Update application state // ... } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## 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/)
0
data/mdn-content/files/en-us/web/api/navigation
data/mdn-content/files/en-us/web/api/navigation/navigateerror_event/index.md
--- title: "Navigation: navigateerror event" short-title: navigateerror slug: Web/API/Navigation/navigateerror_event page-type: web-api-event status: - experimental browser-compat: api.Navigation.navigateerror_event --- {{APIRef("Navigation API")}}{{SeeCompatTable}} The **`navigateerror`** event of the {{domxref("Navigation")}} interface is fired when a navigation fails. For example, if the network is down, any {{domxref("fetch()")}} method invoked to handle a navigation will fail, and the error will be routed to `navigateerror`. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("navigateerror", (event) => {}); onnavigateerror = (event) => {}; ``` ## Event type An {{domxref("ErrorEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("ErrorEvent")}} ## Examples You might deal with a successful navigation by hiding a previously displayed progress indicator, like this: ```js navigation.addEventListener("navigatesuccess", (event) => { loadingIndicator.hidden = true; }); ``` Or you might show an error message on failure: ```js navigation.addEventListener("navigateerror", (event) => { loadingIndicator.hidden = true; // also hide indicator showMessage(`Failed to load page: ${event.message}`); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## 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/)
0
data/mdn-content/files/en-us/web/api/navigation
data/mdn-content/files/en-us/web/api/navigation/cangoforward/index.md
--- title: "Navigation: canGoForward property" short-title: canGoForward slug: Web/API/Navigation/canGoForward page-type: web-api-instance-property status: - experimental browser-compat: api.Navigation.canGoForward --- {{APIRef("Navigation API")}}{{SeeCompatTable}} The **`canGoForward`** read-only property of the {{domxref("Navigation")}} interface returns `true` if it is possible to navigate forwards in the navigation history (i.e. the {{domxref("Navigation.currentEntry", "currentEntry")}} is not the last one in the history entry list), and `false` if it is not. ## Value A boolean value: `true` if it is possible to navigate forwards in the navigation history, `false` otherwise. ## Examples ```js 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"); } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## 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/)
0
data/mdn-content/files/en-us/web/api/navigation
data/mdn-content/files/en-us/web/api/navigation/updatecurrententry/index.md
--- title: "Navigation: updateCurrentEntry() method" short-title: updateCurrentEntry() slug: Web/API/Navigation/updateCurrentEntry page-type: web-api-instance-method status: - experimental browser-compat: api.Navigation.updateCurrentEntry --- {{APIRef("Navigation API")}}{{SeeCompatTable}} The **`updateCurrentEntry()`** method of the {{domxref("Navigation")}} interface updates the `state` of the {{domxref("Navigation.currentEntry","currentEntry")}}; used in cases where the state change will be independent of a navigation or reload. ## Syntax ```js-nolint updateCurrentEntry() updateCurrentEntry(options) ``` ### Parameters - `options` {{optional_inline}} - : An options object containing the following properties: - `state` - : Developer-defined information to be stored in the associated {{domxref("NavigationHistoryEntry")}} once the navigation is complete, retrievable via {{domxref("NavigationHistoryEntry.getState", "getState()")}}. This can be any data type. You might, for example, wish to store a page visit count for analytics purposes, or store UI state details so the view can be shown exactly as the user last left it. Any data stored in `state` must be [structured-cloneable](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). ### Return value None (`undefined`). ### Exceptions - `DataCloneError` {{domxref("DOMException")}} - : Thrown if the `state` parameter had values included in it that are not structured-cloneable. - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the {{domxref("Navigation.currentEntry")}} is `null`, i.e. there is no current history entry. This could occur for example if the current page is `about:blank`. ## Examples You could use something like the following to update the open/closed state of a {{htmlelement("details")}} element so that the state can be restored when reloading the page or navigating back from somewhere else. ```js detailsElem.addEventListener("toggle", () => { navigation.updateCurrentEntry({ state: { detailOpen: detailsElem.open } }); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## 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/)
0
data/mdn-content/files/en-us/web/api/navigation
data/mdn-content/files/en-us/web/api/navigation/back/index.md
--- title: "Navigation: back() method" short-title: back() slug: Web/API/Navigation/back page-type: web-api-instance-method status: - experimental browser-compat: api.Navigation.back --- {{APIRef("Navigation API")}}{{SeeCompatTable}} The **`back()`** method of the {{domxref("Navigation")}} interface navigates backwards by one entry in the navigation history. ## Syntax ```js-nolint back(options) ``` ### Parameters - `options` {{optional_inline}} - : An options object containing the following properties: - `info` {{optional_inline}} - : Developer-defined information to be passed along to the {{domxref("Navigation/navigate_event", "navigate")}} event, made available in {{domxref("NavigateEvent.info")}}. This can be any data type. You might, for example, wish to display newly-navigated content with a different animation depending on how it was navigated to (swipe left, swipe right, or go home). A string indicating which animation to use could be passed in as `info`. ### Return value An object with the following properties: - `committed` - : A {{jsxref("Promise")}} which will fulfill when the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. - `finished` - : A {{jsxref("Promise")}} which will fulfill when all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. Either one of these promises rejects if the navigation has failed for some reason. ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the {{domxref("Navigation.currentEntry")}}'s {{domxref("NavigationHistoryEntry.index")}} value is -1 or 0, i.e. either the current {{domxref("Document")}} is not yet active, or the current history entry is the first one in the history, meaning that backwards navigation is not possible, or if the current {{domxref("Document")}} is unloading. ## Examples ```js 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"); } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## 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/)
0
data/mdn-content/files/en-us/web/api/navigation
data/mdn-content/files/en-us/web/api/navigation/transition/index.md
--- title: "Navigation: transition property" short-title: transition slug: Web/API/Navigation/transition page-type: web-api-instance-property status: - experimental browser-compat: api.Navigation.transition --- {{APIRef("Navigation API")}}{{SeeCompatTable}} The **`transition`** read-only property of the {{domxref("Navigation")}} interface returns a {{domxref("NavigationTransition")}} object representing the status of an in-progress navigation, which can be used to track it. ## Value A {{domxref("NavigationTransition")}} object, or `null` if no navigation is currently in progress. ## Examples ```js async function handleTransition() { if (navigation.transition) { showLoadingSpinner(); await navigation.transition.finished; hideLoadingSpinner(); } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## 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/)
0
data/mdn-content/files/en-us/web/api/navigation
data/mdn-content/files/en-us/web/api/navigation/forward/index.md
--- title: "Navigation: forward() method" short-title: forward() slug: Web/API/Navigation/forward page-type: web-api-instance-method status: - experimental browser-compat: api.Navigation.forward --- {{APIRef("Navigation API")}}{{SeeCompatTable}} The **`forward()`** method of the {{domxref("Navigation")}} interface navigates forwards by one entry in the navigation history. ## Syntax ```js-nolint forward(options) ``` ### Parameters - `options` {{optional_inline}} - : An options object containing the following properties: - `info` {{optional_inline}} - : Developer-defined information to be passed along to the {{domxref("Navigation/navigate_event", "navigate")}} event, made available in {{domxref("NavigateEvent.info")}}. This can be any data type. You might, for example, wish to display newly-navigated content with a different animation depending on how it was navigated to (swipe left, swipe right, or go home). A string indicating which animation to use could be passed in as `info`. ### Return value An object with the following properties: - `committed` - : A {{jsxref("Promise")}} which will fulfill when the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. - `finished` - : A {{jsxref("Promise")}} which will fulfill when all promises returned by the {{domxref("NavigateEvent.intercept()")}} handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. Either one of these promises rejects if the navigation has failed for some reason. ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the {{domxref("Navigation.currentEntry")}}'s {{domxref("NavigationHistoryEntry.index")}} value is -1 or {{domxref("Navigation.entries", "navigation.entries().length - 1")}}, i.e. either the current {{domxref("Document")}} is not yet active, or the current history entry is the last one in the history, meaning that forwards navigation is not possible, or if the current {{domxref("Document")}} is unloading. ## Examples ```js 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"); } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## 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/)
0
data/mdn-content/files/en-us/web/api/navigation
data/mdn-content/files/en-us/web/api/navigation/navigate/index.md
--- title: "Navigation: navigate() method" short-title: navigate() slug: Web/API/Navigation/navigate page-type: web-api-instance-method status: - experimental browser-compat: api.Navigation.navigate --- {{APIRef("Navigation API")}}{{SeeCompatTable}} The **`navigate()`** method of the {{domxref("Navigation")}} interface navigates to a specific URL, updating any provided state in the history entries list. ## Syntax ```js-nolint navigate(url) navigate(url, options) ``` ### Parameters - `url` - : The destination URL to navigate to. Note that when calling `navigate()` on a another window's `navigation` object, the URL will be resolved relative to the target window's URL, not the calling window's URL. This matches the behavior of the [History API](/en-US/docs/Web/API/History_API), but not the behavior of the [Location API](/en-US/docs/Web/API/Location). - `options` {{optional_inline}} - : An options object containing the following properties: - `state` {{optional_inline}} - : Developer-defined information to be stored in the associated {{domxref("NavigationHistoryEntry")}} once the navigation is complete, retrievable via {{domxref("NavigationHistoryEntry.getState", "getState()")}}. This can be any data type. You might, for example, wish to store a page visit count for analytics purposes, or store UI state details so the view can be shown exactly as the user last left it. Any data stored in `state` must be [structured-cloneable](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). - `info` {{optional_inline}} - : Developer-defined information to be passed along to the {{domxref("Navigation/navigate_event", "navigate")}} event, made available in {{domxref("NavigateEvent.info")}}. This can be any data type. You might, for example, wish to display newly-navigated content with a different animation depending on how it was navigated to (swipe left, swipe right, or go home). A string indicating which animation to use could be passed in as `info`. - `history` {{optional_inline}} - : An enumerated value that sets the history behavior of this navigation. The available values are: - `auto`: The default value; will usually perform a `push` navigation but will perform a `replace` navigation under special circumstances (see the `NotSupportedError` description below). - `push`: Will push a new {{domxref("NavigationHistoryEntry")}} onto the entries list, or fail under special circumstances (see the `NotSupportedError` description below). - `replace`: Will replace the current {{domxref("NavigationHistoryEntry")}}. ### Return value An object with the following properties: - `committed` - : A {{jsxref("Promise")}} which will fulfill when the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. - `finished` - : A {{jsxref("Promise")}} which will fulfill when all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. Either one of these promises rejects if the navigation has failed for some reason. ### Exceptions - `DataCloneError` {{domxref("DOMException")}} - : Thrown if the `state` parameter had values included in it that are not structured-cloneable. - `SyntaxError` {{domxref("DOMException")}} - : Thrown if the `url` parameter is not a valid URL. - `NotSupportedError` {{domxref("DOMException")}} - : Thrown if the `history` option is set to `push`, and any of the following special circumstances are true: - The browser is currently showing the initial `about:blank` document. - The `url`'s scheme is `javascript`. ## Examples ### Set up home button ```js 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. }, }); }); ``` ### A smart back button A page-supplied "back" button can take you back, even after reload, by inspecting the previous history entries: ```js backButtonEl.addEventListener("click", () => { if ( navigation.entries()[navigation.currentEntry.index - 1]?.url === "/product-listing" ) { navigation.back(); } else { // If the user arrived here in some other way // e.g. by typing the URL directly: navigation.navigate("/product-listing", { history: "replace" }); } }); ``` ### Using info and state ```js async function navigateHandler() { await navigation.navigate(url, { info: { animation: "swipe-right" }, state: { infoPaneOpen: true }, }).finished; // Update application state // ... } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## 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/)
0
data/mdn-content/files/en-us/web/api/navigation
data/mdn-content/files/en-us/web/api/navigation/cangoback/index.md
--- title: "Navigation: canGoBack property" short-title: canGoBack slug: Web/API/Navigation/canGoBack page-type: web-api-instance-property status: - experimental browser-compat: api.Navigation.canGoBack --- {{APIRef("Navigation API")}}{{SeeCompatTable}} The **`canGoBack`** read-only property of the {{domxref("Navigation")}} interface returns `true` if it is possible to navigate backwards in the navigation history (i.e. the {{domxref("Navigation.currentEntry", "currentEntry")}} is not the first one in the history entry list), and `false` if it is not. ## Value A boolean value: `true` if it is possible to navigate backwards in the navigation history, `false` otherwise. ## Examples ```js 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"); } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## 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/)
0
data/mdn-content/files/en-us/web/api/navigation
data/mdn-content/files/en-us/web/api/navigation/traverseto/index.md
--- title: "Navigation: traverseTo() method" short-title: traverseTo() slug: Web/API/Navigation/traverseTo page-type: web-api-instance-method status: - experimental browser-compat: api.Navigation.traverseTo --- {{APIRef("Navigation API")}}{{SeeCompatTable}} The **`traverseTo()`** method of the {{domxref("Navigation")}} interface navigates to the {{domxref("NavigationHistoryEntry")}} identified by the given {{domxref("NavigationHistoryEntry.key", "key")}}. ## Syntax ```js-nolint traverseTo(key) traverseTo(key, options) ``` ### Parameters - `key` - : The `key` of the {{domxref("NavigationHistoryEntry")}} to navigate to. - `options` {{optional_inline}} - : An options object containing the following properties: - `info` {{optional_inline}} - : Developer-defined information to be passed along to the {{domxref("Navigation/navigate_event", "navigate")}} event, made available in {{domxref("NavigateEvent.info")}}. This can be any data type. You might, for example, wish to display newly-navigated content with a different animation depending on how it was navigated to (swipe left, swipe right, or go home). A string indicating which animation to use could be passed in as `info`. ### Return value An object with the following properties: - `committed` - : A {{jsxref("Promise")}} which will fulfill when the visible URL has changed and a new {{domxref("NavigationHistoryEntry")}} has been created. - `finished` - : A {{jsxref("Promise")}} which will fulfill when all promises returned by the `intercept()` handler are fulfilled. This is equivalent to the {{domxref("NavigationTransition.finished")}} promise fulfilling, when the {{domxref("Navigation/navigatesuccess_event", "navigatesuccess")}} event fires. Either one of these promises rejects if the navigation has failed for some reason. ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the {{domxref("Navigation.currentEntry")}}'s {{domxref("NavigationHistoryEntry.index")}} value is -1, meaning the current {{domxref("Document")}} is not yet active, of if the navigation history list does not contain a {{domxref("NavigationHistoryEntry")}} with the specified key, or if the current {{domxref("Document")}} is unloading. ## Examples ### Set up home button ```js 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 {{Specifications}} ## Browser compatibility {{Compat}} ## 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/)
0
data/mdn-content/files/en-us/web/api/navigation
data/mdn-content/files/en-us/web/api/navigation/entries/index.md
--- title: "Navigation: entries() method" short-title: entries() slug: Web/API/Navigation/entries page-type: web-api-instance-method status: - experimental browser-compat: api.Navigation.entries --- {{APIRef("Navigation API")}}{{SeeCompatTable}} The **`entries()`** method of the {{domxref("Navigation")}} interface returns an array of {{domxref("NavigationHistoryEntry")}} objects representing all existing history entries. ## Syntax ```js-nolint entries() ``` ### Parameters None. ### Return value An array of {{domxref("NavigationHistoryEntry")}} objects. ### Exceptions None. ## Examples ### Return the number of entries in the history ```js let numOfEntries = navigation.entries().length - 1; ``` ### A smart back button A page-supplied "back" button can take you back, even after reload, by inspecting the previous history entries: ```js backButtonEl.addEventListener("click", () => { if ( navigation.entries()[navigation.currentEntry.index - 1]?.url === "/product-listing" ) { navigation.back(); } else { // If the user arrived here in some other way // e.g. by typing the URL directly: navigation.navigate("/product-listing", { history: "replace" }); } }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## 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/)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/hashchangeevent/index.md
--- title: HashChangeEvent slug: Web/API/HashChangeEvent page-type: web-api-interface browser-compat: api.HashChangeEvent --- {{APIRef("HTML DOM")}} 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. {{InheritanceDiagram}} ## Constructor - {{domxref("HashChangeEvent.HashChangeEvent", "HashChangeEvent()")}} - : Creates a new `HashChangeEvent` object. ## Instance properties _This interface also inherits the properties of its parent, {{domxref("Event")}}._ - {{domxref("HashChangeEvent.newURL")}} {{ReadOnlyInline}} - : The new URL to which the window is navigating. - {{domxref("HashChangeEvent.oldURL")}} {{ReadOnlyInline}} - : 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, {{domxref("Event")}}._ ## Examples ### Basic example ```js function locationHashChanged() { if (location.hash === "#somecoolfeature") { somecoolfeature(); } } window.addEventListener("hashchange", locationHashChanged); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## Related events - {{domxref("window.hashchange_event", "hashchange")}} - {{domxref("window.popstate_event", "popstate")}}
0
data/mdn-content/files/en-us/web/api/hashchangeevent
data/mdn-content/files/en-us/web/api/hashchangeevent/oldurl/index.md
--- title: "HashChangeEvent: oldURL property" short-title: oldURL slug: Web/API/HashChangeEvent/oldURL page-type: web-api-instance-property browser-compat: api.HashChangeEvent.oldURL --- {{APIRef("HTML DOM")}} The **`oldURL`** read-only property of the {{domxref("HashChangeEvent")}} interface returns the previous URL from which the window was navigated. ## Value A string. ## Examples ```js window.addEventListener("hashchange", (event) => { console.log(`Hash changed from ${event.oldURL}`); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/hashchangeevent
data/mdn-content/files/en-us/web/api/hashchangeevent/hashchangeevent/index.md
--- title: "HashChangeEvent: HashChangeEvent() constructor" short-title: HashChangeEvent() slug: Web/API/HashChangeEvent/HashChangeEvent page-type: web-api-constructor browser-compat: api.HashChangeEvent.HashChangeEvent --- {{APIRef("HTML DOM")}} The **`HashChangeEvent()`** constructor creates a new {{domxref("HashChangeEvent")}} object, that is used by the {{domxref("Window/hashchange_event", "hashchange")}} event fired at the {{domxref("window")}} object when the fragment of the URL changes. > **Note:** A web developer doesn't typically need to call this constructor, as the browser creates these objects itself when firing {{domxref("Window/hashchange_event", "hashchange")}} events. ## Syntax ```js-nolint new HashChangeEvent(type, options) ``` ### Parameters - `type` - : A string with the name of the event. It is case-sensitive and browsers set it to `hashchange`. - `options` {{optional_inline}} - : An object that, _in addition to the properties defined in {{domxref("Event/Event", "Event()")}}_, has the following properties: - `oldURL` {{optional_inline}} - : A string containing the old URL. Its default value is the empty string (`""`). - `newURL`{{optional_inline}} - : A string containing the new URL. Its default value is the empty string (`""`). ### Return value A new {{domxref("HashChangeEvent")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Window/hashchange_event", "hashchange")}} event
0
data/mdn-content/files/en-us/web/api/hashchangeevent
data/mdn-content/files/en-us/web/api/hashchangeevent/newurl/index.md
--- title: "HashChangeEvent: newURL property" short-title: newURL slug: Web/API/HashChangeEvent/newURL page-type: web-api-instance-property browser-compat: api.HashChangeEvent.newURL --- {{APIRef("HTML DOM")}} The **`newURL`** read-only property of the {{domxref("HashChangeEvent")}} interface returns the new URL to which the window is navigating. ## Value A string. ## Examples ```js window.addEventListener("hashchange", (event) => { console.log(`Hash changed to ${event.newURL}`); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/index.md
--- title: CanvasRenderingContext2D slug: Web/API/CanvasRenderingContext2D page-type: web-api-interface browser-compat: api.CanvasRenderingContext2D --- {{APIRef}} The **`CanvasRenderingContext2D`** interface, part of the [Canvas API](/en-US/docs/Web/API/Canvas_API), provides the 2D rendering context for the drawing surface of a {{HTMLElement("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](/en-US/docs/Web/API/Canvas_API/Tutorial) has more explanation, examples, and resources, as well. For [`OffscreenCanvas`](/en-US/docs/Web/API/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 {{domxref("OffscreenCanvasRenderingContext2D")}} reference page. ## Basic example To get a `CanvasRenderingContext2D` instance, you must first have an HTML `<canvas>` element to work with: ```html <canvas id="my-house" width="300" height="300"></canvas> ``` To get the canvas' 2D rendering context, call {{domxref("HTMLCanvasElement.getContext()", "getContext()")}} on the `<canvas>` element, supplying `'2d'` as the argument: ```js 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: ```js // 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: {{EmbedLiveSample("Basic_example", 700, 330)}} ## Reference ### Context - {{domxref("CanvasRenderingContext2D.isContextLost()")}} {{Experimental_Inline}} - : Returns `true` if the rendering context was lost. ### Drawing rectangles There are three methods that immediately draw rectangles to the canvas. - {{domxref("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. - {{domxref("CanvasRenderingContext2D.fillRect()")}} - : Draws a filled rectangle at _(x, y)_ position whose size is determined by _width_ and _height_. - {{domxref("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 {{domxref("TextMetrics")}} object for text properties. - {{domxref("CanvasRenderingContext2D.fillText()")}} - : Draws (fills) a given text at the given (x, y) position. - {{domxref("CanvasRenderingContext2D.strokeText()")}} - : Draws (strokes) a given text at the given (x, y) position. - {{domxref("CanvasRenderingContext2D.measureText()")}} - : Returns a {{domxref("TextMetrics")}} object. ### Line styles The following methods and properties control how lines are drawn. - {{domxref("CanvasRenderingContext2D.lineWidth")}} - : Width of lines. Default `1.0`. - {{domxref("CanvasRenderingContext2D.lineCap")}} - : Type of endings on the end of lines. Possible values: `butt` (default), `round`, `square`. - {{domxref("CanvasRenderingContext2D.lineJoin")}} - : Defines the type of corners where two lines meet. Possible values: `round`, `bevel`, `miter` (default). - {{domxref("CanvasRenderingContext2D.miterLimit")}} - : Miter limit ratio. Default `10`. - {{domxref("CanvasRenderingContext2D.getLineDash()")}} - : Returns the current line dash pattern array containing an even number of non-negative numbers. - {{domxref("CanvasRenderingContext2D.setLineDash()")}} - : Sets the current line dash pattern. - {{domxref("CanvasRenderingContext2D.lineDashOffset")}} - : Specifies where to start a dash array on a line. ### Text styles The following properties control how text is laid out. - {{domxref("CanvasRenderingContext2D.font")}} - : Font setting. Default value `"10px sans-serif"`. - {{domxref("CanvasRenderingContext2D.textAlign")}} - : Text alignment setting. Possible values: `start` (default), `end`, `left`, `right`, `center`. - {{domxref("CanvasRenderingContext2D.textBaseline")}} - : Baseline alignment setting. Possible values: `top`, `hanging`, `middle`, `alphabetic` (default), `ideographic`, `bottom`. - {{domxref("CanvasRenderingContext2D.direction")}} - : Directionality. Possible values: `ltr`, `rtl`, `inherit` (default). - {{domxref("CanvasRenderingContext2D.letterSpacing")}} - : Letter spacing. Default: `0px`. - {{domxref("CanvasRenderingContext2D.fontKerning")}} - : Font kerning. Possible values: `auto` (default), `normal`, `none`. - {{domxref("CanvasRenderingContext2D.fontStretch")}} - : Font stretch. Possible values: `ultra-condensed`, `extra-condensed`, `condensed`, `semi-condensed`, `normal` (default), `semi-expanded`, `expanded`, `extra-expanded`, `ultra-expanded`. - {{domxref("CanvasRenderingContext2D.fontVariantCaps")}} - : Font variant caps. Possible values: `normal` (default), `small-caps`, `all-small-caps`, `petite-caps`, `all-petite-caps`, `unicase`, `titling-caps`. - {{domxref("CanvasRenderingContext2D.textRendering")}} - : Text rendering. Possible values: `auto` (default), `optimizeSpeed`, `optimizeLegibility`, `geometricPrecision`. - {{domxref("CanvasRenderingContext2D.wordSpacing")}} - : 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. - {{domxref("CanvasRenderingContext2D.fillStyle")}} - : Color or style to use inside shapes. Default `#000` (black). - {{domxref("CanvasRenderingContext2D.strokeStyle")}} - : Color or style to use for the lines around shapes. Default `#000` (black). ### Gradients and patterns - {{domxref("CanvasRenderingContext2D.createConicGradient()")}} - : Creates a conic gradient around a point given by coordinates represented by the parameters. - {{domxref("CanvasRenderingContext2D.createLinearGradient()")}} - : Creates a linear gradient along the line given by the coordinates represented by the parameters. - {{domxref("CanvasRenderingContext2D.createRadialGradient()")}} - : Creates a radial gradient given by the coordinates of the two circles represented by the parameters. - {{domxref("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 {{domxref("CanvasPattern")}}. ### Shadows - {{domxref("CanvasRenderingContext2D.shadowBlur")}} - : Specifies the blurring effect. Default: `0`. - {{domxref("CanvasRenderingContext2D.shadowColor")}} - : Color of the shadow. Default: fully-transparent black. - {{domxref("CanvasRenderingContext2D.shadowOffsetX")}} - : Horizontal distance the shadow will be offset. Default: `0`. - {{domxref("CanvasRenderingContext2D.shadowOffsetY")}} - : Vertical distance the shadow will be offset. Default: `0`. ### Paths The following methods can be used to manipulate paths of objects. - {{domxref("CanvasRenderingContext2D.beginPath()")}} - : Starts a new path by emptying the list of sub-paths. Call this method when you want to create a new path. - {{domxref("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. - {{domxref("CanvasRenderingContext2D.moveTo()")}} - : Moves the starting point of a new sub-path to the (x, y) coordinates. - {{domxref("CanvasRenderingContext2D.lineTo()")}} - : Connects the last point in the current sub-path to the specified (x, y) coordinates with a straight line. - {{domxref("CanvasRenderingContext2D.bezierCurveTo()")}} - : Adds a cubic Bézier curve to the current path. - {{domxref("CanvasRenderingContext2D.quadraticCurveTo()")}} - : Adds a quadratic Bézier curve to the current path. - {{domxref("CanvasRenderingContext2D.arc()")}} - : Adds a circular arc to the current path. - {{domxref("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. - {{domxref("CanvasRenderingContext2D.ellipse()")}} - : Adds an elliptical arc to the current path. - {{domxref("CanvasRenderingContext2D.rect()")}} - : Creates a path for a rectangle at position (x, y) with a size that is determined by _width_ and _height_. - {{domxref("CanvasRenderingContext2D.roundRect()")}} - : Creates a path for a rounded rectangle with a specified position, width, height, and corner radii. ### Drawing paths - {{domxref("CanvasRenderingContext2D.fill()")}} - : Fills the current sub-paths with the current fill style. - {{domxref("CanvasRenderingContext2D.stroke()")}} - : Strokes the current sub-paths with the current stroke style. - {{domxref("CanvasRenderingContext2D.drawFocusIfNeeded()")}} - : If a given element is focused, this method draws a focus ring around the current path. - {{domxref("CanvasRenderingContext2D.scrollPathIntoView()")}} {{Experimental_Inline}} - : Scrolls the current path or a given path into the view. - {{domxref("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](/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing) in the Canvas tutorial. - {{domxref("CanvasRenderingContext2D.isPointInPath()")}} - : Reports whether or not the specified point is contained in the current path. - {{domxref("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 {{domxref("Path2D")}} objects. The methods listed below remain for historical and compatibility reasons as {{domxref("DOMMatrix")}} objects are used in most parts of the API nowadays and will be used in the future instead. - {{domxref("CanvasRenderingContext2D.getTransform()")}} - : Retrieves the current transformation matrix being applied to the context. - {{domxref("CanvasRenderingContext2D.rotate()")}} - : Adds a rotation to the transformation matrix. The angle argument represents a clockwise rotation angle and is expressed in radians. - {{domxref("CanvasRenderingContext2D.scale()")}} - : Adds a scaling transformation to the canvas units by x horizontally and by y vertically. - {{domxref("CanvasRenderingContext2D.translate()")}} - : Adds a translation transformation by moving the canvas and its origin x horizontally and y vertically on the grid. - {{domxref("CanvasRenderingContext2D.transform()")}} - : Multiplies the current transformation matrix with the matrix described by its arguments. - {{domxref("CanvasRenderingContext2D.setTransform()")}} - : Resets the current transform to the identity matrix, and then invokes the `transform()` method with the same arguments. - {{domxref("CanvasRenderingContext2D.resetTransform()")}} - : Resets the current transform by the identity matrix. ### Compositing - {{domxref("CanvasRenderingContext2D.globalAlpha")}} - : Alpha value that is applied to shapes and images before they are composited onto the canvas. Default `1.0` (opaque). - {{domxref("CanvasRenderingContext2D.globalCompositeOperation")}} - : With `globalAlpha` applied this sets how shapes and images are drawn onto the existing bitmap. ### Drawing images - {{domxref("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 {{domxref("ImageData")}} object. - {{domxref("CanvasRenderingContext2D.createImageData()")}} - : Creates a new, blank {{domxref("ImageData")}} object with the specified dimensions. All of the pixels in the new object are transparent black. - {{domxref("CanvasRenderingContext2D.getImageData()")}} - : Returns an {{domxref("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. - {{domxref("CanvasRenderingContext2D.putImageData()")}} - : Paints data from the given {{domxref("ImageData")}} object onto the bitmap. If a dirty rectangle is provided, only the pixels from that rectangle are painted. ### Image smoothing - {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}} - : Image smoothing mode; if disabled, images will not be smoothed if scaled. - {{domxref("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: - {{domxref("CanvasRenderingContext2D.save()")}} - : Saves the current drawing style state using a stack so you can revert any change you make to it using `restore()`. - {{domxref("CanvasRenderingContext2D.restore()")}} - : Restores the drawing style state to the last element on the 'state stack' saved by `save()`. - {{domxref("CanvasRenderingContext2D.canvas")}} - : A read-only back-reference to the {{domxref("HTMLCanvasElement")}}. Might be [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) if it is not associated with a {{HTMLElement("canvas")}} element. - {{domxref("CanvasRenderingContext2D.getContextAttributes()")}} - : Returns an object containing the context attributes used by the browser. Context attributes can be requested when using {{domxref("HTMLCanvasElement.getContext()")}} to create the 2D context. - {{domxref("CanvasRenderingContext2D.reset()")}} - : Resets the rendering context, including the backing buffer, the drawing state stack, path, and styles. - {{domxref("CanvasRenderingContext2D.isContextLost()")}} {{Experimental_Inline}} - : Returns `true` if the rendering context was lost. ### Filters - {{domxref("CanvasRenderingContext2D.filter")}} - : Applies a CSS or SVG filter to the canvas, e.g., to change its brightness or blurriness. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLCanvasElement")}} - {{HTMLElement("canvas")}} - {{domxref("OffscreenCanvas")}}
0
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d
data/mdn-content/files/en-us/web/api/canvasrenderingcontext2d/rotate/index.md
--- title: "CanvasRenderingContext2D: rotate() method" short-title: rotate() slug: Web/API/CanvasRenderingContext2D/rotate page-type: web-api-instance-method browser-compat: api.CanvasRenderingContext2D.rotate --- {{APIRef}} The **`CanvasRenderingContext2D.rotate()`** method of the Canvas 2D API adds a rotation to the transformation matrix. ## Syntax ```js-nolint rotate(angle) ``` ![Rectangular coordinate system with the rotation of the abscissa axis by the alpha angle](canvas_grid_rotate.png) ### Parameters - `angle` - : The rotation angle, clockwise in radians. You can use `degree * Math.PI / 180` to calculate a radian from a degree. The rotation center point is always the canvas origin. To change the center point, you will need to move the canvas by using the {{domxref("CanvasRenderingContext2D.translate", "translate()")}} method. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Rotating a shape This example rotates a rectangle by 45°. Note that the center of rotation is the top-left corner of the canvas, and not a location relative to any shape. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Point of transform origin ctx.arc(0, 0, 5, 0, 2 * Math.PI); ctx.fillStyle = "blue"; ctx.fill(); // Non-rotated rectangle ctx.fillStyle = "gray"; ctx.fillRect(100, 0, 80, 20); // Rotated rectangle ctx.rotate((45 * Math.PI) / 180); ctx.fillStyle = "red"; ctx.fillRect(100, 0, 80, 20); // Reset transformation matrix to the identity matrix ctx.setTransform(1, 0, 0, 1, 0, 0); ``` #### Result The center of rotation is blue. The non-rotated rectangle is gray, and the rotated rectangle is red. {{ EmbedLiveSample('Rotating_a_shape', 700, 180) }} ### Rotating a shape around its center This example rotates a shape around its center point. To do this, the following steps are applied to the matrix: 1. First, {{domxref("CanvasRenderingContext2D.translate()", "translate()")}} moves the matrix's origin to the shape's center. 2. `rotate()` rotates the matrix by the desired amount. 3. Finally, `translate()` moves the matrix's origin back to its starting point. This is done by applying the values of the shape's center coordinates in a negative direction. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript The shape is a rectangle with its corner at (80, 60), a width of 140, a height of 30. Its horizontal center is at (80 + 140 / 2), or 150. Its vertical center is at (60 + 30 / 2\), or 75. Thus, the center point is at (150, 75). ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Non-rotated rectangle ctx.fillStyle = "gray"; ctx.fillRect(80, 60, 140, 30); // Matrix transformation ctx.translate(150, 75); ctx.rotate(Math.PI / 2); ctx.translate(-150, -75); // Rotated rectangle ctx.fillStyle = "red"; ctx.fillRect(80, 60, 140, 30); ``` #### Result The non-rotated rectangle is gray, and the rotated rectangle is red. {{ EmbedLiveSample('Rotating_a_shape_around_its_center', 700, 180) }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The interface defining this method: {{domxref("CanvasRenderingContext2D")}}
0